[c#]System.IdentityModel.Tokens.JwtSecurityToken 自定义属性

标签: Asp.net C#
发布时间: 2017/2/25 3:45:33
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

目前我认证服务器使用下面的代码生成 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);

有效载荷看起来像这样︰

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

我想添加一些自定义的字段/属性内的令牌的有效载荷,如 ProfilePicURL,以便有效负载可以看起来像这样︰

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

如何着手添加这些自定义属性,并确保该令牌包含他们?

解决方法 1:

JwtSecurityToken公开了 JwtPayload Payload { get; set;} 属性。 JwtPayload 来自 Dictionary<string, object> 所以只是将其添加到负载...

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);
赞助商