0
votes

I have an ASP.NET Core 2.2 MVC Application with a web API. I'm using cookie auth for MVC pages and JWT Bearer auth for API. I followed the solution described How can i implement Cookie base authentication and jwt in asp.net core 2.2? which is based on https://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2

The trouble comes when I want to add an authorization policy to ensure the entire site is available to authenticated users

services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            }) 

When I do this, the JWT Bearer authentication is ignored even though the atrribute [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] is present. Thus accessing these API controllers returns a redirect to the login page.

How could I enable the authorization policy and still maintain both forms of authentication? A workaround is to add [Authorize] attribute to all controllers

2

2 Answers

0
votes

You can combine the jwt bearer schema and asp.net identity authentication schema when building AuthorizationPolicy :

var policy = new  AuthorizationPolicyBuilder(new[] { JwtBearerDefaults.AuthenticationScheme, IdentityConstants.ApplicationScheme })
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));

So that both authenticated by asp.net identity and JWT token authentication could access your protected actions .

0
votes

It seems like it is a known issue in the .Net core. I am using .NET Core 3.1 and it is still not resolved.

Here is my workaround:

 var principal = context.User;
        if (!principal.Identity.IsAuthenticated)
        {
            return Task.FromResult(0);  //user not logged in
        }