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

blg*_*boy 9 c# asp.net jwt

我的AuthServer当前正在使用以下代码生成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);
Run Code Online (Sandbox Code Playgroud)

有效负载如下所示:

{
  "unique_name": "myUserName",
  "sub": "myUserName",
  "role": "API_User",
  "iss": "Automation",
  "aud": "099153c2625149bc8ecb3e85e03f0022",
  "exp": 1486056731,
  "nbf": 1483464731
}
Run Code Online (Sandbox Code Playgroud)

我想在令牌有效负载中添加一些自定义字段/属性,例如ProfilePicURL,以便有效负载看起来像这样:

{
  "unique_name": "myUserName",
  "sub": "myUserName",
  "role": "API_User",
  "iss": "Automation",
  "aud": "099153c2625149bc8ecb3e85e03f0022",
  "exp": 1486056731,
  "nbf": 1483464731,
  "profilePicture": "http://url/user.jpg"
}
Run Code Online (Sandbox Code Playgroud)

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

Nko*_*osi 15

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);
Run Code Online (Sandbox Code Playgroud)