当我在 ASP.NET 中组合 Bearer Token 和 Cookie 身份验证时,我得到 401

I get 401, When I Combined Bearer Token and Cookie Authentication in ASP.NET

我需要结合token 和cookie 来授权wepapi 项目中的请求。 我添加了 Cookies 和 Jwt 来验证请求。 在更改 DefaultPolicy 之前,我可以得到我的 claims(/info),但是在更改之后我得到 401.

这是我的 Program.cs 代码:

builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);

builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
    {
        options.Authority = "https://localhost:7208/";
        options.TokenValidationParameters.ValidateAudience = false;
        options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
    });

var multiSchemePolicy = new AuthorizationPolicyBuilder(
        CookieAuthenticationDefaults.AuthenticationScheme,
        JwtBearerDefaults.AuthenticationScheme)
    .RequireAuthenticatedUser()
    .Build();

builder.Services.AddAuthorization(o =>
{
    o.DefaultPolicy = multiSchemePolicy;
});

var app = builder.Build();


app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

和控制器代码:

namespace Whois.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class AccountController : ControllerBase
    {
        [HttpGet("info")]
        [Authorize]
        public IActionResult Info()
        {
            return Ok(User.Claims.Select(m => m.Value));
        }
        [HttpPost("login")]
        public async Task<IActionResult> Login()
        {
            var user = _userManager.Users.FirstOrDefault();

            await _signInManager.SignInAsync(user, new AuthenticationProperties() { });
            return Ok();
        }
    }
}

有什么解决办法吗?

问题是当您使用 signInManager 登录时,它会添加 Identity.Application 而不是 cookie。

解决方案:

builder.Services.AddAuthentication()
.AddCookie()
.AddJwtBearer("Bearer", options => { });

var policy = new AuthorizationPolicyBuilder("Identity.Application", "Bearer")
.RequireAuthenticatedUser().Build();
builder.Services.AddAuthorization(m => m.DefaultPolicy = policy);

在构建策略时将 CookieAuthenticationDefaults.AuthenticationScheme 替换为 Identity.Application。