简体   繁体   English

无法读取使用 System.IdentityModel.Tokens.Jwt 生成的 JWT 令牌

[英]Unable to read JWT token generated using System.IdentityModel.Tokens.Jwt

We have started development on a new project and are considering using Identity Server/OpenId for authorization and Authentication needs.我们已经开始开发一个新项目,并正在考虑使用 Identity Server/OpenId 来满足授权和身份验证需求。 Since I have not worked with Jwt tokens before I was reading up on Microsoft's Jwt classes and support and trying out some sample code.因为在阅读 Microsoft 的 Jwt 类和支持并尝试一些示例代码之前,我没有使用过 Jwt 令牌。 I installed the System.Identitymodel.Tokend.Jwt version 5.4 from Nuget and generated the token using the sample code below (which I found on stack overflow)我从 Nuget 安装了 System.Identitymodel.Tokend.Jwt 5.4 版,并使用下面的示例代码生成了令牌(我在堆栈溢出时发现)

        string strToken = string.Empty;

        string strKey = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
        var vSymmetricSecurityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(strKey));
        var vSigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(vSymmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);
        var header = new JwtHeader(vSigningCredentials);
        var payload = new JwtPayload
        {
            { "Id", "userId" },
            { "Role", "userrole" },
            { "FirstName", "first_name" },
            { "LastName", "last_name" },
            { "EmailAddress", "email_address" },
            { "TenantId", "tenant_id" },
        };
        var secToken = new JwtSecurityToken(header, payload);
        var handler = new JwtSecurityTokenHandler();
        strToken = handler.WriteToken(secToken);

The token was generated successfully.令牌生成成功。 But when I go to read the token I get the following error但是当我去阅读令牌时,我收到以下错误

IDX12709: CanReadToken() returned false. IDX12709:CanReadToken() 返回 false。 JWT is not well formed: '[PII is hidden]'. JWT 格式不正确:'[PII is hidden]'。 The token needs to be in JWS or JWE Compact Serialization Format.令牌需要采用 JWS 或 JWE 紧凑序列化格式。 (JWS): 'EncodedHeader.EndcodedPayload.EncodedSignature'. (JWS): 'EncodedHeader.EndcodedPayload.EncodedSignature'。 (JWE): 'EncodedProtectedHeader.EncodedEncryptedKey.EncodedInitializationVector.EncodedCiphertext.EncodedAuthenticationTag'. (JWE): 'EncodedProtectedHeader.EncodedEncryptedKey.EncodedInitializationVector.EncodedCiphertext.EncodedAuthenticationTag'。

If I paste the token in JWT - it tells me invalid signature.如果我将令牌粘贴到 JWT 中 - 它会告诉我签名无效。 What could be incorrect?什么可能是不正确的?

The token generated is eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJJZCI6InVzZXJJZCIsIlJvbGUiOiJ1c2Vycm9sZSIsIkZpcnN0TmFtZSI6ImZpcnN0X25hbWUiLCJMYXN0TmFtZSI6Imxhc3RfbmFtZSIsIkVtYWlsQWRkcmVzcyI6ImVtYWlsX2FkZHJlc3MiLCJUZW5hbnRJZCI6InRlbmFudF9pZCJ9.BXUFKLcVmnGxRG5yGRNYVLTU2gT_F_AmBGev6sWhQd0所产生的令牌是eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJJZCI6InVzZXJJZCIsIlJvbGUiOiJ1c2Vycm9sZSIsIkZpcnN0TmFtZSI6ImZpcnN0X25hbWUiLCJMYXN0TmFtZSI6Imxhc3RfbmFtZSIsIkVtYWlsQWRkcmVzcyI6ImVtYWlsX2FkZHJlc3MiLCJUZW5hbnRJZCI6InRlbmFudF9pZCJ9.BXUFKLcVmnGxRG5yGRNYVLTU2gT_F_AmBGev6sWhQd0

You are using the wrong key type and algorithm.您使用了错误的密钥类型和算法。 JWT uses public/private keys and not symmetric keys. JWT 使用公钥/私钥而不是对称密钥。

Also, there is a standard for the content of the JWT claims (payload).此外,JWT 声明(有效负载)的内容也有一个标准。 You are missing items such as the issued, expires at, etc. fields.您缺少诸如已发行、到期于等字段的项目。 Once you fix your signing problem create a new question if you need help with JWT claims as this is a very different subject.解决签名问题后,如果您需要有关 JWT 声明的帮助,请创建一个新问题,因为这是一个非常不同的主题。

Note: strKey should be the Private Key of the keypair.注意:strKey 应该是密钥对的私钥。 The Public Key is used to verify the signature of the JWT (called JWS).公钥用于验证 JWT(称为 JWS)的签名。

Change these lines:更改这些行:

var vSymmetricSecurityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(strKey));
var vSigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(vSymmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);

to:到:

var vRsaSecurityKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(privateKey);
var vSigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(vSymmetricSecurityKey, SecurityAlgorithms.RsaSha256Signature);

In my case it was wrong OAuth Bearer Token.就我而言,这是错误的 OAuth 承载令牌。 Double check it, for example it can have two times "Bearer" at the beginning of the string仔细检查它,例如它可以在字符串的开头有两次“Bearer”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 System.IdentityModel.Tokens.Jwt 验证在 C# 中生成的令牌 - Verify Token generated in C# with System.IdentityModel.Tokens.Jwt 使用System.IdentityModel.Tokens.Jwt在Web API中进行JWT身份验证 - JWT Authentication in Web API using System.IdentityModel.Tokens.Jwt 使用ASP.NET 5中的System.IdentityModel.Tokens.Jwt编码JWT令牌 - Encoding JWT Token Using System.IdentityModel.Tokens.Jwt in ASP.NET 5 将System.IdentityModel.Tokens.Jwt 4.0.2更新为5.4令牌问题 - Update System.IdentityModel.Tokens.Jwt 4.0.2 to 5.4 Token Issues 使用System.IdentityModel.Tokens.Jwt与RS512验证JWT签名 - Validate JWT signature with RS512 using System.IdentityModel.Tokens.Jwt 使用 System.IdentityModel.Tokens.Jwt 验证没有密钥 Id 的外部创建的 JWT - Validate an externally created JWT with no key Id using System.IdentityModel.Tokens.Jwt 使用Microsoft System.IdentityModel.Tokens.Jwt在Asp.net WebApi中实现JWT身份验证 - Implementing JWT authentication in Asp.net WebApi using Microsoft System.IdentityModel.Tokens.Jwt 在System.IdentityModel.Tokens.Jwt中键入加载错误 - Type Load error in System.IdentityModel.Tokens.Jwt 如何使用 System.IdentityModel.Tokens.Jwt package 提取令牌过期时间 - How to extract the token expiration time with the System.IdentityModel.Tokens.Jwt package System.Identitymodel.Tokens.jwt 没有发行人可能吗? - System.Identitymodel.Tokens.jwt without issuer possible?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM