Skip to content

JWT Auth ​

Added: v1.1.0 - Token issuing added in v1.5.0

JWT authentication using RS256, HS256, or any asymmetric algorithm. Validates the Authorization: Bearer <token> header.

Basic Usage ​

go
import (
    "github.com/golang-jwt/jwt/v5"

    "github.com/Pavan-Silva/go-zen/auth"
)

jwtAuth := &auth.JWTAuth{
    Secret:        []byte("your-secret-key"),
    SigningMethod: jwt.SigningMethodHS256,
}

r.EnableAuth(jwtAuth)

Issuing Tokens ​

Generate signs a token with the adapter's own Secret and SigningMethod - no duplication of key material at the call site. It copies the claim map, sets iat, and sets exp from the expiry duration:

go
token, err := jwtAuth.Generate(jwt.MapClaims{
    "sub":   "user-123",
    "roles": []string{"user"},
}, 24*time.Hour)

Verifying Tokens ​

Parse verifies a raw token string against the same Secret and SigningMethod and returns the claims. Use it wherever you receive tokens outside the HTTP middleware flow (websockets, background jobs, other services):

go
claims, err := jwtAuth.Parse(tokenString)
if err != nil {
    // invalid signature, expired, wrong algorithm, ...
}

Both methods validate the adapter configuration first and return an error when SigningMethod is nil or Secret is empty - misconfiguration surfaces immediately instead of at request time.

go
jwtAuth := &auth.JWTAuth{
    Secret:        publicKeyPEM,
    SigningMethod: jwt.SigningMethodRS256,
}

Custom Claims ​

go
type CustomClaims struct {
    Role string `json:"role"`
}

jwtAuth := &auth.JWTAuth{
    Secret:        []byte("secret"),
    SigningMethod: jwt.SigningMethodHS256,
    ClaimsFunc: func(claims jwt.MapClaims) *zen.User {
        return &zen.User{
            ID:       claims["sub"].(string),
            Username: claims["preferred_username"].(string),
            Roles:    []string{"user"},
            Claims:   claims,
        }
    },
}

User from JWT ​

The Authenticate method extracts claims and populates the User struct:

go
user := c.GetUser()
user.ID       // "sub" claim
user.Username // "username" claim, falling back to "name"
user.Roles    // "roles" claim (array) or "role" claim (single name)
user.Claims   // full claim map (includes "scope"/"authorities" for business logic)

Released under the MIT License.