ASP.NET Core Invoke an Authentication

745 Views Asked by At

My Problem: Find a way to Authorize a User if need be with BasicAuth if it is set in the DB for the specific Controller/Action, before JWT Authentication is used.

I am searching for a way to call two different AuthenticationHandlers from a custom AuthenticationHandler, is this even possible or maybe I am approaching the problem wrong?

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        //Get the Controller/Action from this.OriginalPath            
        //Ask the DB if the Controller/Action should be authorize using
        //BasicAuth first or just use JWT
        //Call the Basic or JWT Handler
    }
1

There are 1 best solutions below

0
Janik Sachs On

This is the best Solution I found so far:

        if (AuthType.StartsWith("Basic"))
        {
            var handlers = Context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
            var handler = handlers.GetHandlerAsync(Context, BasicAuthenticationDefaults.AuthenticationScheme).Result;
            var res = handler.AuthenticateAsync().Result;
            Debug.WriteLine(res.Succeeded);
            if (res.Succeeded)                
                return Task.FromResult(res);

        }
        else if(AuthType.StartsWith("Bearer"))
        {
            var handlers = Context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
            var handler = handlers.GetHandlerAsync(Context, JwtBearerDefaults.AuthenticationScheme).Result;
            var res = handler.AuthenticateAsync().Result;
            Debug.WriteLine(res.Succeeded);
            if (res.Succeeded)
                return Task.FromResult(res);
        }

It is not working with WindowsAuthentication. I only get an Error saying:

No authentication handler is configured to authenticate for the scheme: Windows

But I added IISDefaults

services.AddAuthentication(IISDefaults.AuthenticationScheme)

Pls feel free to comment or Edit.