Accessing dotnetcore middleware AFTER a JWT Token is validated

后端 未结 2 1141
离开以前
离开以前 2021-01-18 09:42

I am using JWT bearer authentication, configured as follows.

My problem is that the middleware is executing before the token is validated.

2条回答
  •  旧巷少年郎
    2021-01-18 10:25

    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());
    
            ...
    

提交回复
热议问题