[英]How to parse a JWT token with RSA in jwt-go ParseWithClaims?
I have developed the following method, which should enable token-based authentication (jwt).我开发了以下方法,它应该启用基于令牌的身份验证 (jwt)。 An asynchronous process should be used to generate the token.
应使用异步过程来生成令牌。
The source code seems to work up to and including the generation of the signed token.源代码似乎适用于并包括签名令牌的生成。 I encountered an issue when querying the token with
ParseWithClaims
.使用
ParseWithClaims
查询令牌时遇到问题。 Can someone help please?有人可以帮忙吗?
package controllers
import (
"crypto/rand"
rsaKeys "crypto/rsa"
"fmt"
jwtgo "github.com/dgrijalva/jwt-go"
"github.com/gofiber/fiber"
)
func Login(c *fiber.Ctx) error {
type TestClaims struct {
HAPP string `json:"happ"`
jwtgo.StandardClaims
}
currentPrivateKey, err := rsaKeys.GenerateKey(rand.Reader, 512)
claims := TestClaims{
"owa",
jwtgo.StandardClaims{
Issuer: "test",
ExpiresAt: 15000,
},
}
token := jwtgo.NewWithClaims(jwtgo.SigningMethodRS256, claims)
tokenSigned, err := token.SignedString(currentPrivateKey)
if err != nil {
fmt.Printf("Failed to sign in account %v", err)
}
//Issue is in this statement
_, errTest := jwtgo.ParseWithClaims(tokenSigned, &TestClaims{"owa", jwtgo.StandardClaims{}}, func(token *jwtgo.Token) (interface{}, error) {
return currentPrivateKey, nil
})
if errTest != nil {
fmt.Printf("Error Message: %v", errTest) //Does throw error: key is of invalid type
}
return c.JSON(fiber.Map{
"message": "success",
})
}
To validate the JWT you need the public key, specifically ParseWithClaims
expects a key of type *rsa.PublicKey
.为了验证你所需要的公共密钥的智威汤逊,具体
ParseWithClaims
预计类型的密钥*rsa.PublicKey
。
You can get it from the private key with PrivateKey.Public
:您可以使用
PrivateKey.Public
从私钥中获取它:
tok, err := jwtgo.ParseWithClaims(tokenSigned, &TestClaims{"owa", jwtgo.StandardClaims{}}, func(token *jwtgo.Token) (interface{}, error) {
return currentPrivateKey.Public(), nil
})
Please note that dgrijalva/jwt-go
is unmaintained .请注意
dgrijalva/jwt-go
是未维护的。 If you can, switch to the community fork golang-jwt/jwt
, which includes critical security fixes.如果可以,请切换到社区分支
golang-jwt/jwt
,其中包括关键的安全修复程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.