Mubarak Imam
Mubarak Imam

Reputation: 43

Cookie Authentication not working with Authorization policy in asp.net core

Upgrading Scott Wildermuth's World Trip app to ASP.NET Core 2.0. The code below is not working.

Since I am using two authentication types and I would like both to work on the api controllers, I decided to use an Authorization policy.

public void ConfigureServices(IServiceCollection services)
{
   //Some code here
   services.AddAuthentication()
       .AddCookie()
       .AddJwtBearer(/*Implementation is fine*/);

   services.AddAuthorization(options =>
   {
       options.AddPolicy("Authenticated", policy =>
       {
           policy.AddAuthenticationSchemes(
               CookieAuthenticationDefaults.AuthenticationScheme,
               JwtBearerDefaults.AuthenticationScheme)
                   .RequireAuthenticatedUser();
       });
   });
}

Now in my controllers,

namespace TheWorld.Controllers.Api
{
    [Route("api/trips")]
    [Authorize(policy: "Authenticated")]
    public class TripsController : controller
    {
      // Implementation is fine
    }
}

Requests coming from client (web) with cookie authentication is never seen as authenticated while requests from Jwt authenticated clients work as expected.

It only works with cookie authentication if I use the simple [Authorize] on the controller, in which asp.net core just chooses the default cookie authentication and never accepts requests from Jwt Clients.

Upvotes: 0

Views: 3894

Answers (1)

poke
poke

Reputation: 387647

policy.AddAuthenticationSchemes(scheme1, scheme2)

This means that in order for the policy authentication to be successful, both specified authentication schemes must succeed.

Your two authentication schemes are likely set up so that when the JWT authentication succeeds, it would automatically succeed the cookie authentication (to set the cookie in that case, so on further requests the JWT token is no longer necessary but the cookie is enough). So when the JWT authentication is successful, the cookie authentication is also successful. However, the reverse is not true: If you’re only using the cookie to establish the authentication, then the JWT token may not be there at all.

If you do not care about which authentication scheme provided the authentication, you should just remove the AddAuthenticationSchemes call. By saying policy.RequireAuthenticatedUser() you are basically saying that there needs to be some authentication scheme that successfully authenticated the user.

This is btw. the exact same behavior, the default policy (with just [Authorize]) has.

Upvotes: 2

Related Questions