Asp.Net Core Use Cookie Authorization and JWT Auth

2020-06-28 01:26发布

问题:

I am facing a problem which I cannot seem to solve in my application. Right now I am using cookie authorization for the MVC part of my application and JWT Tokens for the Api. So far so good, everything works like expected; I am able to authorize my MVC controllers with the cookie authorization scheme and I am able to authorize my API with JWT authorization scheme.

But here is the problem: My views make Ajax requests to get some data from my Api. Every time a request is made, it gives me a not authorized error. This happens since the Api uses the JWT scheme. What is the best solution to go form here? Do I need to create a JWT token locally, save it in a separate cookie and then setting the authorization header before I send the request? Like so:

// Attatch token to all requests
$(document).ajaxSend(function (event, xhr, options) {
    xhr.setRequestHeader('Authorization', 'Bearer ' + '@Request.Cookies["Token"].Value');
});

Or would I set the authorization scheme to JWT and cookies for the Api controllers?


Startup.cs:

services.AddAuthentication()
    .AddCookie()
    .AddJwtBearer(cfg =>
    {
        cfg.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidIssuer = _configuration["Tokens:Issuer"],
            ValidAudience = _configuration["Tokens:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]))
        };
    });

Edit:

According to the Microsoft article, I am supposed to do it like this:

[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme + "," + JwtBearerDefaults.AuthenticationScheme)]

It still shows a 401 error if I send an Ajax request from my view. It does work when I send a request from Postman with the JWT token included.

I found out that if I set only the JWT bearer scheme, the scheme get applied correctly and works as expected for JWT tokens:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

But for the Cookie authentication it only works when I don't specify any scheme at all, like this:

[Authorize]

Doing this doesn't work:

[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]

JwtBearerDefaults