server

package
v0.16.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: 9 Imported by: 0

Documentation

Overview

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

Index

Examples

Constants

This section is empty.

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 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