【问题标题】:How to add userid parameter to payload of jwt when generate access token?生成访问令牌时如何将 userid 参数添加到 jwt 的有效负载?
【发布时间】:2020-01-10 01:43:12
【问题描述】:

如何在生成访问令牌时将userId 参数添加到jwt 的负载中?

我在asp.net core 2.2 上工作,我需要将userId 参数添加到生成访问令牌 的负载中,然后生成JSON 格式的结果。

  public string GenerateTokens(string userId)
            {    
                var Claims = new Claim[]
                         {
                new Claim(JwtRegisteredClaimNames.Sub,userId)
                         };
                var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is secret phrase"));
                var SigningCredntials = new SigningCredentials(signingkey, SecurityAlgorithms.HmacSha256);
                var Jwt = new JwtSecurityToken();

                return new JwtSecurityTokenHandler().WriteToken(Jwt);
            }

【问题讨论】:

  • 有什么不清楚的地方

标签: c# asp.net-mvc asp.net-core jwt


【解决方案1】:

您应该在初始化JwtSecurityToken 实例时设置声明:

var Claims = new Claim[]
{
    new Claim(JwtRegisteredClaimNames.Sub,"userid")
     //your other claims
};
var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is secret phrase"));
var SigningCredntials = new SigningCredentials(signingkey, SecurityAlgorithms.HmacSha256);
var Jwt = new JwtSecurityToken(claims:Claims,signingCredentials:SigningCredntials);

return new JwtSecurityTokenHandler().WriteToken(Jwt);

JwtSecurityToken的构造函数,也可以设置issue,audience,expires..

public JwtSecurityToken(string issuer = null, string audience = null, IEnumerable<Claim> claims = null, DateTime? notBefore = null, DateTime? expires = null, SigningCredentials signingCredentials = null);

【讨论】:

  • 添加用户 id 怎么办?
  • 这样我需要添加用户名怎么办?
  • 这是一件好事,但这是什么意思 JwtRegisteredClaimNames.Sub
  • 有什么错误问题吗?如果回复有帮助,请考虑标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 2016-05-03
  • 2021-12-24
  • 2019-10-29
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多