JSON web令牌和cookie身份验证同时进行

时间:2017-12-04 08:44:00

标签: json authentication cookies asp.net-core

我有一个带有cookie和JWT身份验证的Web应用程序。该站点使用cookie架构,web api - JWT架构。并且有一个控制器,它需要两种类型(如果请求有'Bearer'标题 - JWT,否则 - cookie,但只有cookie可用。这是ConfigureServices和Configure方法:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddOptions();
        services.AddCommonLogger();
        services.AddAutoMapper();

        services.AddDatabase(Configuration);
        services.AddLogicUnits();
        services.AddFrontendLogic(Configuration);
        services.ConfigureSettings(Configuration);
        services.AddCommonServices();

        var authTokenSettings = Configuration.GetSection(nameof(TokenProviderSettings)).Get<TokenProviderSettings>();
        services.AddAuthentication()
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, u =>
                {
                    u.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = authTokenSettings.Issuer,
                        ValidAudience = authTokenSettings.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(authTokenSettings.Key))
                    };
                })
                .AddCookie("CookieAuthScheme", cfg => cfg.SlidingExpiration = true);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, UnhandledExceptionLoggerProvider provider)
    {
        loggerFactory.AddNLog();
        loggerFactory.AddProvider(provider);
        app.AddNLogWeb();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvcWithDefaultRoute();
    }

如果我像这样设置AuthenticationScremes

[Authorize(AuthenticationSchemes = "Bearer,CookieAuthScheme")]
    public async Task<IActionResult> MyRecords()
    { // Do some work...}

我获得了http 404,如果我使用空[Authorise]属性,则使用cookie身份验证。

如果我删除.AddCookie("CookieAuthScheme", cfg => cfg.SlidingExpiration = true);,则使用基于JWT的身份验证并且工作正常。我做错了什么?

0 个答案:

没有答案