System.IdentityModel.Tokens.JwtSecurityToken custom properties(System.IdentityModel.Tokens.JwtSecurityToken 自定义属性)
问题描述
我的 AuthServer 目前正在使用以下代码生成 JwtSecurityToken:
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);
有效载荷如下所示:
{
"unique_name": "myUserName",
"sub": "myUserName",
"role": "API_User",
"iss": "Automation",
"aud": "099153c2625149bc8ecb3e85e03f0022",
"exp": 1486056731,
"nbf": 1483464731
}
我想在令牌负载中添加一些自定义字段/属性,例如 ProfilePicURL,以便负载看起来像这样:
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?
推荐答案
JwtSecurityToken
暴露了一个 JwtPayload Payload { get;设置;}
属性.JwtPayload
派生自 Dictionary
所以只需将其添加到有效负载中...
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);
使用 WriteToken
对令牌进行编码和签名很重要,因为简单地获取 RawData
属性将不起作用(令牌将不包含自定义声明).
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).
这篇关于System.IdentityModel.Tokens.JwtSecurityToken 自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:System.IdentityModel.Tokens.JwtSecurityToken 自定义属性


基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01