How to implement local JWT verification in Go?
To implement local verification of JSON Web Token (JWT) in Go, you can follow these steps:
- To begin with, you need to install and import the github.com/dgrijalva/jwt-go library. You can install it using the following command:
go get github.com/dgrijalva/jwt-go
- Import the necessary packages in the code.
import (
"github.com/dgrijalva/jwt-go"
)
- Create a structure to represent the payload of a JSON Web Token (JWT).
type Claims struct {
Username string `json:"username"`
jwt.StandardClaims
}
Here, jwt.StandardClaims is used to include the standard fields of JWT (such as expiration time, etc.).
- – private key
var secretKey = []byte("your-secret-key")
- Create a function to generate JWT. Here is an example function that generates JWT:
func GenerateJWT(username string) (string, error) {
claims := &Claims{
Username: username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 24).Unix(), // 设置过期时间为24小时
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, err := token.SignedString(secretKey)
if err != nil {
return "", err
}
return signedToken, nil
}
In this example, we created a JWT using jwt.NewWithClaims and specified the signing algorithm with SigningMethodHS256. Then, we signed the JWT using the token.SignedString method and returned the signed JWT string.
- Create a function to verify JWT. Here is an example function for verifying JWT:
func ValidateJWT(tokenString string) (*Claims, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return secretKey, nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, errors.New("invalid token")
}
return claims, nil
}
In this example, we use the jwt.ParseWithClaims method to parse the JWT and store the parsed claims in the claims variable. Then, we verify the validity of the JWT signature using the same key. If the verification is successful, we return the parsed claims. Otherwise, we return an error.
- Now, you can use the defined functions above to generate and validate JWT. Here is a complete example:
package main
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"time"
)
type Claims struct {
Username string `json:"username"`
jwt.StandardClaims
}
var secretKey = []byte("your-secret-key")
func main() {
username := "john.doe"
token, err := GenerateJWT(username)
if err != nil {
fmt.Println("Error generating JWT:", err)
return
}
fmt.Println("JWT:", token)
claims, err := ValidateJWT(token)
if err != nil {
fmt.Println("Error validating JWT:", err)
return
}
fmt.Println("Valid token for user:", claims.Username)
}
func GenerateJWT(username string) (string, error) {
claims := &Claims{
Username: username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 24).Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, err := token.SignedString(secretKey)
if err != nil {
return "", err
}
return signedToken, nil
}
func ValidateJWT(tokenString string) (*Claims, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return secretKey, nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, errors.New("invalid token")
}
return claims, nil
}
In this example, we