System.IdentityModel.Tokens.JwtSecurityToken自定义属性

16

目前我的身份验证服务器正在使用以下代码生成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"
}

我该如何添加这些自定义属性并确保令牌(token)包含它们?


将其添加到Payload属性中,该属性源自于Dictionary<string, object>,即token.Payload["profilePicture"] = "http://url/user.jpg" - Nkosi
1个回答

28

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

使用 WriteToken 对令牌进行编码和签名非常重要,因为仅获取 RawData 属性不起作用(令牌将不包含自定义声明)。


谢谢!我在其他地方找不到这个,也不知道它是一个可以编辑的字典! - Gaspa79

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接