Shaka
Shaka
CC#
Created by Shaka on 11/10/2023 in #help
❔ Is this possible in WEBAPI to add logic between JWT token validation and the authorization?
I read a blog about the AspNetCore WebApi: https://jasonwatmore.com/post/2022/02/18/net-6-role-based-authorization-tutorial-with-example-api this sample add an User instance in HttpContext.Items after the token validation and bring it to the Authorization filter to use it. I'm trying implement this with AspNetCore internal functions(middleware, policy and requirements). but I cannot find a way to add User instance in that time. and also try to created a custom middleware but this Handler will be invoked after the authorization.
public class CustomAuthMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
{
private IUserService userService;

public CustomAuthMiddlewareResultHandler(IUserService userService)
{
this.userService = userService;
}
public Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
{
if (authorizeResult.Challenged)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask; ;
}
var userId = int.Parse(context.User.Claims.First(x => x.Type == "id").Value);
context.Items["User"] = userService.GetById(userId);
next(context);
return Task.CompletedTask;
}
}
public class CustomAuthMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
{
private IUserService userService;

public CustomAuthMiddlewareResultHandler(IUserService userService)
{
this.userService = userService;
}
public Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
{
if (authorizeResult.Challenged)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask; ;
}
var userId = int.Parse(context.User.Claims.First(x => x.Type == "id").Value);
context.Items["User"] = userService.GetById(userId);
next(context);
return Task.CompletedTask;
}
}
Is there any handler can add some logic between JWT token validation and API authorization?
103 replies