I have an App Service in Azure with Authentication enabled with Microsoft Identity Provider with the following settings:
I have code in startup to use custom middleware to process headers with access token and prepare claims for authorization purposes:
public void ConfigureServices(IServiceCollection services)
{
....
services.AddTransient<CustomAuthenticationMiddleware>();
services.AddAuthorization();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
...
app.UseAuthentication();
app.UseCustomAuthenticationMiddleware();
app.UseAuthorization();
}
public static IApplicationBuilder UseCustomAuthenticationMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomAuthenticationMiddleware>();
}
public class CustomAuthenticationMiddleware
{
private readonly RequestDelegate _next;
public CustomAuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
const string tokenHeaderName = "X-MS-TOKEN-AAD-ACCESS-TOKEN";
if (context.Request.Headers.TryGetValue(tokenHeaderName, out StringValues value))
{
... Parse token, and set context.User
}
await _next(context);
}
It worked perfectly, but the behavior changed recently, this header is not attached to the request after some after login has passed. If I clear cookie and refresh the page everything is working again for some time. There were no changes in environment related to authentication so it is not obvious to me why it was working before and stopped working as intended.