Home  >  Article  >  Backend Development  >  Unable to verify JWT token

Unable to verify JWT token

WBOY
WBOYforward
2024-02-09 08:00:21565browse

无法验证 JWT 令牌

php editor Xigua introduces you to a common problem: Unable to verify JWT token. JWT (JSON Web Token) is an open standard for authentication and authorization. However, sometimes in PHP applications, we may encounter problems with not being able to validate JWT tokens. This could be due to a number of reasons, such as key mismatch, token expiration, etc. This article will explain the possible causes of this problem in detail and provide solutions to help you successfully verify JWT tokens.

Question content

All I want to do is generate a new key, create the jwt token, and then verify 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")
    }
}

I get token is invalid: key is of invalid type. What did i do wrong?

Solution

According to Documentation

ECDSA signature method (ES256, ES384, ES512) requires *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification

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

The above is the detailed content of Unable to verify JWT token. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete