how to custom jwtBearer Handler?

mc 5,491 Reputation points
2023-05-21T08:04:21.4433333+00:00

I use jwtbearer

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)}AddJwtBearer("Bearer",options =>{

}

);

how to custom it's handler of HandleChallengeAsync or HandleForbiddenAsync

what I want is to change the status code when it is not authorized.

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Qing Guo - MSFT 896 Reputation points Microsoft External Staff
    2023-05-22T06:15:55.8+00:00

    Hi @mc

    what I want is to change the status code when it is not authorized.

    Below is a way to override the default challenge logic in JwtBearerHandler.HandleChallengeAsync , is to hook a handler to the JwtBearerEvents.OnChallenge callback in builder.Services.AddAuthentication().AddJwtBearer():

    
    builder.Services.AddAuthentication().AddJwtBearer("Bearer",options =>{
       ...
       options .Events.OnChallenge = async context =>
        {
            // Call this to skip the default logic and avoid using the default response
            context.HandleResponse();
    
            // Write to the response in any way you wish
            context.Response.StatusCode =202;
            context.Response.Headers.Append("my-custom-header", "custom-value");
            await context.Response.WriteAsync("You are not authorized! (or some other custom message)");
        };
    }
    );
    

    result:

    Capture

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Qing Guo

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2023-10-06T08:01:12.84+00:00
    
    namespace CustAuthCore
    {
        public class CustomAuthenticationRequirement : IAuthorizationRequirement
        {
        }
    }
    
    
    
    
    builder.Services.AddAuthorization(options =>
    {
        options.AddPolicy("CustomAuthentication", policy =>
            policy.Requirements.Add(new CustomAuthenticationRequirement()));
    });
    
    builder.Services.AddSingleton<IAuthorizationHandler, CustomAuthenticationHandler>();
    
    
    
    
    
     namespace CustAuthCore.Filters {     public class CustomAuthenticationHandler : AuthorizationHandler<CustomAuthenticationRequirement>     {         protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomAuthenticationRequirement requirement)         {             //your previous codes to check the user             if (context.Resource is HttpContext authorizationFilterContext)             {                 if (authorizationFilterContext.Request.Headers.ContainsKey("Authorization"))                 {                     var authToken = authorizationFilterContext.Request.Headers["Authorization"].ToString().Substring("Bearer ".Length).Trim();                     var decodedAuthToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));                     var arrUsernameandPassword = decodedAuthToken.Split(':');                     if (IsAuthorizedUser(arrUsernameandPassword[0], arrUsernameandPassword[1]))                     {                         var claims = new List<Claim>                     {                         new Claim(ClaimTypes.Name, arrUsernameandPassword[0])                     };                          var identity = new ClaimsIdentity(claims, "custom");                         var principal = new ClaimsPrincipal(identity);                         authorizationFilterContext.User = principal;                          context.Succeed(requirement);                     }                 }             }              return Task.CompletedTask;         }          private bool IsAuthorizedUser(string username, string password)         {             return username == "test" && password == "pass";         }     } } 
    
    
    
     [Authorize(Policy = "CustomAuthentication")]
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.