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!

InterfacesandpolymorphisminGoenhancecodereusabilityandmaintainability.1)Defineinterfacesattherightabstractionlevel.2)Useinterfacesfordependencyinjection.3)Profilecodetomanageperformanceimpacts.

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

Interface combinations build complex abstractions in Go programming by breaking down functions into small, focused interfaces. 1) Define Reader, Writer and Closer interfaces. 2) Create complex types such as File and NetworkStream by combining these interfaces. 3) Use ProcessData function to show how to handle these combined interfaces. This approach enhances code flexibility, testability, and reusability, but care should be taken to avoid excessive fragmentation and combinatorial complexity.

InitfunctionsinGoareautomaticallycalledbeforethemainfunctionandareusefulforsetupbutcomewithchallenges.1)Executionorder:Multipleinitfunctionsrunindefinitionorder,whichcancauseissuesiftheydependoneachother.2)Testing:Initfunctionsmayinterferewithtests,b

Article discusses iterating through maps in Go, focusing on safe practices, modifying entries, and performance considerations for large maps.Main issue: Ensuring safe and efficient map iteration in Go, especially in concurrent environments and with l

The article discusses creating and manipulating maps in Go, including initialization methods and adding/updating elements.

The article discusses differences between arrays and slices in Go, focusing on size, memory allocation, function passing, and usage scenarios. Arrays are fixed-size, stack-allocated, while slices are dynamic, often heap-allocated, and more flexible.

The article discusses creating and initializing slices in Go, including using literals, the make function, and slicing existing arrays or slices. It also covers slice syntax and determining slice length and capacity.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
