server

package
v0.17.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package server provides auth-specific ServerOption factories for github.com/dioad/net/http servers.

Index

Examples

Constants

View Source
const (
	// ValidatorCheckName is the name AddValidatorCheck registers the check under,
	// and so the key it has in a readiness report.
	ValidatorCheckName = "jwt-validators"

	// DefaultValidatorCheckTimeout caps the check and each of its requests. It is
	// below the 5s that Fly and lifecycle.DefaultCheckTimeout both use, so a hung
	// identity provider makes the check report degraded rather than the probe
	// itself time out.
	DefaultValidatorCheckTimeout = 2 * time.Second

	// DefaultValidatorCheckCacheTTL is how long a result is reused, so frequent
	// probes make at most one discovery and one JWKS request per issuer per
	// interval per instance.
	DefaultValidatorCheckCacheTTL = 30 * time.Second
)

Variables

This section is empty.

Functions

func APIMiddlewares added in v0.16.0

func APIMiddlewares(validators []oidc.ValidatorConfig, extractor auth.PrincipalExtractor, opts ...ValidatorHandlerOption) ([]nethttp.Middleware, error)

APIMiddlewares returns the authentication half of an API's middleware chain, in order: bearer token validation against validators, then principal extraction with extractor. Token validation is left out when there are no validators, which is the allow-unauthenticated case, so every request reaches the principal extractor with no token.

Put anything that must run before authentication, such as a header check, ahead of the result, and anything that needs the principal, such as a rate limiter keyed by principal, after it. opts are passed to OAuth2ValidatorHandler.

func AddValidatorCheck added in v0.17.0

func AddValidatorCheck(r *lifecycle.Readiness, validators []oidc.ValidatorConfig, opts ...lifecycle.CheckOption)

AddValidatorCheck adds a readiness check to r that every identity provider behind validators answers OIDC discovery and serves at least one signing key (see oidc.ProbeValidators). It adds nothing when no validator fetches keys: none configured, or all use a static HMAC secret.

The check is degraded, not failing: an identity provider outage affects every instance alike, so failing readiness would take the whole service out of rotation without moving traffic anywhere that could validate tokens. A pass means each issuer was reachable within DefaultValidatorCheckCacheTTL; it does not prove the validators' own key caches are current.

opts follow the defaults, so WithCheckTimeout or WithCacheTTL replaces them.

Example

ExampleAddValidatorCheck reports the identity provider behind a service's token validators as a readiness check. The check is degraded, not failing, so an identity provider outage shows in the report without taking the service out of rotation.

The example serves a minimal discovery document and key set so that it runs without a real provider.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/dioad/lifecycle"

	"github.com/dioad/auth/http/server"
	"github.com/dioad/auth/oidc"
)

func main() {
	var issuer *httptest.Server
	issuer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/.well-known/openid-configuration":
			_, _ = fmt.Fprintf(w, `{"issuer":%q,"jwks_uri":%q}`, issuer.URL, issuer.URL+"/jwks")
		case "/jwks":
			_, _ = fmt.Fprint(w, `{"keys":[{"kty":"RSA","kid":"k1"}]}`)
		default:
			http.NotFound(w, r)
		}
	}))
	defer issuer.Close()

	readiness := lifecycle.NewReadiness()
	server.AddValidatorCheck(readiness, []oidc.ValidatorConfig{{Issuer: issuer.URL}})
	readiness.MarkStarted()

	report, err := readiness.Ready(context.Background())
	fmt.Println(err)
	fmt.Println(report)
}
Output:
<nil>
map[jwt-validators:ok]

func OAuth2ValidatorHandler

func OAuth2ValidatorHandler(v []oidc.ValidatorConfig, opts ...ValidatorHandlerOption) (nethttp.Middleware, error)

OAuth2ValidatorHandler returns a middleware that validates OAuth2 bearer tokens using the provided configurations. A request without a token is rejected with 401.

