通过JWT网络令牌遗失声明

时间:2020-02-17 21:32:31

标签: jwt asp.net-core-webapi

我有以下代码在webapi核心应用程序中创建JWT令牌。

var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
                var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

                var claims = new[] {
                    new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username!=null?userInfo.Username:string.Empty),
                    new Claim(JwtRegisteredClaimNames.Email, userInfo.Email!=null?userInfo.Email:string.Empty),
                    new Claim(JwtRegisteredClaimNames.Jti, userInfo.AccountId!=null?userInfo.AccountId.ToString():Guid.Empty.ToString()),
                    new Claim(JwtRegisteredClaimNames.NameId, userInfo.UserId!=null?userInfo.UserId.ToString():Guid.Empty.ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, userInfo.ClientId!=null?userInfo.ClientId.ToString():Guid.Empty.ToString())
                };

                var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                  _config["Jwt:Issuer"],
                  claims,
                  null,
                  expires: DateTime.Now.AddMinutes(20),
                  signingCredentials: credentials);

                return new JwtSecurityTokenHandler().WriteToken(token);

但是,当我尝试在客户端调用webapi端点之后找回声明时,我只有以下声明。如您所见,“ JTI”声明很好,但是缺少“ UniqueName”声明。

[0]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: }
    [1]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress: }
    [2]: {jti: f7c5af77-d0c4-4026-9b33-2fe9fbf5ee28}
    [3]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: 00000000-0000-0000-0000-000000000000}
    [4]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: b34a1b42-df24-42a3-93d7-68e88523602f}
    [5]: {exp: 1581973428}
    [6]: {iss: Test.com}
    [7]: {aud: Test.com}

我需要怎么做才能使索赔出现?

请注意,我设置为JwtRegisteredClaimNames.UniqueName的声明确实出现在声明中,但没有使用该名称。其值设置在项目下

[4]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: b34a1b42-df24-42a3-93d7-68e88523602f}

但是使用null时,它不会恢复原状

identity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value;

1 个答案:

答案 0 :(得分:1)

但是使用null时,它不会恢复原状

struct EditItemView: View { @ObservedObject var myItem : Item var body: some View { ...} }

要解决上述问题,您可以尝试使用Startup.cs中的以下代码片段清除入站声明类型映射

identity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value;

测试结果

设置System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); 的测试值

JwtRegisteredClaimNames.UniqueName

可以使用//just for testing purpose new Claim(JwtRegisteredClaimNames.UniqueName, "b34a1b42-df24-42a3-93d7-68e88523602f")

获得期望值

enter image description here