我正在努力让JWT与Firebase一起使用。我能够创建一个令牌并使用JWT.IO解码它,一切看起来都正确。我的问题是我也希望能够验证签名。这是我第一次使用Firebase并创建令牌,所以我不在这里。我一直试图找到样品,这就是我想出来的。我相信我需要将我的私钥和/或公钥传递给RSACryptoServiceProvider,但我不确定如何做到这一点。此外,当我尝试解码此令牌并验证JwtHeader对象上的签名时,我看到kid属性为null。
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
namespace MossCorps.Authorization
{
public class GoogleJsonWebToken
{
public static string Encode(string uid)
{
var firebaseInfJsonContent = @"JSON String from file";
var firebaseInf = JsonConvert.DeserializeObject<dynamic>(firebaseInfJsonContent);
// NOTE: Replace this with your actual RSA public/private keypair!
var provider = new RSACryptoServiceProvider(2048);
var parameters = provider.ExportParameters(true);
// Build the credentials used to sign the JWT
var signingKey = new RsaSecurityKey(parameters);
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256);
// Create a collection of optional claims
var now = DateTimeOffset.UtcNow;
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, firebaseInf.client_email.ToString()),
new Claim(JwtRegisteredClaimNames.Iat, now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
new Claim("uid", uid, ClaimValueTypes.String),
new Claim("premium_account", "true", ClaimValueTypes.Boolean)
};
// Create and sign the JWT, and write it to a string
var jwt = new JwtSecurityToken(
issuer: firebaseInf.client_email.ToString(),
audience: "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
claims: claims,
expires: now.AddMinutes(60).DateTime,
signingCredentials: signingCredentials);
return new JwtSecurityTokenHandler().WriteToken(jwt);
}
}
}