C#中如何用获取的公钥验证JWT有效性?求技术指导
解决RS256算法JWT的公钥验证问题
首先明确:你当前用JwtSecurityToken直接解析token的操作只读取了token内容,完全没做签名验证,这就是你觉得“解决方案里未使用公钥”的原因——真正的签名验证需要借助JwtSecurityTokenHandler配合公钥完成。
以下是修改后的完整代码,包含公钥转换、签名验证逻辑:
using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Cryptography; using System.Text; public JwtSecurityToken getUnsignedProperies(string signedUserProperties) { try { JObject jsonNode = JObject.Parse(signedUserProperties); if (jsonNode["error"] != null) { throw new Exception(jsonNode["error"].ToString()); } // 提取公钥和token string publicKeyStr = jsonNode["publicKey"].ToString(); string token = jsonNode["token"].ToString(); // 将PEM格式公钥转换为RsaSecurityKey RsaSecurityKey rsaKey; using (var rsa = RSA.Create()) { // 清理PEM头尾标记和换行符 var cleanedKey = publicKeyStr .Replace("-----BEGIN PUBLIC KEY-----", "") .Replace("-----END PUBLIC KEY-----", "") .Replace("\r", "") .Replace("\n", ""); // 导入公钥 rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(cleanedKey), out _); rsaKey = new RsaSecurityKey(rsa); } // 配置验证参数 var validationParams = new TokenValidationParameters { ValidateIssuer = false, // 根据业务需求决定是否验证Issuer ValidateAudience = false, // 根据业务需求决定是否验证Audience ValidateLifetime = true, // 验证token有效期 IssuerSigningKey = rsaKey, // 指定用于验证的公钥 ValidAlgorithms = new[] { SecurityAlgorithms.RsaSha256 } // 指定算法为RS256 }; // 执行验证 var handler = new JwtSecurityTokenHandler(); SecurityToken validatedToken; handler.ValidateToken(token, validationParams, out validatedToken); // 验证通过后返回解析后的token return validatedToken as JwtSecurityToken; } catch (SecurityTokenValidationException ex) { // 捕获签名无效、token过期等验证失败场景 throw new Exception("JWT验证失败: " + ex.Message, ex); } catch (Exception ex) { throw new Exception("处理JWT时出错: " + ex.Message, ex); } }
关键补充说明:
- 如果你的公钥是JWK(JSON Web Key)格式,直接替换公钥转换部分:
var rsaKey = new JsonWebKey(publicKeyStr);即可。 - 若需要验证Issuer或Audience,开启
ValidateIssuer/ValidateAudience后,需在validationParams中指定ValidIssuer和ValidAudience的具体值。 ValidateToken方法会自动校验签名有效性、token有效期等核心逻辑,验证不通过会直接抛出异常。
内容的提问来源于stack exchange,提问作者Bar
相关产品推荐
相关产品推荐

