1 回答
TA貢獻1798條經驗 獲得超7個贊
在github.com/dgrijalva/jwt-goSigningMethodECDSA.Sign文檔中,您可以找到:
[...] 對于這種簽名方法,密鑰必須是一個ecdsa.PrivateKey結構
所以,舉個例子:
p8bytes, err := ioutil.ReadFile("SomeAppleKey.p8")
if err != nil {
log.Println(err)
return
}
// Here you need to decode the Apple private key, which is in pem format
block, _ := pem.Decode(p8bytes)
// Check if it's a private key
if block == nil || block.Type != "PRIVATE KEY" {
log.Println("Failed to decode PEM block containing private key")
return
}
// Get the encoded bytes
x509Encoded := block.Bytes
token := jwt.NewWithClaims(
jwt.SigningMethodES256, // specific instance of `*SigningMethodECDSA`
jwt.StandardClaims{
// ...
},
)
// Now you need an instance of *ecdsa.PrivateKey
parsedKey, err := x509.ParsePKCS8PrivateKey(x509Encoded) // EDIT to x509Encoded from p8bytes
if err != nil {
panic(err)
}
ecdsaPrivateKey, ok := parsedKey.(*ecdsa.PrivateKey)
if !ok {
panic("not ecdsa private key")
}
// Finally sign the token with the value of type *ecdsa.PrivateKey
signed, err := token.SignedString(ecdsaPrivateKey)
if err != nil {
panic(err)
}
fmt.Println(signed) // the signed JWT
注意:如代碼片段所示,因為來自蘋果的密鑰文件是PEM格式,需要先解碼
警告!
請注意,它github.com/dgrijalva/jwt-go已長期無人維護,并且有嚴重的未修復錯誤。并且在版本 4 之前不支持 Go 模塊(無論如何這只是一個預覽版)。我強烈建議選擇一個不同的庫來處理 JWT。
2021 年 6 月更新
現(xiàn)在有一個圖書館的官方社區(qū)分支:由原始項目的所有者祝福。golang-jwt/jwt
- 1 回答
- 0 關注
- 243 瀏覽
添加回答
舉報