The token is read from the Authorization header only. Pass WithCookieTokenName to also accept it from a cookie.

Example

ExampleOAuth2ValidatorHandler protects an API with JWT validation. The token is read from the Authorization header only: a valid token in a cookie is refused, so a browser cannot be made to call the API with credentials it attaches by itself.

The example validates tokens with a shared secret so that it runs without an identity provider. HMACSecret is for local development and tests only. A real configuration names an issuer, and the keys are fetched from it.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/golang-jwt/jwt/v5"

	"github.com/dioad/auth/http/server"
	"github.com/dioad/auth/oidc"
)

func main() {
	middleware, err := server.OAuth2ValidatorHandler([]oidc.ValidatorConfig{{
		HMACSecret:        "example-secret",
		AllowInsecureHMAC: true,
		Audiences:         []string{"my-api"},
	}})
	if err != nil {
		fmt.Println(err)
		return
	}

	api := middleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		_, _ = fmt.Fprintln(w, "hello")
	}))

	now := time.Now()
	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"sub": "alice",
		"iss": "https://idp.example",
		"aud": "my-api",
		"iat": now.Unix(),
		"exp": now.Add(time.Hour).Unix(),
	}).SignedString([]byte("example-secret"))
	if err != nil {
		fmt.Println(err)
		return
	}

	call := func(modify func(*http.Request)) int {
		req := httptest.NewRequest(http.MethodGet, "/", nil)
		modify(req)
		rr := httptest.NewRecorder()
		api.ServeHTTP(rr, req)
		return rr.Code
	}

	fmt.Println("bearer token:", call(func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+token) }))
	fmt.Println("no token:", call(func(*http.Request) {}))
	fmt.Println("token in a cookie:", call(func(r *http.Request) { r.AddCookie(&http.Cookie{Name: "auth_token", Value: token}) }))
	fmt.Println("bad token:", call(func(r *http.Request) { r.Header.Set("Authorization", "Bearer not-a-token") }))

}
Output:
bearer token: 200
no token: 401
token in a cookie: 401
bad token: 401

func WithOAuth2Validator

func WithOAuth2Validator(v []oidc.ValidatorConfig, opts ...ValidatorHandlerOption) nethttp.ServerOption

WithOAuth2Validator returns a ServerOption that configures the server to validate OAuth2 bearer tokens. See OAuth2ValidatorHandler for opts.

func WithServerAuth

func WithServerAuth(cfg authhttp.ServerConfig) nethttp.ServerOption

WithServerAuth returns a ServerOption that configures the server to use the given authentication configuration. When the resolved auth handler needs additional routes beyond the Wrap middleware chain (currently only OIDC's login/callback/logout flow), those routes are registered on the server's mux automatically.

Types

type ValidatorHandlerOption added in v0.15.0

type ValidatorHandlerOption func(*validatorHandlerOptions)

ValidatorHandlerOption configures the middleware built by OAuth2ValidatorHandler and WithOAuth2Validator.

func WithCookieTokenName added in v0.15.0

func WithCookieTokenName(name string) ValidatorHandlerOption

WithCookieTokenName also accepts a bearer token from the cookie called name. Without it the token is read from the Authorization header only.

Use it only for browser-facing routes. A machine-to-machine API that browsers can reach must not accept a cookie credential: that is a CSRF risk, and it couples the API to the cookie name of any browser app on the same origin.

func WithValidatorDebug added in v0.15.0

func WithValidatorDebug() ValidatorHandlerOption

WithValidatorDebug logs the outcome of every token validation through the request-scoped logger. See oidc.NewValidatorDebugger.

func WithValidatorOptions added in v0.15.0

func WithValidatorOptions(opts ...jwtvalidator.Option) ValidatorHandlerOption

WithValidatorOptions passes go-jwt-middleware validator options to every configured validator, for example validator.WithCustomClaims. They are base options: a validator config or provider type that sets the same thing overrides them. See oidc.NewMultiValidatorFromConfig.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL