Home » c# » c# – Different type of authentication for the same controller

c# – Different type of authentication for the same controller

Posted by: admin February 21, 2020 Leave a comment

Questions:

I have WEB API CORE 3.0 back-end application. Its controllers are protected with Azure AD.
For this I Use microsoft identity web library.

In the source code I configure it like this:

        public void ConfigureServices(IServiceCollection services)
        {
            Trace.TraceInformation("Configuring services");
        services.AddProtectedWebApi(Configuration, subscribeToJwtBearerMiddlewareDiagnosticsEvents: true)
            .AddProtectedApiCallsWebApis(Configuration)
            .AddInMemoryTokenCaches();
...

And to protect controller I use [Authorize].

Everything works perfect.

Now I want to add the second way to authorize users (along with Azure AD).
I want that users be able to login either with Azure AD or, say, JWT.

Is it possible to implement it for the same controller?

How to&Answers:

Is it possible to change the existing authorizing mechanism to allow non-AzureAD users to use the controller.

Sounds like you’re trying to make the [Authorize] to allow multiple authentication scheme at the same time. If that’s the case, you should firstly register those authentication scheme with AddAuthentication().AddMyScheme1().AddMyScheme2()...:

services.AddAuthentication()
    .AddAzureAD(options => Configuration.Bind("AzureAd", options));
    .AddJwtBearer(otps=>{
        otps.TokenValidationParameters = new TokenValidationParameters{ ...};
    });

And then change the default Authorization Policy to authenticate those authentication schemes at the same time. For example, if you want to allow Identity/JwtBearer/AzureAd at the same time, you could do it in following way

services.AddAuthorization(opts =>{
    opts.DefaultPolicy = new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(
            IdentityConstants.ApplicationScheme     // ASP.NET Core Identity Authentication
            ,JwtBearerDefaults.AuthenticationScheme // JwtBearer Authentication
            // ,"AzureAD"                           // AzureAd Authentication
        )
        .RequireAuthenticatedUser()
        .Build();
});

Or if you want to allow only specific user/Role further, feel free to custom it by :

opts.DefaultPolicy = new AuthorizationPolicyBuilder()
    .AddAuthenticationSchemes(
        IdentityConstants.ApplicationScheme     // ASP.NET Core Identity Authentication
        ,JwtBearerDefaults.AuthenticationScheme // JwtBearer Authentication
        // ,"AzureAD"                           // AzureAd Authentication
    )
    .RequireAuthenticatedUser()
    .RequireRole(...)
    .RequireAssertion(ctx =>{
        ...
        return true_or_false;
    })
    .Build();