无法验证JWT令牌。

huangapple go评论84阅读模式
英文:

Can't validate JWT token

问题

我只会翻译代码部分,以下是翻译好的代码:

我只想做的是生成一个新的密钥创建JWT令牌然后验证它

package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"encoding/base64"
	"fmt"
	"log"
	"time"

	"github.com/golang-jwt/jwt/v4"
)

func main() {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		log.Fatalln(err)
		return
	}

	privateK, err := x509.MarshalECPrivateKey(key)
	if err != nil {
		log.Fatalln(err)
		return
	}

	claims := jwt.MapClaims{}
	claims["authorized"] = true
	claims["user_id"] = 10
	claims["exp"] = time.Now().Add(time.Hour * time.Duration(1)).Unix()
	t := jwt.NewWithClaims(jwt.SigningMethodES256, claims)

	tokenStr, err := t.SignedString(key)
	if err != nil {
		log.Fatalln(err)
		return
	}

	fmt.Printf("Secret: %s\n", base64.StdEncoding.EncodeToString(privateK))
	fmt.Printf("Token: %s\n", tokenStr)

	// 验证令牌

	_, err = jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
			return nil, fmt.Errorf("unexpected signing method %v", token.Header["alg"])
		}
		return key, nil
	})

	if err != nil {
		log.Fatalf("Token is invalid %v", err)
	} else {
		fmt.Println("Token is valid")
	}
}

我得到的错误信息是Token is invalid: key is of invalid type。我做错了什么?

英文:

All I wanted to do, is to generate a new secret key, create JWT token and then validate it.

package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"fmt"
"log"
"time"
"github.com/golang-jwt/jwt/v4"
)
func main() {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
log.Fatalln(err)
return
}
privateK, err := x509.MarshalECPrivateKey(key)
if err != nil {
log.Fatalln(err)
return
}
claims := jwt.MapClaims{}
claims["authorized"] = true
claims["user_id"] = 10
claims["exp"] = time.Now().Add(time.Hour * time.Duration(1)).Unix()
t := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
tokenStr, err := t.SignedString(key)
if err != nil {
log.Fatalln(err)
return
}
fmt.Printf("Secret: %s\n", base64.StdEncoding.EncodeToString(privateK))
fmt.Printf("Token: %s\n", tokenStr)
// Validate token
_, err = jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
return nil, fmt.Errorf("unexpected signing method %v", token.Header["alg"])
}
return key, nil
})
if err != nil {
log.Fatalf("Token is invalid %v", err)
} else {
fmt.Println("Token is valid")
}
}

And I get Token is invalid: key is of invalid type. What I'm doing wrong?

答案1

得分: 1

根据文档中的说明:

ECDSA签名方法(ES256、ES384、ES512)需要使用ecdsa.PrivateKey进行签名,使用ecdsa.PublicKey进行验证。

你的keyfunc返回的是一个*edcsa.PrivateKey,与上述要求不匹配。要修复这个问题,请将return key, nil更改为return &key.PublicKey, nilplayground)。

英文:

As per the docs

>The ECDSA signing method (ES256,ES384,ES512) expect *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for validation

Your keyfunc is returning a *edcsa.PrivateKey which does not match the above. To fix this change return key, nil to return &key.PublicKey, nil (playground).

huangapple
  • 本文由 发表于 2023年1月10日 05:28:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75063115.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定