I am using JWT bearer authentication, configured as follows.
My problem is that the middleware is executing before the token is validated.
based on @leppie's comment, here is a solution that works.
public class ActiveUserFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
var userName = context.HttpContext.User.Identity.IsAuthenticated
? context.HttpContext.User.GetClaim("email")
: "(unknown)";
using (LogContext.PushProperty("ActiveUser", !string.IsNullOrWhiteSpace(userName) ? userName : "(unknown)"))
await next();
}
}
Inserted as follows...
services.AddMvc(
_ =>
{
_.Filters.Add(
new AuthorizeFilter(
new AuthorizationPolicyBuilder(
JwtBearerDefaults.AuthenticationScheme,
IdentityConstants.ApplicationScheme)
.RequireAuthenticatedUser()
.Build()));
_.Filters.Add(new ActiveUserFilter());
...