【问题标题】:The AuthorizationPolicy named: 'Bearer' was not found未找到名为“Bearer”的 AuthorizationPolicy
【发布时间】:2019-03-12 14:33:52
【问题描述】:

尝试将 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-core jwt


    【解决方案1】:

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

    您需要使用 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 中使用此方法。

    【讨论】:

      猜你喜欢
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 2022-01-22
      • 2022-11-22
      相关资源
      最近更新 更多