7

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.

LuccasMF
  • 413
  • 5
  • 15

1 Answers1

8

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]

x5657
  • 1,172
  • 2
  • 13
  • 26
LuccasMF
  • 413
  • 5
  • 15