golang jwt example

To create a JWT authentication example in Go (Golang), follow these steps:

  1. Install the necessary packages:
go get github.com/dgrijalva/jwt-go
  1. Import the required packages in your Go file:
import (
    "fmt"
    "github.com/dgrijalva/jwt-go"
    "net/http"
    "time"
)
  1. Define the key and token expiration time:
var mySigningKey = []byte("secret")
var expirationTime = time.Now().Add(time.Minute * 30).Unix()
  1. 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
}
  1. 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
}
  1. 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.