【问题标题】:How to parse a set of JWK with x5c and verify JWT?如何使用 x5c 解析一组 JWK 并验证 JWT?
【发布时间】:2021-06-25 13:10:16
【问题描述】:

我想验证 JSON Web 令牌。用于验证的 JSON Web Key 在this url 下可用。这些是具有 x509 证书 (x5c) 的 JWK。基于answer to another question,尝试了以下方法:

import  "github.com/dgrijalva/jwt-go"
import  "github.com/lestrrat-go/jwx/jwk"

func verifyToken(tokenBytes []byte) {
    token, err := jwt.Parse(string(tokenBytes), getKey)
    if err != nil {
        panic(err)
    }
}

func getKey(token *jwt.Token) (interface{}, error) {
    set, err := jwk.Fetch(context.Background(), "https://shareduks.uks.attest.azure.net/certs")
    if err != nil {
        return nil, err
    }
    keyID, ok := token.Header["kid"].(string)
    if !ok {
        return nil, err
    }
    key, ok := set.LookupKeyID(keyID)
    if !ok {
        return nil, errors.New("could not find key with kid")
    }
    return key, nil
}

但我收到以下错误

panic: failed to parse JWK set: failed to unmarshal JWK set: failed to unmarshal key #1 (total 5) from multi-key JWK set: failed to unmarshal JSON into key (*jwk.rsaPublicKey): required field e is missing

我找不到使用 x5c 的示例。解决方案不必使用我在示例中使用的库。谢谢!

【问题讨论】:

    标签: go jwt x509 jwk


    【解决方案1】:

    该错误 (required field e is missing) 的原因是来自 this url 的 JWK 集无效。即使 JWK 包含 x5c,它仍然必须包含针对特定 kty 的另一个 required public key members,对于该 URL 中列出的 RSA 密钥,这意味着具有 ne

    【讨论】:

    • 感谢您的回答!我认为你是对的,这似乎是问题所在。有没有办法验证令牌?我的意思是所需的信息在 x5c 部分。我想到了类似将 x5c 的内容从 DER 转换为 PEM 并使用 PEM 使用 jwk 包进行验证...
    • 我没有您的包裹的详细信息,但是当 x5c[0] 得到 base64url 解码时,它就是 DER X.509 证书。当使用-----BEGIN CERTIFICATE-----\n + x5c[0] + \n-----END CERTIFICATE----- 包裹时,它是一个有效的 PEM X.509 证书。
    【解决方案2】:

    http://github.com/lestrrat-go/jwx 的作者在这里。

    我还没有合并解析证书的能力,但等待问题报告者的回复,但代码已经写好了https://github.com/lestrrat-go/jwx/compare/topic/issue-350

    一旦进行了更改,就可以执行一些扭曲并解析这些证书(伪代码):

    data := ... read from that URL ...
    
    rawSet := make(map[string]interface{})
    if err := json.Unmarshal(data, &rawSet); err != nil {
       ...
    }
    
    // yikes
    keys := rawset["keys"].([]interface{})
    firstKey := keys[0].(map[string]interface{})
    x5c := (firstKey["x5c"].([]interface{}))[0].(string)
    
    // Decode from base64 
    cert, _ := base64.RawStdEncoding.DecodeString(x5c)
    
    // turn the certificate into JWK (NOT YET MERGED)
    key, _ := jwk.ParseKey(cert, jwk.WithPEM(true))
    

    如果您需要将证书解析为 JWK 的能力,请在存储库中提交一个新问题,以便我跟踪更改。

    另外,如果您要导入 http://github.com/lestrrat-go/jwx/jwk,您不妨将 http://github.com/lestrrat-go/jwx/jwt 用于 JWT;)

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 2021-05-09
      • 2022-10-31
      • 2020-11-27
      • 2019-10-21
      • 2019-08-09
      • 1970-01-01
      • 2017-09-01
      • 2019-03-28
      相关资源
      最近更新 更多