Wallen
Wallen

Reputation: 302

How to access Token data from controller method?

How do I access jwt token data passed from a client to my controller method? I need the userId from the token in order to access more data about the user through other method calls within my data repository layer.

I have been able to do it with a hardcoded token string, but not from a token passed from a client. How would I write this controller method to take the jwt token as an input... or access the token string from within this controller method and thus retrieve the data I am looking for?

How do I actually pass the token into my controller method?

[HttpGet("tokenz")]
        public ApplicationUser ParseToken()
        {
            var stringToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJXaWxsQGdtYWlsLmNvbSIsImp0aSI6IjMxMWM3ZGU5LTcxMDctNGI4MC1hMzViLTA4NjJlYTE1MjZjOCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWVpZGVudGlmaWVyIjoiYzE3ZTEyNWItYmE0NC00N2MxLTg2NzUtOTc2ZmJlZDRlMTEyIiwiZXhwIjoxNTc2NDU0NDYxLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo1NzA5NiIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjU3MDk2In0.VtsMgq7fc17M6y8kKHQRw3vO3M7aSrQgF62gw0-mXWg";

            var handler = new JwtSecurityTokenHandler();

            var tokenS = handler.ReadToken(stringToken) as JwtSecurityToken;

            var tokenSubject = tokenS.Subject;

            var appUser = _unitofWork.User.GetUserFromSubject(tokenSubject);

            return appUser;
        }

This has not worked:

JWT token data access from action/controller layer

Or this:

Retrieving access token in controller

Sooo...

Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
        [HttpPost("moretokenz")]
        public JwtSecurityToken MoreToken(string strToken)
        {
            //Where would strToken come from?
            return new JwtSecurityTokenHandler().ReadJwtToken(strToken);
        }

Upvotes: 8

Views: 13067

Answers (2)

Rena
Rena

Reputation: 36645

Try this:

[HttpGet]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public async Task<ActionResult<string>> Get()
{
    var token = await HttpContext.GetTokenAsync("access_token");
    return token;
}

Result: enter image description here

Upvotes: 10

qbacid313
qbacid313

Reputation: 31

You just need to get the claims in the payload of the JWT Token. Visit https://jwt.io/introduction/

var securityTokenHandler = new JwtSecurityTokenHandler();
        if (securityTokenHandler.CanReadToken(yourStringAccessToken))
        {
            var decriptedToken = securityTokenHandler.ReadJwtToken(yourStringAccessToken);
            var claims = decriptedToken.Claims;
            //At this point you can get the claims in the token, in the example I am getting the expiration date claims
            //this step depends of the claims included at the moment of the token is generated
            //and what you are trying to accomplish
            var expiredClaimValue = claims.Where(c => c.Type == "exp").FirstOrDefault().Value;
        }

Upvotes: 3

Related Questions