C# InvalidOperationException:名为&x27的授权策略;持票人';找不到

C# InvalidOperationException:名为&x27的授权策略;持票人';找不到,c#,authorization,asp.net-core-2.0,bearer-token,C#,Authorization,Asp.net Core 2.0,Bearer Token,我目前正在尝试学习如何使用承载令牌构建一个安全的api,我一直遇到这个错误(InvalidOperationException:未找到名为“Bearner”的授权策略),我不知道为什么。我正在使用asp.net-core 2.0并尝试使用jwt auth中间件。 这是我的创业课程,任何帮助都将不胜感激 public class Startup { public Startup(IConfiguration configuration) { Configuratio

我目前正在尝试学习如何使用承载令牌构建一个安全的api,我一直遇到这个错误(InvalidOperationException:未找到名为“Bearner”的授权策略),我不知道为什么。我正在使用asp.net-core 2.0并尝试使用jwt auth中间件。 这是我的创业课程,任何帮助都将不胜感激

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    const string TokenAudience = "ExampleAudience";
    const string TokenIssuer = "ExampleIssuer";
    private RsaSecurityKey key;
    private TokenAuthOptions tokenOptions;

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        var keyParams = RSAKeyUtils.GetRandomKey();
        key = new RsaSecurityKey(keyParams);

        tokenOptions = new TokenAuthOptions()
        {
            Audience = TokenAudience,
            Issuer = TokenIssuer,
            SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
        };

        services.AddDbContext<VulnerabilityContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddScoped<LoggingActionFilter>();
        services.AddScoped<VulnsService>();

        services.AddAuthentication(o =>
        {
            o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(o =>
        {
            o.Authority = "https://localhost:54302";
            o.Audience = tokenOptions.Audience;
            o.RequireHttpsMetadata = false;
        });

        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        //app.UseSession();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseAuthentication();

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
const string TokenAudience=“ExampleAccession”;
const-string-TokenIssuer=“exampleisuer”;
私钥;
私人代币期权;
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
var keyParams=RSAKeyUtils.GetRandomKey();
key=新的RsaSecurityKey(keyParams);
tokenOptions=新的TokenAuthOptions()
{
观众=观众,
发行人=代币发行人,
SigningCredentials=新的SigningCredentials(密钥、SecurityAlgorithms.rsasa256Signature)
};
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
services.addScope();
services.addScope();
services.AddAuthentication(o=>
{
o、 DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
o、 DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o=>
{
o、 权威=”https://localhost:54302";
o、 观众=选项。观众;
o、 RequireHttpsMetadata=false;
});
services.AddMvc();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
//app.UseSession();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
}
}

出现此错误是因为身份验证方案和授权策略不是一回事。让我们看看每一个都是什么

认证方案 它们是应用程序中不同的身份验证方法。在您发布的代码中,您有一个由您指定的名称和选项标识的身份验证方案

可以在一个应用程序中设置多个身份验证方案:

  • 您可以使用cookie或JWT承载令牌对用户进行身份验证
  • 您甚至可以接受来自不同来源的JWT令牌;在这种情况下,需要调用
    AddJwtBearer
    方法两次。还需要注意的是,身份验证方案的名称应该是唯一的,因此您需要使用
授权策略 当用户在应用程序中经过身份验证时,并不意味着它可以访问其中的每个功能。您可能有不同的访问级别,管理员拥有其他人没有的特殊权限;这在ASP.NET核心中使用授权策略表示。我强烈建议你读这本书,因为我认为它很棒

授权策略由两部分组成:

  • 唯一的名字
  • 一套要求
以上面提到的管理员为例,我们可以创建一个虚构的授权策略:

  • 名称:
    管理员
  • 要求:必须经过身份验证,并且具有
    角色
    声明和
    管理员
这可以用代码表示:

services.AddAuthorization(选项=>
{
options.AddPolicy(“管理员”,新授权PolicyBuilder()
.RequireAuthenticatedUser()文件
.Require(“角色”、“管理员”)
.Build());
});
然后,您可以通过使用
[Authorize(policy=“Administrators”)]
属性对应用程序中的某些特定控制器或操作应用此策略。然后,在请求期间,MVC将针对当前用户运行需求,并确定他们是否可以访问特定功能

我的猜测是,您在一个操作/控制器上添加了这样的属性,但您没有在授权系统中注册授权策略名称
Bearer


如果您的目标是阻止未经身份验证的用户访问某些操作,则可以应用
[Authorize]
属性。这样做将运行,默认情况下,只需要对用户进行身份验证。

我没有使用策略,当我忘记在authorize属性中指示角色时,发生了此错误

我有这个:

[Authorize("Administrator")] // if you don't specify the property name Roles it will consider it as the policy name
通过将其更改为:

[Authorize(Roles = "Administrator")]

AuthenticationSchemes
添加到控制器类对我很有用:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]