golang jwt example
To create a JWT authentication example in Go (Golang), follow these steps:
- Install the necessary packages:
go get github.com/dgrijalva/jwt-go
- Import the required packages in your Go file:
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"net/http"
"time"
)
- Define the key and token expiration time:
var mySigningKey = []byte("secret")
var expirationTime = time.Now().Add(time.Minute * 30).Unix()
- Create a function to generate the JWT token:
func GenerateJWT() (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["authorized"] = true
claims["user"] = "John Doe"
claims["exp"] = expirationTime
tokenString, err := token.SignedString(mySigningKey)
if err != nil {
return "", err
}
return tokenString, nil
}
- Create a handler to handle the token generation and validation:
func handleRequests(w http.ResponseWriter, r *http.Request) {
tokenString, err := GenerateJWT()
if err != nil {
fmt.Println("Error generating token:", err)
}
// Validate token here
}
- Run the server and test the JWT generation and validation:
func main() {
http.HandleFunc("/", handleRequests)
http.ListenAndServe(":9000", nil)
}
By following these steps, you can create a JWT authentication example in Go using the golang jwt package.