![](/img/trans.png)
[英]Verifying JWT signed with the RS256 algorithm using public key in C#
[英]Verifying a JWT using the public key with C#
我正在構建一個由用 C# 編寫的 Azure 函數支持的 React 應用程序。 我已經通過 Userfront 實現了 JWT 身份驗證,這在前端工作正常,但我正在努力使用函數中的公鑰驗證令牌。
我嘗試了很多方法, JWT-DotNet是最新的但無濟於事。
誰能提供一個工作代碼示例?
這是我目前所擁有的(在創建新的 RS256Algorithm 時出現“找不到請求的 object”的錯誤):
var headers = req.Headers;
if (!headers.TryGetValue("Authorization", out var tokenHeader))
return new StatusCodeResult(StatusCodes.Status403Forbidden);
var token = tokenHeader[0].Replace("Bearer ", "");
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("Userfront_PublicKey"));
var urlEncoder = new JwtBase64UrlEncoder();
var publicKey = urlEncoder.Encode(plainTextBytes);
try
{
IJsonSerializer serializer = new JsonNetSerializer();
var provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IJwtAlgorithm algorithm = new RS256Algorithm(new X509Certificate2(plainTextBytes));
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder,algorithm);
var json = decoder.Decode(token[0], publicKey, verify: true);
}
catch (TokenExpiredException)
...
catch (SignatureVerificationException)
...
假設環境變量“Userfront_PublicKey”包含一個 PEM 編碼的 RSA 公鑰,即:
-----BEGIN RSA PUBLIC KEY-----
(your base64-encoded RSA public key)
-----END RSA PUBLIC KEY-----
那么我會嘗試以下方法(未經測試,抱歉):
var headers = req.Headers;
if (!headers.TryGetValue("Authorization", out var tokenHeader))
return new StatusCodeResult(StatusCodes.Status403Forbidden);
var token = tokenHeader[0].Replace("Bearer ", "");
var publicKeyPem = Environment.GetEnvironmentVariable("Userfront_PublicKey");
var publicKey = RSA.Create();
publicKey.ImportFromPem(publicKeyPem);
try
{
var json = JwtBuilder.Create()
.WithAlgorithm(new RS256Algorithm(publicKey))
.MustVerifySignature()
.Decode(token);
}
catch (TokenExpiredException)
...
catch (SignatureVerificationException)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.