使用JWK在C#中验证JWT令牌

时间:2016-02-26 09:57:57

标签: asp.net-mvc jwt asp.net-identity-3

我有id_token和access_token的JsonWebKeys(JWK)。然后我从/ token url获得了我的id_token。 如何在C#中使用JWK验证此JWT id_token。

毋庸置疑,除了(IdenityModels.Jwt等)之外,我几乎已经尝试了所有东西,但是JwtSecurityTokenHandler不接受JsonWebKey。 我使用RS512作为签名算法。

1 个答案:

答案 0 :(得分:6)

我自己为Google IdToken验证实现了这个:

var parameters = new TokenValidationParameters
{
    ...
    IssuerSigningKeyResolver = await keyProvider.GetIssuerSigningKeyResolverAsync(cancellationToken),
};

SecurityToken token;
var handler = new JwtSecurityTokenHandler();
var principal = handler.ValidateToken(source, parameters, out token);

keyProvider是:

public class GoogleOAuth2KeyProvider
{
    private readonly IGoogleAuthConfiguration configuration;
    private Jwk lastCertResponse;
    private DateTimeOffset lastCertExpires;

    public GoogleOAuth2KeyProvider(IGoogleAuthConfiguration configuration)
    {
        this.configuration = configuration;
    }

    public async Task<IssuerSigningKeyResolver> GetIssuerSigningKeyResolverAsync(CancellationToken cancellationToken)
    {
        await UpdateCert(cancellationToken);

        var keys = lastCertResponse.Keys
            .Where(key => key.Kty == "RSA" && key.Use == "sig")
            .ToDictionary(key => key.Kid, StringComparer.InvariantCultureIgnoreCase);
        return new IssuerSigningKeyResolver((token, securityToken, keyIdentifier, tokenValidationParameters) =>
        {
            foreach (var keyIdentifierClause in keyIdentifier)
            {
                Jwk.KeysData key;
                if (!keys.TryGetValue(keyIdentifierClause.Id, out key))
                {
                    continue;
                }
                var rsa = RSA.Create();
                rsa.ImportParameters(new RSAParameters
                {
                    Exponent = Base64UrlEncoder.DecodeBytes(key.E),
                    Modulus = Base64UrlEncoder.DecodeBytes(key.N),
                });
                return new RsaSecurityKey(rsa);
            }
            return null;
        });
    }

    private async Task UpdateCert(CancellationToken cancellationToken)
    {
        if (lastCertResponse != null && DateTimeOffset.UtcNow < lastCertExpires)
        {
            return;
        }
        var initializer = new BaseClientService.Initializer
        {
            ApiKey = configuration.ServerApiKey,
        };
        using (var service = new Oauth2Service(initializer))
        {
            lastCertResponse = await service.GetCertForOpenIdConnect().ExecuteAsync(cancellationToken);
            lastCertExpires = DateTimeOffset.UtcNow.AddHours(12);
        }
    }
}

RSA等只是System.Security.Cryptography,而Base64UrlEncoder来自System.IdentityModel(但很容易做到)

不幸的是,它看起来并不像other kty / alg values那样容易支持,例如没有ECDsa.ImportParameters(),它需要来自CngKey的通用byte[],因此执行通用.NET JWK库的人必须打包x,{{大概是假装自己。