Documentation
¶
Overview ¶
Package auth provides authentication and authorization building blocks: a transport-neutral Principal carried in context, credential extraction from HTTP requests, a pluggable Verifier (token -> Principal), a built-in JWT verifier, and net/http middleware for authentication and role-based access control.
The Verifier seam keeps the middleware independent of the token format: the bundled JWTVerifier covers HMAC and RSA/ECDSA (and JWKS via a custom Keyfunc), but any Verifier — an opaque-token introspection client, a test stub — plugs in the same way. Rejections are written as *errs.Error JSON with the right status (401/403), each carrying an i18n MessageID.
Usage ¶
Build a Verifier, then compose the middleware onto your router. Authenticate both verifies and requires a token; RequireRole gates by role:
v, err := auth.NewJWTVerifier(auth.JWTConfig{
HMACSecret: []byte(secret),
Issuer: "myapp",
Audience: "myapp-api",
})
if err != nil {
return err
}
mux.Handle("/me", auth.Authenticate(v, log)(meHandler))
mux.Handle("/admin",
auth.Authenticate(v, log)(auth.RequireRole("admin")(adminHandler)))
// Inside a handler, read the verified identity:
func meHandler(w http.ResponseWriter, r *http.Request) {
p, ok := auth.PrincipalFromContext(r.Context())
if !ok {
return
}
_ = p.Subject
if p.HasRole("admin") { /* ... */ }
}
Principal ¶
Principal is the authenticated identity (Subject, Roles, and the full verified Claims). HasRole / HasAnyRole answer authorization questions; HasAnyRole with no arguments returns true (authentication alone suffices). WithPrincipal and PrincipalFromContext move it through the request context.
Credential extraction ¶
BearerToken pulls a token from "Authorization: Bearer <token>" (case-insensitive scheme); APIKey reads a named header such as "X-API-Key".
Middleware ¶
Each guard comes in two forms: net/http middleware for a raw handler, and a rest.MidFunc (the App suffix) for a typed route, which returns the rejection as an *errs.Error for rest.Respond to encode:
- Authenticate / AuthenticateApp — extract, verify, and require a token (401 on failure).
- Optional / OptionalApp — verify when present, never reject; an invalid token is ignored.
- RequireAuthenticated / RequireAuthenticatedApp — reject requests with no Principal (place after Optional).
- RequireRole / RequireRoleApp — 401 when unauthenticated, 403 when authenticated without a required role.
Guard seals AuthenticateApp and RequireRoleApp into one rest.MidFunc, the usual guard of a typed route. It is nil, a public route, when the verifier is nil, so a service builds it unconditionally:
handle("POST /widgets", h.create, auth.Guard(v, "admin"))
JWTConfig ¶
Exactly one key source must be set: HMACSecret, RSAPublicKeyPEM, ECPublicKeyPEM, or a custom Keyfunc (use the latter for JWKS). Other fields:
- ValidMethods — accepted "alg" values; defaults derive from the key source (HS*/RS*/ES*) and are required when using Keyfunc.
- Issuer / Audience — validated against the token claims when set.
- Leeway — clock-skew tolerance for time-based claims.
- SubjectClaim — principal-id claim (default "sub").
- RolesClaim — roles claim (default "roles"); accepts a JSON array of strings or a single space-separated string.
NewJWTVerifier always requires expiration and restricts accepted algorithms, so "alg":"none" and algorithm-confusion attacks are rejected.
Example ¶
Guard verifies the bearer token and requires a role in one rest.MidFunc: no token is a 401, a token without the role a 403. The handler reads the verified identity from the context.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/assanoff/skit/auth"
"github.com/assanoff/skit/rest"
"github.com/assanoff/skit/rest/router"
)
var secret = []byte("an-hmac-secret-of-32-bytes-long!")
// sign issues the token an identity provider would: HS256 with the subject,
// the roles, the issuer and an expiry.
func sign(sub string, roles ...string) string {
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": sub,
"roles": roles,
"iss": "shop",
"exp": time.Now().Add(time.Hour).Unix(),
})
s, err := tok.SignedString(secret)
if err != nil {
panic(err)
}
return s
}
// call sends method path with the bearer token, if any, to h and prints the
// status and the body.
func call(h http.Handler, method, path, token string) {
req := httptest.NewRequest(method, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
fmt.Println(strings.TrimSpace(fmt.Sprintf("%d %s", w.Code, w.Body)))
}
func main() {
v, err := auth.NewJWTVerifier(auth.JWTConfig{HMACSecret: secret, Issuer: "shop"})
if err != nil {
fmt.Println(err)
return
}
r := router.New()
r.HandleApp("DELETE /widgets/{id}", func(ctx context.Context, _ *http.Request) rest.ResponseEncoder {
p, _ := auth.PrincipalFromContext(ctx)
return rest.JSON(map[string]string{"deleted_by": p.Subject})
}, auth.Guard(v, "admin"))
call(r, http.MethodDelete, "/widgets/42", "")
call(r, http.MethodDelete, "/widgets/42", sign("u-1", "viewer"))
call(r, http.MethodDelete, "/widgets/42", sign("u-2", "admin"))
}
Output: 401 {"code":"unauthenticated","detail":"missing bearer token"} 403 {"code":"permission_denied","detail":"insufficient permissions"} 200 {"deleted_by":"u-2"}
Index ¶
- func APIKey(r *http.Request, header string) (string, bool)
- func AuthenticateApp(v Verifier) rest.MidFunc
- func BearerToken(r *http.Request) (string, bool)
- func Guard(v Verifier, roles ...string) rest.MidFunc
- func OptionalApp(v Verifier) rest.MidFunc
- func RequireAuthenticatedApp() rest.MidFunc
- func RequireRoleApp(roles ...string) rest.MidFunc
- func WithPrincipal(ctx context.Context, p *Principal) context.Context
- type JWTConfig
- type JWTVerifier
- type Middleware
- type Principal
- type Verifier
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func APIKey ¶
APIKey extracts a token from the named header (e.g. "X-API-Key").
Example ¶
APIKey reads a credential from a named header; a middleware of the service verifies it and stores the Principal with WithPrincipal.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/assanoff/skit/auth"
)
// apiKeys is a Verifier of API keys: any credential plugs in behind the
// Verifier seam, not only a JWT.
type apiKeys map[string]*auth.Principal
func (k apiKeys) Verify(_ context.Context, key string) (*auth.Principal, error) {
p, ok := k[key]
if !ok {
return nil, errors.New("unknown api key")
}
return p, nil
}
func main() {
var v auth.Verifier = apiKeys{"k-123": {Subject: "partner-1", Roles: []string{"partner"}}}
partner := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key, _ := auth.APIKey(r, "X-Api-Key")
p, err := v.Verify(r.Context(), key)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r.WithContext(auth.WithPrincipal(r.Context(), p)))
})
}
h := partner(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, _ := auth.PrincipalFromContext(r.Context())
fmt.Fprintln(w, p.Subject, p.HasAnyRole("partner", "admin"))
}))
for _, key := range []string{"k-123", "k-000"} {
req := httptest.NewRequest(http.MethodGet, "/feed", nil)
req.Header.Set("X-Api-Key", key)
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
fmt.Println(strings.TrimSpace(fmt.Sprintf("%d %s", w.Code, w.Body)))
}
}
Output: 200 partner-1 true 401 unauthorized
func AuthenticateApp ¶
AuthenticateApp is the rest.MidFunc form of Authenticate: it extracts and verifies the bearer token and stores the resulting Principal in the context, then calls the next handler. Unlike Authenticate it does not write to the ResponseWriter; it returns an *errs.Error (Unauthenticated) so the failure flows through the typed handler chain and is encoded by rest.Respond. Use it as a per-route guard via the rest.Handle seam:
handle("POST /widgets", h.create, auth.AuthenticateApp(verifier))
func BearerToken ¶
BearerToken extracts a token from an "Authorization: Bearer <token>" header. The scheme match is case-insensitive.
func Guard ¶
Guard is the common case sealed into one rest.MidFunc: it composes AuthenticateApp and RequireRoleApp (via rest.Chain) so a single value verifies the bearer token, stores the Principal, and requires at least one of roles (authentication alone when no roles are given).
It returns nil when v is nil — a no-op that the rest.Handle seam and ChainMiddleware skip — so a caller can build it unconditionally and stay public when auth is disabled (the verifier is nil). Build it where you have the verifier and apply it at any level: a single route via the Handle seam, a group via router.WithApp, or the whole router via UseApp.
guard := auth.Guard(verifier, "admin") // nil (public) when verifier is nil
handle("POST /widgets", h.create, guard)
func OptionalApp ¶
OptionalApp is the rest.MidFunc form of Optional: it stores the Principal when a valid bearer token is present but never rejects the request. Pair it with RequireAuthenticatedApp or RequireRoleApp to enforce access per route.
Example ¶
OptionalApp reads a token when there is one and never rejects: a public route serves guests and members alike. A route that needs the identity adds RequireAuthenticatedApp.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/assanoff/skit/auth"
"github.com/assanoff/skit/rest"
"github.com/assanoff/skit/rest/router"
)
var secret = []byte("an-hmac-secret-of-32-bytes-long!")
// sign issues the token an identity provider would: HS256 with the subject,
// the roles, the issuer and an expiry.
func sign(sub string, roles ...string) string {
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": sub,
"roles": roles,
"iss": "shop",
"exp": time.Now().Add(time.Hour).Unix(),
})
s, err := tok.SignedString(secret)
if err != nil {
panic(err)
}
return s
}
// call sends method path with the bearer token, if any, to h and prints the
// status and the body.
func call(h http.Handler, method, path, token string) {
req := httptest.NewRequest(method, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
fmt.Println(strings.TrimSpace(fmt.Sprintf("%d %s", w.Code, w.Body)))
}
func main() {
v, err := auth.NewJWTVerifier(auth.JWTConfig{HMACSecret: secret})
if err != nil {
fmt.Println(err)
return
}
greet := func(ctx context.Context, _ *http.Request) rest.ResponseEncoder {
name := "guest"
if p, ok := auth.PrincipalFromContext(ctx); ok {
name = p.Subject
}
return rest.JSON(map[string]string{"hello": name})
}
r := router.New(auth.OptionalApp(v))
r.HandleApp("GET /hello", greet)
r.HandleApp("GET /orders", greet, auth.RequireAuthenticatedApp())
call(r, http.MethodGet, "/hello", "")
call(r, http.MethodGet, "/hello", sign("u-1"))
call(r, http.MethodGet, "/orders", "")
}
Output: 200 {"hello":"guest"} 200 {"hello":"u-1"} 401 {"code":"unauthenticated","detail":"authentication required"}
func RequireAuthenticatedApp ¶
RequireAuthenticatedApp is the rest.MidFunc form of RequireAuthenticated: it rejects requests that carry no Principal with Unauthenticated. Place it after OptionalApp, or use AuthenticateApp which both verifies and requires.
func RequireRoleApp ¶
RequireRoleApp is the rest.MidFunc form of RequireRole: it rejects requests whose Principal lacks at least one of roles — Unauthenticated when no principal is present, PermissionDenied when one is present without a required role. Called with no roles it denies every request (PermissionDenied); use RequireAuthenticatedApp for an authentication-only guard.
Types ¶
type JWTConfig ¶
type JWTConfig struct {
HMACSecret []byte
RSAPublicKeyPEM []byte
ECPublicKeyPEM []byte
// Keyfunc overrides the key sources above (e.g. JWKS). When set, ValidMethods
// should list the algorithms you accept.
Keyfunc jwt.Keyfunc
// ValidMethods restricts accepted "alg" values. Defaults are derived from the
// configured key source (HS*/RS*/ES*); set explicitly when using Keyfunc.
ValidMethods []string
// Issuer / Audience, when set, are validated against the token claims.
Issuer string
Audience string
// Leeway tolerates small clock skew on time-based claims.
Leeway time.Duration
// SubjectClaim names the principal-id claim (default "sub").
SubjectClaim string
// RolesClaim names the roles claim (default "roles"). Accepts a JSON array of
// strings or a single space-separated string.
RolesClaim string
}
JWTConfig configures the built-in JWT verifier. Exactly one key source must be set: HMACSecret, RSAPublicKeyPEM, ECPublicKeyPEM, or a custom Keyfunc (use the latter for JWKS — e.g. a keyfunc backed by a remote key set).
type JWTVerifier ¶
type JWTVerifier struct {
// contains filtered or unexported fields
}
JWTVerifier verifies JWTs and maps their claims to a Principal.
func NewJWTVerifier ¶
func NewJWTVerifier(cfg JWTConfig) (*JWTVerifier, error)
NewJWTVerifier builds a JWTVerifier from cfg.
type Middleware ¶
Middleware is standard net/http middleware (composes with router.Use).
func Authenticate ¶
func Authenticate(v Verifier, log *slog.Logger) Middleware
Authenticate extracts a bearer token, verifies it, and stores the resulting Principal in the request context. Requests without a valid token are rejected with 401. log may be nil.
Example ¶
Authenticate and RequireRole are the net/http forms, for a handler outside the typed layer.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/assanoff/skit/auth"
)
var secret = []byte("an-hmac-secret-of-32-bytes-long!")
// sign issues the token an identity provider would: HS256 with the subject,
// the roles, the issuer and an expiry.
func sign(sub string, roles ...string) string {
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": sub,
"roles": roles,
"iss": "shop",
"exp": time.Now().Add(time.Hour).Unix(),
})
s, err := tok.SignedString(secret)
if err != nil {
panic(err)
}
return s
}
// call sends method path with the bearer token, if any, to h and prints the
// status and the body.
func call(h http.Handler, method, path, token string) {
req := httptest.NewRequest(method, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
fmt.Println(strings.TrimSpace(fmt.Sprintf("%d %s", w.Code, w.Body)))
}
func main() {
v, err := auth.NewJWTVerifier(auth.JWTConfig{HMACSecret: secret})
if err != nil {
fmt.Println(err)
return
}
me := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, _ := auth.PrincipalFromContext(r.Context())
fmt.Fprintln(w, p.Subject, p.Roles, p.HasRole("admin"))
})
mux := http.NewServeMux()
mux.Handle("GET /me", auth.Authenticate(v, nil)(me))
mux.Handle("GET /admin", auth.Authenticate(v, nil)(auth.RequireRole("admin")(me)))
call(mux, http.MethodGet, "/me", "not-a-jwt")
call(mux, http.MethodGet, "/me", sign("u-1", "viewer"))
call(mux, http.MethodGet, "/admin", sign("u-1", "viewer"))
}
Output: 401 {"code":"unauthenticated","detail":"invalid token: auth: jwt: token is malformed: token contains an invalid number of segments"} 200 u-1 [viewer] false 403 {"code":"permission_denied","detail":"insufficient permissions"}
func Optional ¶
func Optional(v Verifier) Middleware
Optional verifies a bearer token when present and stores the Principal, but never rejects the request. Downstream handlers use PrincipalFromContext (or RequireAuthenticated) to enforce access. An invalid token is ignored.
func RequireAuthenticated ¶
func RequireAuthenticated() Middleware
RequireAuthenticated rejects requests that carry no Principal with 401. Place it after Optional, or use Authenticate which both verifies and requires.
func RequireRole ¶
func RequireRole(roles ...string) Middleware
RequireRole rejects requests whose Principal lacks at least one of roles: 401 when unauthenticated, 403 when authenticated without a required role. Called with no roles it denies every request with 403 (a role gate must name at least one role); use RequireAuthenticated for an authentication-only guard.
type Principal ¶
type Principal struct {
// Subject is the unique principal id (JWT "sub").
Subject string
// Roles are the principal's authorization roles.
Roles []string
// Claims carries the full, verified claim set for application use.
Claims map[string]any
}
Principal is the authenticated identity attached to a request context.
func PrincipalFromContext ¶
PrincipalFromContext returns the principal stored by the middleware, if any.
func (*Principal) HasAnyRole ¶
HasAnyRole reports whether the principal has at least one of roles. With no roles given it returns true (authentication alone suffices).