ASP.NET核心2授权属性jwt

ASP.NET Core 2 Authorize attribute jwt

请告诉我为什么这段代码不起作用。

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

    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)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = AuthOptions.ISSUER,
                ValidateAudience = true,
                ValidAudience = AuthOptions.AUDIENCE,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey()
            };
        });

        services.AddDbContext<ApplicationContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddIdentity<User, IdentityRole>().AddEntityFrameworkStores<ApplicationContext>();
        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)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action}/{id?}",
                defaults: new { controller = "Home", action = "Index" });
        });
    }
}

我尝试删除 options.Default* 并将其替换为仅 JwtBearerDefaults.AuthenticationScheme。只有当我将 [Authorize] 更改为 [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] 时它才有效。但我不想对每个属性使用 AuthenticationSchemes 属性。

services.AddIdentity(…) 设置 ASP.NET Core Identity,它使用 form-based 身份登录所需的 Cookie 身份验证注册多个 Cookie 身份验证方案。

作为其中的一部分,它还将默认身份验证和质询方案设置为 IdentityConstants.ApplicationScheme

由于您在 AddAuthentication之后调用了AddIdentity ,您为后者所做的默认配置将被身份配置覆盖。因此,要解决您的问题,您必须确保在身份选项中设置默认方案 after registering Identity.

services.AddIdentity<User, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationContext>();;

services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
})
    .AddJwtBearer(…);

请注意,这将 显然 停止将 ASP.NET 核心身份的身份验证 cookie 作为默认身份验证和质询方案。因此,如果您的应用程序 有您未使用 JWT Bearer 的区域,那么这些区域将停止工作并且需要明确的 Authenticate 属性才能切换回身份 cookie。