ASP.NET Core 2授权属性jwt

时间:2018-03-11 01:36:16

标签: asp.net-core 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。只有当我将[授权]更改为[授权(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]时才有效。我不想为每个属性使用AuthenticationSchemes属性。谢谢

1 个答案:

答案 0 :(得分:5)

services.AddIdentity(…)设置ASP.NET核心身份,它使用Cookie身份验证注册多个Cookie身份验证方案,这些身份验证是基于表单的身份登录工作所必需的。

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

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

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承载的区域,那么它们将停止工作,并且需要显式Authenticate属性才能切换回Identity cookie。