Ishara Madawa
Ishara Madawa

Reputation: 1622

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;

Upvotes: 3

Views: 6887

Answers (2)

Md Shahi Dullah
Md Shahi Dullah

Reputation: 41

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;
}

Upvotes: 2

jps
jps

Reputation: 22575

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.

Upvotes: 4

Related Questions