Search code examples
authentication.net-coreauthorizationpolicy

Seting a Default Authorization Policy on multiple policies scenario


I'm setting 2 possible Policies for my application

services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser().Build());

                auth.AddPolicy("apiKey", policy =>
                    policy.Requirements.Add(new ApiKeyRequirement()));
            });

It makes mandatory to use [Authorize(Policy="Bearer")] or [Authorize(Policy="ApiKey")] when calling my controllers.

Is there any way to set one of them as the Default, then, when I want to use it, I'm able to use just [Authorize] and if I want to use the other one, I specify it?

E.g:

Setting the "Bearer" as default, then, when using a Bearer scheme I just need to set [Authorize], but if I want to use the "ApiKey", I specify it by using [Authorize(Policy="ApiKey")]

Couldn't find any example.


Solution

  • The DefaultPolicy property lets you set the Default:

    services.AddAuthorization(auth =>
                {
                    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                        .RequireAuthenticatedUser().Build());
    
                    auth.AddPolicy("apiKey", policy =>
                        policy.Requirements.Add(new ApiKeyRequirement()));
    
                    auth.DefaultPolicy = auth.GetPolicy("Bearer");
                });
    

    in this case, when I want to use the "Bearer" scheme, I just need to use [Authorization]