Asp.net core Cookie身份验证无法与JWT身份验证ASP.NET核心一起正常工作

Asp.net core Cookie身份验证无法与JWT身份验证ASP.NET核心一起正常工作,asp.net-core,cookies,jwt,asp.net-identity,identity,Asp.net Core,Cookies,Jwt,Asp.net Identity,Identity,我正在练习使用ASP.NET CORE编写web应用程序,我遇到了一个身份问题。我试着在网上搜索,看看是否有其他人有过这样的问题,但没有结果 我已经构建了一个简单的web api,它使用JWT进行身份验证,并且一切工作都非常完美。但我还需要允许用户使用表单登录,即cookie身份验证。以下是我的配置服务方法 private static void ConfigureJwt(IConfiguration configuration, IServiceCollection services)

我正在练习使用ASP.NET CORE编写web应用程序,我遇到了一个身份问题。我试着在网上搜索,看看是否有其他人有过这样的问题,但没有结果

我已经构建了一个简单的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

                    };
                });
        }
但我总是被重定向到登录页面

我实现这一点的唯一方法是删除默认身份验证设置

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

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

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
        [HttpGet(ApiRoutes.Posts.GetAll)]
        public async Task<IActionResult> GetAll()
        {
            var posts = await _postService.GetAllAsync();
            return Ok(posts);
        }
[授权(AuthenticationSchemes=JwtBearerDefaults.AuthenticationScheme)]
[HttpGet(apirouts.Posts.GetAll)]
公共异步任务GetAll()
{
var posts=wait_postService.GetAllAsync();
返回Ok(posts);
}

所以我的问题是,为什么初始配置不起作用?由于我的应用程序主要使用JWT身份验证,我希望它是默认的身份验证方案,并且只在少数控制器方法中指定cookie身份验证方案,因为它很少使用。这可能吗?如果是,我怎样才能做到这一点呢?

经过更多的挖掘,我偶然发现了这个问题,这回答了我的问题

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

但是,如果您想使用“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));
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
        [HttpGet(ApiRoutes.Posts.GetAll)]
        public async Task<IActionResult> GetAll()
        {
            var posts = await _postService.GetAllAsync();
            return Ok(posts);
        }
var result = await _signInManager.PasswordSignInAsync(loginModel.Email, loginModel.Password, true, false);

                if (result.Succeeded)
                {
                    return LocalRedirect("/home/index");
                }
var claims = new[]
                {
                    new Claim("email", user.Email),
                };
                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(identity));