Search code examples
asp.net-identityasp.net-core-webapiasp.net-authorization

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


I need to combine token and cookies for authorizing requests in wepapi project. I have added Cookies and Jwt for authenticating requests. Before changing DefaultPolicy, I can get my claims(/info), But after changing i get 401.

Here is my Program.cs codes:

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();

And controller codes:

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();
        }
    }
}

Is there any solution?


Solution

  • The problem is when you signin with signInManager it will add Identity.Application not cookies.

    enter image description here

    Solution:

    builder.Services.AddAuthentication()
    .AddCookie()
    .AddJwtBearer("Bearer", options => { });
    
    var policy = new AuthorizationPolicyBuilder("Identity.Application", "Bearer")
    .RequireAuthenticatedUser().Build();
    builder.Services.AddAuthorization(m => m.DefaultPolicy = policy);
    

    replace CookieAuthenticationDefaults.AuthenticationScheme with Identity.Application when building you policy.