System.IdentityModel.Tokens.JwtSecurityToken定制属性

编程入门 行业动态 更新时间:2024-10-21 17:35:58
本文介绍了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": "url/user.jpg" }

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

How do I go about adding these custom properties and ensuring that the token contains them?

推荐答案

JwtSecurityToken公开了 JwtPayload Payload { get; set;} 属性. JwtPayload 源自Dictionary<string, object>,因此只需将其添加到有效负载中即可.

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"] = "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定制属性

本文发布于:2023-11-13 00:14:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582876.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   IdentityModel   System   JwtSecurityToken   Tokens

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!