golang-jwt / jwt

Go implementation of JSON Web Tokens (JWT).

Home Page:https://golang-jwt.github.io/jwt/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

key is of invalid type when parsing JWT

Inasayang opened this issue · comments

I'm using ES256.

JWT can not be parsed by the private key. But it can be verified by the public key.

func TestJWT(t *testing.T) {
	//generate ECDSA
	priKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Error(err)
	}
	pubKey := priKey.Public()

	//x509Encoded, _ := x509.MarshalECPrivateKey(priKey)
	//pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509Encoded})
	//x509EncodedPub, _ := x509.MarshalPKIXPublicKey(pubKey)
	//pemEncodedPub := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: x509EncodedPub})

	//generate JWT
	token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.StandardClaims{})
	//key, err := jwt.ParseECPrivateKeyFromPEM(priKey)
	//if err != nil {
	//	t.Error(err)
	//}
	tokenString, err := token.SignedString(priKey)
	t.Logf("JWT:%s\n", tokenString)
	//verify JWT
	parts := strings.Split(tokenString, ".")
	res := jwt.SigningMethodES256.Verify(strings.Join(parts[0:2], "."), parts[2], pubKey)
	if res != nil {
		t.Logf("verify failed : %+v\n", res)
	} 
	t.Logf("verify success")
	//parse JWT
	token1, err := jwt.Parse(tokenString, 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 priKey, nil
	})
	if err != nil {
		t.Error(err)
	}
	t.Log(token1.Valid)
}

Problem solved. I should use the public key to parse JWT.