問題描述
我的 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 自定義屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!