我遇到了这个问题,真的不知道如何解决,有人可以帮助您提供有效的解决方案吗?
func GenerateJWT(name, role string) (string, error) { //create a singner for rsa 256 claims := &jwt.StandardClaims{ ExpiresAt: 15000, Issuer: "test", } token :=jwt.NewWithClaims(jwt.SigningMethodES256, claims) log.Println("generated toke is ") log.Println(token) tokenString, err := token.SignedString([]byte("secret")) .... }
现在我总是有:
密钥类型无效
错误。我在Google上搜索了很多东西,甚至对于jwt-go图书馆本身,他们也提供了完全相同的解决方案,但是为什么我一直拥有
jwt-go
错误?
谁能提供有关如何生成jwt令牌的有效示例go?
jwt
go
从自述文件:
ECDSA签名方法(ES256,ES384,ES512)期望 ecdsa.PrivateKey进行签名,而 ecdsa.PublicKey进行验证
因此,使用椭圆曲线键:
package main import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "log" jwt "github.com/dgrijalva/jwt-go" ) func main() { key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { log.Fatal(err) } claims := &jwt.StandardClaims{ ExpiresAt: 15000, Issuer: "test", } token := jwt.NewWithClaims(jwt.SigningMethodES256, claims) tokenString, err := token.SignedString(key) if err != nil { log.Fatal(err) } log.Println(tokenString) }
要存储生成的密钥以供以后与jwt.ParseECPrivateKeyFromPEM和jwt.ParseECPublicKeyFromPEM一起使用:
import ( "crypto/ecdsa" "crypto/x509" "encoding/pem" ) func pemKeyPair(key *ecdsa.PrivateKey) (privKeyPEM []byte, pubKeyPEM []byte, err error) { der, err := x509.MarshalECPrivateKey(key) if err != nil { return nil, nil, err } privKeyPEM = pem.EncodeToMemory(&pem.Block{ Type: "EC PRIVATE KEY", Bytes: der, }) der, err = x509.MarshalPKIXPublicKey(key.Public()) if err != nil { return nil, nil, err } pubKeyPEM = pem.EncodeToMemory(&pem.Block{ Type: "EC PUBLIC KEY", Bytes: der, }) return }