Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Branching ASP.NET Core Pipeline Authentication

My application is currently using Basic authentication but I want to transition to OAuth, so there will be a short period where both types of authentication need to be used. Is there some way to branch my ASP.NET Core pipeline like so:

public void Configure(IApplicationBuilder application)
{
    application
        .Use((context, next) =>
        {
            if (context.Request.Headers.ContainsKey("Basic"))
            {
                // Basic
            }
            else if (context.Request.Headers.ContainsKey("Authorization"))
            {
                // OAuth
            }

            return next();
        })
        .UseStaticFiles()
        .UseMvc();
}

So above, I am using basic authentication if I detect the HTTP header, otherwise I use OAuth.

like image 613
Muhammad Rehan Saeed Avatar asked Sep 15 '25 16:09

Muhammad Rehan Saeed


1 Answers

Technically you can use UseWhen like this:

app.UseWhen(context => context.Request.Headers.ContainsKey("Basic"), appBuilder =>
{
    // use basic middleware
} 
app.UseWhen(context => context.Request.Headers.ContainsKey("Authorization"), appBuilder =>
{
    // use oauth authentication
} 

But for your case, the authentication middlewares should handle these conditions inside own authentication handler and if does not match condition then it skips. You shouldn't need to handle conditions. So you can just use these authentication middlewares:

app.UseBasicAuthentication();

app.UseOauthAuthentication();
like image 63
adem caglin Avatar answered Sep 17 '25 07:09

adem caglin