'Authentication asp.net 6 API with both Azure AD & custom JWT
I have an ASP.NET 6 API, that currently authenticates requests with a homemade JWT middleware that generates a JWT from a secret key defined in it's appsettings.
Goal: I need the API to be able to authenticate requests with both the homemade JWT middleware and Azure AD Auth, But I have been unable to achieve this so far.
Code:
This is my code so far:
Startup.cs:
namespace MyNamespace.Api
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
Logger.Information("Configuring services");
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));
// Omitted stuff
}
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
// Omitted
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseHomemadeJwtAuth(
key: key,
routes: new[]
{
SomeController.Route,
AnotherController.Route
}
);
}
}
}
MyCustomJwtMiddleware.cs
static class MyCustomJwtExtensions
{
const string AuthHeaderKey = "Authorization";
const string ValidAuthHeaderPrefix = "Bearer ";
public static void UseCustomJwtAuth(this IApplicationBuilder app, string key, string[] routes)
{
app.Use(async (context, next) =>
{
var request = context.Request;
try
{
if (IsMatch(request.Path, normalizedRoutes))
{
var authorizationHeader = request.Headers[AuthHeaderKey].FirstOrDefault();
context.User = DecodeMyAccessToken(authorizationHeader, decoder, key);
}
await next();
}
catch (SecurityException exception)
{
Log.Warning(exception, "Could not auth from {ip}", request.Method, request.Path, request.HttpContext?.Connection?.RemoteIpAddress);
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync(exception.Message);
}
});
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
