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

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

有效负载如下所示:

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

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

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

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

最佳答案

JwtSecurityToken公开一个 JwtPayload Payload { get; set;} 属性(property)。 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对 token 进行编码和签名,只需获取 RawData属性将不起作用( token 将不包含自定义声明)。

关于c# - System.IdentityModel.Tokens.JwtSecurityToken 自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41450141/

相关文章:

C# sql 查询 if() else() 基于结果 null?

c# - 如何将 IConfigurationSection 中的配置映射到一个简单的类

c# - XNA 内容加载异常

javascript - ASP.NET 使用 Javascript 停止 CodeBehind 调用

c# - 如何检查文件格式

c# - 如何使用 model.id 动态生成 HTML 属性值?

jwt - Auth0.com,它到底是如何运作的?

c# - 具有来自其他数据表的 id 的数据表,需要转换此数据表以将 id 替换为其数据表名称列值

java - 如何在Spring Security中的所有请求中添加jwt身份验证 header ?

node.js - 为什么 jsonwebtoken 会抛出 "invalid signature"错误?