Home > Net >  Can't validate JWT token
Can't validate JWT token

Time:01-10

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?

CodePudding user response:

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).

  • Related