首页 > 解决方案 > 未找到名为“Bearer”的 AuthorizationPolicy

问题描述

尝试将 Jwt 身份验证添加到我的 DotNetCore 2.1 服务器和 Angular 6 应用程序。

我看过很多关于这个话题的文章,似乎没有人会这样做,而且似乎也没有什么对我有用......我不知道出了什么问题......

我得到:'未找到名为:'Bearer' 的 AuthorizationPolicy。当我启动我的服务器...

服务

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
         options.TokenValidationParameters = new TokenValidationParameters
         {
             ValidateIssuer = true,
             ValidateAudience = true,
             ValidateLifetime = true,
             ValidateIssuerSigningKey = true,
             ValidIssuer = "http://localhost:54523",
             ValidAudience = "http://localhost:4300",
             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("tokensecret))
        };
   });

services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", builder =>
    {
        builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials()
            .Build();
    });
});

services.AddMvc();

配置

app.UseAuthentication();
app.UseCors("CorsPolicy");
app.UseMvc();

控制器

[Authorize()]
[Route("api/[controller]")]
public class ProjectController : Controller

如果我使用控制器 [Authorize],当用户未通过身份验证时,它会返回 /Account/Login?ReturnUrl=...

但它是 JWT,它应该只返回 401、403 ......

如果我尝试使用 [Authorize(JwtBearerDefaults.AuthenticationScheme)],我会得到“名为:'Bearer' 的 AuthorizationPolicy 未找到。”

但为什么...

编辑

我不知道那条线正在改变身份验证的行为,但我也使用这条线

serviceCollection.AddIdentity<User, Role>();

怎么了 ?我们不能将 Identity 与 JWT 一起使用?如何为 JWT 配置它?

标签: .net-corejwt

解决方案


好的,我找到了让它工作的方法......终于!

您需要使用 AddIdentityCore 而不是 AddIdentity。然后需要自己配置,添加AddIdentityCore中没有注册的missings服务。

链接到 AddIdentityCore 方法:https ://github.com/aspnet/Identity/blob/9b385180a9abcb264507efc23279f083bfc50520/src/Core/IdentityServiceCollectionExtensions.cs

身份注册码

        var builder = serviceCollection.AddIdentityCore<User>(opt =>
        {
            opt.Password.RequireDigit = true;
            opt.Password.RequiredLength = 8;
            opt.Password.RequireNonAlphanumeric = true;
            opt.Password.RequireUppercase = true;
            opt.Password.RequireLowercase = true;
        });

        builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
        builder.AddEntityFrameworkStores<AmiliaContext>();
        builder.AddDefaultTokenProviders();

        builder.AddRoleValidator<RoleValidator<Role>>();
        builder.AddRoleManager<RoleManager<Role>>();
        builder.AddSignInManager<SignInManager<User>>();

        serviceCollection.AddDependencies(Assembly.GetExecutingAssembly());

附加说明

用户必须继承 IdentityUser 角色必须继承 IdentityRole

您不能使用 SignInManager 中的 SignInAsync,而需要使用 CheckPasswordSignInAsync。

为什么 ?

因为 SignInAsync 在内部使用 cookie,所以我们不能在 JWT 中使用这种方法。


推荐阅读