MIP1983
MIP1983

Reputation: 1374

Authentication handler not being hit (.NET Core 2.1 MVC)

My application has multiple authentication handlers configured in startup:

services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })                
            .AddCookie()
            .AddOpenIdConnect(options =>
            {
                ...
            })
            .AddApiKeyAuth();  

The openid connect auth is working fine, however I want for one specific controller to use the 'ApiKeyAuth' I've defined. So as per the docs:

https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-2.1&tabs=aspnetcore2x

I have specified the authentication scheme I want this controller to use:

[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = ApiKeyAuthHandler.SchemeName)]
public class MyApiController : ControllerBase

However, the app just seems to ignore this and the openId connect handler seems to be kicking in.

What am I missing, why is it ignoring my attribute?

Upvotes: 0

Views: 664

Answers (1)

MIP1983
MIP1983

Reputation: 1374

Ok, I've found that having a global auth policy was causing the issue. I removed the lines below and added an Auth attribute manually to all my controllers (while just specifying the alternate auth scheme on my other controller), and it's now behaving as I want.

services.AddMvc(config =>
        {
            Remove--> var policy = new AuthorizationPolicyBuilder()
                 .RequireAuthenticatedUser()
                 .Build();

            Remove --> config.Filters.Add(new AuthorizeFilter(policy));
        });

Upvotes: 1

Related Questions