This repository contains shared Go packages for the Booking Eco microservices ecosystem.
The auth middleware provides JWT token verification using asymmetric encryption (RS256). It verifies tokens issued by the authentication service using the public key provided in the consuming application's environment variables.
go get booking-eco/shared
The JWT middleware verifies tokens and adds user claims to the request context.
package main
import (
"fmt"
"net/http"
"booking-eco/shared/middleware/auth"
)
func main() {
// Create a protected route with default configuration
http.Handle("/api/protected", auth.VerifyJWT()(http.HandlerFunc(protectedHandler)))
// Create a route that requires specific scopes
http.Handle("/api/admin", auth.VerifyJWTWithScopes("admin")(http.HandlerFunc(adminHandler)))
// Start the server
http.ListenAndServe(":8080", nil)
}
func protectedHandler(w http.ResponseWriter, r *http.Request) {
// Extract user ID from the token
userID, err := auth.ExtractUserID(r)
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
fmt.Fprintf(w, "Hello, User %s!", userID)
}
func adminHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, Admin!")
}
The middleware requires the public key to be set in the environment variable:
export JWT_PUBLIC_KEY="$(cat public.pem)"
You can customize the environment variable name:
config := auth.DefaultConfig()
config.PublicKeyEnv = "MY_CUSTOM_PUBLIC_KEY_ENV"
http.Handle("/api/custom", auth.VerifyJWTWithConfig(config)(http.HandlerFunc(customHandler)))
By default, tokens are extracted from the Authorization header. You can provide a custom extractor:
config := auth.DefaultConfig()
config.TokenExtractor = func(r *http.Request) (string, error) {
return r.URL.Query().Get("token"), nil
}
http.Handle("/api/query-token", auth.VerifyJWTWithConfig(config)(http.HandlerFunc(queryTokenHandler)))
You can access the full claims object:
func userHandler(w http.ResponseWriter, r *http.Request) {
claims, err := auth.GetClaims(r.Context())
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
fmt.Fprintf(w, "User: %s, Email: %s", claims.UserID, claims.Email)
}
- Always store your public key securely in environment variables
- Never log or expose the token content in production
- Use HTTPS in production environments
- Consider setting appropriate token expiration times
MIT License