问题
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.
回答1:
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();
来源:https://stackoverflow.com/questions/37841270/branching-asp-net-core-pipeline-authentication