Access dotnetcore middleware AFTER the JWT token is verified

I am using JWT bearer authentication configured as follows.

My problem is that the middleware runs before the token is confirmed.
How to configure middleware for later launch?

services.AddAuthentication()
    .AddCookie(_ => _.SlidingExpiration = true)
    .AddJwtBearer(
        _ =>
        {
            _.Events = new JwtBearerEvents
            {
                // THIS CODE EXECUTES AFTER THE MIDDLEWARE????
                OnTokenValidated = context =>
                {
                    context.Principal = new ClaimsPrincipal(
                        new ClaimsIdentity(context.Principal.Claims, "local"));
                    return Task.CompletedTask;
                }
            };
            _.RequireHttpsMetadata = false;
            _.SaveToken = false;
            _.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidIssuer = this.Configuration["Tokens:Issuer"],
                ValidAudience = this.Configuration["Tokens:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.Configuration["Tokens:Key"])),
            };
        });

I am trying to add middleware to a pipeline that is accessing the current user. This code, unfortunately, executes BEFORE the token is verified . How to do it after that?

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseIdentityServer();
    app.UseAuthentication();

    app.Use(async (httpContext, next) =>
       {
           // THIS CODE EXECUTES BEFORE THE TOKEN IS VALIDATED IN OnTokenValidated.
           var userName = httpContext.User.Identity.IsAuthenticated 
             ? httpContext.User.GetClaim("email")
             : "(unknown)";
           LogContext.PushProperty("ActiveUser", !string.IsNullOrWhiteSpace(userName) ? userName : "(unknown)");
           await next.Invoke();
       });
+4
source share
2 answers

, , , , , .

, , . HttpContext.User / , . "" , . , AuthorizeFilter. JWT, , Identity .. ( ) User , .

, ( cookie, jwt)... , , Jwt , HttpContext.User , :

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+5

@leppie, , .

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

:

services.AddMvc(
    _ =>
    {
        _.Filters.Add(
           new AuthorizeFilter(
               new AuthorizationPolicyBuilder(
                 JwtBearerDefaults.AuthenticationScheme,
                 IdentityConstants.ApplicationScheme)
               .RequireAuthenticatedUser()
                 .Build()));
        _.Filters.Add(new ActiveUserFilter());

        ...
+2

Source: https://habr.com/ru/post/1685941/


All Articles