Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i retrieve information other than username/Identity from bearer token Web API

I am pretty much new to token base authentication. Can i read other than username from ClaimsPrincipal principal (identity). Is there any way to read/write(store) other information in bearer token.

ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

var Name = ClaimsPrincipal.Current.Identity.Name;
like image 775
Ishara Madawa Avatar asked Dec 31 '25 13:12

Ishara Madawa


2 Answers

Additional information is stored is so called claims in the payload part of a JWT. JWT is described in RFC 7519 and section 4 of this rfc describes the standard claims as well as the possibility to use private claim names.

The JWT issuer (the authorization server) can also write addional claims to the JWT, e.g.:

var identity = new ClaimsIdentity("JWT");  

identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); // standard claim
identity.AddClaim(new Claim("myClaim", "myClaimValue")); // private claim                

Please note: only the issuer can add information to the JWT and it can only be done during the creation of the JWT.

As the payload of a JWT is just normal JSON (after base64 decoding), you can read all the claims.

Check https://jwt.io/ for examples.

like image 166
jps Avatar answered Jan 03 '26 02:01

jps


You can get any value from your bearer token with key like "user_name".

private string GetUserName()
{       
    var claims = (ClaimsIdentity)ClaimsPrincipal.Current.Identity;

    if (claims == null)
    {
        return defaultValue;
    }

    var targetClaim = claims.FirstOrDefault(c => c.Type == "user_name");
    if (targetClaim == null)
    {
        return defaultValue;
    }

    return targetClaim.Value;
}
like image 45
Md Shahi Dullah Avatar answered Jan 03 '26 03:01

Md Shahi Dullah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!