Reputation: 3
I am building an ASP.NET Core API that uses Azure Entra ID (formerly Azure AD) for authentication. I need to process the TokenValidated event in JwtBearerEvents to handle group overage scenarios. For this, I use a service that attempts to retrieve the user's access token from the HttpContext. However, my current implementation triggers recursion because retrieving the token seems to invoke the middleware pipeline again.
Here is my JwtBearerEvents
implementation:
public class JwtBearerEventsProcessor(IGroupOverageService groupOverageService) : JwtBearerEvents
{
public override async Task TokenValidated(TokenValidatedContext context)
{
if (context != null)
{
// Handle group overage (calls a method to process claims)
await groupOverageService.ProcessAnyGroupOverage(context);
}
await Task.CompletedTask;
}
}
The ProcessAnyGroupoverage
method attempts to retrieve the access token using this code:
public async Task<string> GetAccessToken()
{
if (_httpContextAccessor.HttpContext == null)
{
throw new InvalidOperationException("HttpContext not initialized!");
}
//FIXME: This call triggers TokenValidated which leads to recursion.
var accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new InvalidOperationException("Unable to get access token from HttpContext!");
}
return accessToken;
}
The access token is needed in order to query the groups of the user from Microsoft Graph via http.
Calling GetTokenAsync
triggers the TokenValidated
event, leading to a recursive loop.
How can I safely retrieve the access token without triggering the middleware pipeline or causing recursion? Is there another (better) way to handle group overage?
Any help is appreciated. Thank you!
Instead of creating my own implementation of JwtBearerEvents
, I created a custom Middleware that calls the IGroupOverageService
. This approach works although it feels a bit hacky. Any comments are appreciated.
public class GroupOverageMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context, IGroupOverageService groupOverageService)
{
await groupOverageService.ProcessAnyGroupOverage();
await next(context);
}
}
Upvotes: 0
Views: 71