C#或VB使用手动创建的JWK验证JWT

时间:2018-10-23 18:01:34

标签: .net jwt jwk

发疯了,因为我在下面尝试验证时收到“ IDX10511:签名验证失败。尝试了密钥...”。我尝试了一个简单的JsonWebKey并转换为RSA并产生了相同的错误。在javascript中手动验证令牌和JWK。

Private Sub ValidateTokenAndSetIdentity(token As String)
    Dim TokenHandler As New JwtSecurityTokenHandler()
    Dim ValidationParameters As TokenValidationParameters = GetValidationParameters()
    Dim validToken As Microsoft.IdentityModel.Tokens.SecurityToken
    If TokenHandler.CanReadToken(token) Then
        Dim ValidKey As New JsonWebKeyConverter
        Dim Principal As ClaimsPrincipal = TokenHandler.ValidateToken(token, ValidationParameters, validToken)
        Thread.CurrentPrincipal = Principal
        HttpContext.Current.User = Principal
    End If
End Sub

Private Function GetValidationParameters() As TokenValidationParameters
    Dim SecurityKeys As List(Of Microsoft.IdentityModel.Tokens.SecurityKey) = GetSecurityKey()
    Dim TVP As New TokenValidationParameters With
        {
        .ClockSkew = TimeSpan.FromMinutes(5),
        .RequireSignedTokens = True,
        .RequireExpirationTime = True,
        .IssuerSigningKeys = SecurityKeys
    }
    Return TVP
End Function
Private Function GetSecurityKey() As List(Of Microsoft.IdentityModel.Tokens.SecurityKey)
    Dim Key As New JsonWebKey With {
    .Kid = "df255eb3e247cf83bac5a6227572f96e",
    .Kty = "RSA",
    .Alg = "RS256",
    .N = "LongValidStringHere",
    .E = "ShortValidString"
    }

    Dim Keys As New List(Of Microsoft.IdentityModel.Tokens.SecurityKey)
    Dim e As Byte() = Base64UrlEncoder.DecodeBytes(Key.E)
    Dim n = Base64UrlEncoder.DecodeBytes(Key.N)

    Dim FullKey As New Microsoft.IdentityModel.Tokens.RsaSecurityKey(New RSAParameters With {.Exponent = e, .Modulus = n}) With
        {
        .KeyId = Key.Kid
        }
    Keys.Add(FullKey)
    Return Keys
End Function

1 个答案:

答案 0 :(得分:0)

在我的情况下,错误是由JWT的aud字段中的无效值引起的。确保与有效的受众群体相同。