Cookie身份验证无法与JWT身份验证ASP.NET CORE一起正常使用

时间:2020-01-15 06:25:38

标签: asp.net-core cookies jwt asp.net-identity identity

我正在练习使用ASP.NET CORE编写Web应用程序,但遇到了Identity的问题。我试着在网上搜索,看看别人是否有这样的问题,无济于事。

我建立了一个简单的Web api,它使用JWT进行身份验证,并且一切运行正常。但是我还需要使用户能够使用表单(即Cookie身份验证)登录。以下是我的配置服务方法。

private static void ConfigureJwt(IConfiguration configuration, IServiceCollection services)
        {
            services.AddSingleton<JwtSettings>();
            services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddCookie( conf =>
                {
                    conf.SlidingExpiration = true;
                    conf.LoginPath = "/account/login";
                    conf.LogoutPath = "/account/logout";
                })
                .AddJwtBearer(options =>
                {
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey =
                            new SymmetricSecurityKey(Encoding.ASCII.GetBytes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")),
                        ValidateAudience = false,
                        ValidateIssuer = false,
                        RequireExpirationTime = false,
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.Zero,
                        ValidateActor = true

                    };
                });
        }

因此,由于DefaultChallengeScheme设置为“ JwtBearerDefaults.AuthenticationScheme”,所以我假设,如果我想授权使用cookie身份验证登录的用户,我应该只在如下所示的特定控制器方法中指定cookie身份验证方案

[Route("[controller]/[action]")]
    [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
    public class HomeController : Controller
    {
        // GET
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }
    }

但是我总是被重定向到登录页面。

唯一可行的方法是删除默认身份验证设置

private static void ConfigureJwt(IConfiguration configuration, IServiceCollection services)
        {
            var jwtSettings = new JwtSettings();
            configuration.Bind(nameof(JwtSettings), jwtSettings);
            services.AddSingleton<JwtSettings>();
            services.AddAuthentication()
                .AddCookie( conf =>
                {
                    conf.SlidingExpiration = true;
                    conf.LoginPath = "/account/login";
                    conf.LogoutPath = "/account/logout";
                })
                .AddJwtBearer("jwt", options =>
                {
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey =
                            new SymmetricSecurityKey(Encoding.ASCII.GetBytes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")),
                        ValidateAudience = false,
                        ValidateIssuer = false,
                        RequireExpirationTime = false,
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.Zero,
                        ValidateActor = true

                    };
                });
        }

然后在与Cookie相关的路由上使用常规的[Authorize]属性

[Route("[controller]/[action]")]
    [Authorize]
    public class HomeController : Controller
    {
        // GET
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }
    }

然后在我所有的API路由中,我指定了JWT的身份验证方案

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
        [HttpGet(ApiRoutes.Posts.GetAll)]
        public async Task<IActionResult> GetAll()
        {
            var posts = await _postService.GetAllAsync();
            return Ok(posts);
        }

所以我的问题是,为什么初始配置不起作用?而且由于我的应用程序主要是JWT使用身份验证,因此我希望它成为默认身份验证方案,并且仅在很少的控制器方法中指定cookie身份验证方案,因为它很少使用。这可能吗?如果是,我该如何实现?

1 个答案:

答案 0 :(得分:0)

经过进一步的挖掘,我偶然发现了这个thread,它回答了我的问题。

我误解了身份验证在使用身份的asp.net核心应用程序中的工作方式。 当您使用身份验证用户身份并登录时,使用的默认身份验证方案称为“ Identity.Applicaiton”,而不是“ Cookies”。

var result = await _signInManager.PasswordSignInAsync(loginModel.Email, loginModel.Password, true, false);

                if (result.Succeeded)
                {
                    return LocalRedirect("/home/index");
                }

但是,如果要使用“ Cookies”身份验证方案,则必须使用HttpContext.SignInAsync进行身份验证和登录,如下所示,并明确选择“ Cookies”作为身份验证方案。

var claims = new[]
                {
                    new Claim("email", user.Email),
                };
                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(identity));