To generate and validate JSON Web Tokens (JWT) in Go, you can use the github.com/dgrijalva/jwt-go
library. Here's how you can do it:
Install the jwt-go
package using the following command:
go get github.com/dgrijalva/jwt-go
Import the required packages in your Go code:
import (
"github.com/dgrijalva/jwt-go"
"time"
)
Generate a new JWT token:
func generateToken() (string, error) {
// Create a new token
token := jwt.New(jwt.SigningMethodHS256)
// Set the claims (payload) for the token
claims := token.Claims.(jwt.MapClaims)
claims["user_id"] = 1234
claims["exp"] = time.Now().Add(time.Hour * 24).Unix() // Expiration time
// Generate the token with a secret key
secretKey := []byte("your-secret-key") // Make sure to keep this secret!
tokenString, err := token.SignedString(secretKey)
if err != nil {
return "", err
}
return tokenString, nil
}
Validate a JWT token:
func validateToken(tokenString string) (bool, error) {
// Parse the token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
secretKey := []byte("your-secret-key") // The same secret key used for signing
return secretKey, nil
})
if err != nil {
return false, err
}
// Check if the token is valid
if token.Valid {
return true, nil
}
return false, nil
}
You can use the generateToken()
function to generate a new token and the validateToken()
function to validate a token. Note that you need to replace "your-secret-key"
with your actual secret key. Additionally, you can add more claims or modify the code as per your requirements.