Shakibuz_Zaman
Shakibuz_Zaman

Reputation: 270

How to get JWT token information in a Service in asp.net core api?

I want to access the token informations like claims of stored token in a service. I have tried injecting AuthorizationHandlerContext in my service. But the api can't to resolve the AuthorizationHandlerContext and throws exception. Is there any other way to access the token information inside a service?

Upvotes: 0

Views: 2062

Answers (3)

Farhad Zamani
Farhad Zamani

Reputation: 5861

You can inject IHttpContextAccessor to your service then get all user claims or user information from the JWT

Register IHttpContextAccessor into DI

services.AddHttpContextAccessor();
private readonly IHttpContextAccessor _httpContextAccessor;
public YourService(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}
var username =_httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

Upvotes: 2

Manzur Alahi
Manzur Alahi

Reputation: 2096

Since you want to access the JWT token informations, A more structured approach will be,

Step 1. Create a Model

    public class AuthorizedUser
    {
        public ClaimsPrincipal Claims { get; set; }        
    }

Step 2. Use this model inside your authorized Controller method. like:

    [Authorized]
    [HttpPost]
    public async Task<IActionResult> Modify([FromForm] RequestDto dto)
    {
        var user = new AuthorizedUser()
        {
            Claims = User
        };
        return Ok(await _service.MakeChanges(user, dto));
    }

Step 3. Create an extension function for ease of access

   public static string GetUserId(this ClaimsPrincipal claims)
   {
        return claims.Claims.Where(c => c.Type == "sub")
            .Select(c => c.Value).SingleOrDefault();
   }

Step 4. Simply access that users claims and other JWT properties like,

    public Task<object> MakeChanges(AuthorizedUser user, RequestDto dto){
          var userId = user.Claims.GetUserId();
    }

That's it.

Upvotes: 0

Always_a_learner
Always_a_learner

Reputation: 1304

Try this code on OnAuthorization(IAuthorizationFilter) action:

  string email=context.HttpContext.User.Claims.FirstOrDefault(c => c.Type == "email").Value;

Upvotes: 0

Related Questions