Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.IdentityModel.Tokens.JwtSecurityToken custom properties

Tags:

c#

asp.net

jwt

My AuthServer is currently using the following code to generate a JwtSecurityToken:

var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
var handler = new JwtSecurityTokenHandler();
var jwt = handler.WriteToken(token);

The payload looks like this:

{
  "unique_name": "myUserName",
  "sub": "myUserName",
  "role": "API_User",
  "iss": "Automation",
  "aud": "099153c2625149bc8ecb3e85e03f0022",
  "exp": 1486056731,
  "nbf": 1483464731
}

I would like to add some custom fields/properties within the token payload, such as ProfilePicURL, so that the payload can look something like this:

{
  "unique_name": "myUserName",
  "sub": "myUserName",
  "role": "API_User",
  "iss": "Automation",
  "aud": "099153c2625149bc8ecb3e85e03f0022",
  "exp": 1486056731,
  "nbf": 1483464731,
  "profilePicture": "http://url/user.jpg"
}

How do I go about adding these custom properties and ensuring that the token contains them?

like image 727
blgrnboy Avatar asked Jan 03 '17 18:01

blgrnboy


People also ask

What is SigningCredentials?

Use the SigningCredentials class to specify the signing key, signing key identifier, and security algorithms that are used by WCF to generate the digital signature for a SamlAssertion. To set the digital signature details, set the SigningCredentials property of the SamlAssertion class.

Which method is used by Securitytokenhandler?

The CanReadKeyIdentifierClause method and the ReadKeyIdentifierClause method: Deserializing key identifier clauses.


1 Answers

JwtSecurityToken exposes a JwtPayload Payload { get; set;} property. JwtPayload derives from Dictionary<string, object> so just add it to the payload...

var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
token.Payload["profilePicture"] = "http://url/user.jpg"
var handler = new JwtSecurityTokenHandler();
var jwt = handler.WriteToken(token);

It is important that you use WriteToken to encode and sign the token, as simply getting the RawData property will not work (the token will not contain the custom claims).

like image 56
Nkosi Avatar answered Oct 19 '22 19:10

Nkosi