Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Mixing Cookie Auth and JWT auth in same controller (dual auth)

$
0
0

Hi

I'm working on an ASP Core 2.0 project that contains in the same controller both API actions returning JSON and actions returning views for simplicity.

I implemented the dual auth considering the following blog :

https://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2

It works, but because of my mixing API/actions for views in the same controller, If I have such a controller :

[Authorize]
public class AccountController : Controller
{

...



[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

public IActionResult Get()
{
return Ok(new[] { "One", "Two", "Three" });
}

}

then the Get Action needs both a Cookie Auth and a JWT bearer token auth to be authorized.

I would like to separate :

Autorize with cookies for actions for views and JWT bearer auth for API, not a cumulative auth.

Here is my startup.cs code (method ConfigureServices):

// Enable Dual Authentication
services.AddAuthentication()
.AddCookie(cfg => cfg.SlidingExpiration = true)
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;

cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = Configuration["Tokens:Issuer"],
ValidAudience = Configuration["Tokens:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
};

});



I managed to make it work separately if I don't use the Authorize globally on the Controller, but on each Action instead.

But I would like to find a way to keep my [Authorize] globally and specify for each needed API actions the JWT bearer auth [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] and only it.

Is there a way to do this ?

Many thanks


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>