簡體   English   中英

帶有 rsa 密鑰的 Golang 包 jwt-go。 如何放置公鑰以及如何從令牌中獲取它?

[英]Golang package jwt-go with rsa key. How to put the public key and how to get it from the token?

我正在嘗試使用 golang 中的 jwt-go 包生成帶有 rsa 密鑰的令牌。

這里有一篇博客解釋了如何做到這一點,但該代碼將始終驗證所有令牌,因為它使用存儲在服務器中的公鑰而不是從令牌中獲取它。 你如何將完整的公鑰放在令牌中? 我正在嘗試這個:

var secretKey, _ = rsa.GenerateKey(rand.Reader, 1024)
token := jwt.New(jwt.SigningMethodRS256)
token.Claims["username"] = "victorsamuelmd"
token.Claims["N"] = secretKey.PublicKey.N
token.Claims["E"] = secretKey.PublicKey.E

tokenString, err := token.SignedString(secretKey)

nt, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
    // here I need to recover the public key from the token
    // but N is a big.Int and the token stores N as int64
})

對不起我的英語。 謝謝。

我認為將公鑰存儲在聲明中並不是一個好主意,因為我們可以在技術上使用該密鑰驗證 JWT,但這意味着它不再是簽名的 JWT。 如果任何人都可以使用自己的私鑰生成 JWT 並將公鑰存儲在 JWT 中,我們無法確定誰是簽名者。

無論如何,您可以將公鑰轉換為 PEM 格式的字符串,並將其存儲在聲明中。 在客戶端,您也可以簡單地再次將其解析為公鑰格式。 示例代碼如下:

privateKey, _ := rsa.GenerateKey(rand.Reader, 1024)
bytes, _ := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
pem := pem.EncodeToMemory(&pem.Block{
    Type:  "RSA PUBLIC KEY",
    Bytes: bytes,
})
claim["publickey"] = string(pem)

pem := []byte(claims["publickey"].(string))
return jwt.ParseRSAPublicKeyFromPEM(pem)

jwtdgrijalva 的 jwt-go

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM