Help us shape the future of Go! Take the 2026 Go Developer Survey

authenticationhttp

package
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 9 Imported by: 1

Documentation

Overview

Package authenticationhttp provides strict HTTP credential extraction, challenges, and authentication-only middleware for net/http. Start with NewExtractor and NewMiddleware; sources read borrowed request headers/URL/cookies, never the body. Source byte bounds apply to selected values, not total header/query/ cookie parsing allocations; server request limits remain deployment-owned. See docs/specification-decisions.md for RFC9110/7617/6750 parsing profiles.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatChallenge

func FormatChallenge(challenge authentication.Challenge) (string, error)

FormatChallenge revalidates bounded challenge data and serializes sorted parameter names with quoted backslash/quote escaping. Invalid/zero challenges fail; values are protocol-screened, not confidentiality-classified. It owns one field value, not a whole response header-count budget (AUTH-DEC-007).

func NewMiddleware

func NewMiddleware(extractor CredentialExtractor, authenticator authentication.Authenticator, options ...MiddlewareOption) (func(http.Handler) http.Handler, error)

NewMiddleware validates nonnil/typed-nil collaborators and creates authentication-only middleware. Optional anonymous access applies only to extraction absence; other failures never authorize access. A 401 requires a valid failure/fallback challenge; otherwise refusal is a fixed-text 503. It shallow-copies request context, borrowing body/headers and next handler. Provider/handler/writer panics propagate, no additional cancellation barrier is imposed, and caller owns concurrency, request limits and lifetimes.

Example
package main

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

	authentication "github.com/faustbrian/go-authentication/v2"
	authhttp "github.com/faustbrian/go-authentication/v2/adapters/http"
	"github.com/faustbrian/go-authentication/v2/bearer"
)

func main() {
	extractor, _ := authhttp.NewExtractor(authhttp.BearerAuthorization())
	authenticator, _ := bearer.New(bearer.ValidatorFunc(
		func(_ context.Context, _ string) (authentication.Principal, error) {
			return authentication.NewPrincipal(authentication.PrincipalSpec{
				Subject: "service", Method: "bearer",
			})
		},
	))
	middleware, _ := authhttp.NewMiddleware(extractor, authenticator)
	handler := middleware(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) {
		principal, _ := authentication.PrincipalFromContext(request.Context())
		fmt.Println(principal.Subject())
	}))
	request := httptest.NewRequest(http.MethodGet, "/", nil)
	request.Header.Set("Authorization", "Bearer token")
	handler.ServeHTTP(httptest.NewRecorder(), request)
}
Output:
service

Types

type APIKeyOption

type APIKeyOption func(*apiKeySource)

APIKeyOption configures an API-key source.

func WithAPIKeyMaxBytes

func WithAPIKeyMaxBytes(maximum int) APIKeyOption

WithAPIKeyMaxBytes sets the inclusive API-key size bound.

type BearerOption

type BearerOption func(*authorizationSource)

BearerOption configures a bearer source.

func WithBearerMaxBytes

func WithBearerMaxBytes(maximum int) BearerOption

WithBearerMaxBytes sets the inclusive bearer-token size bound.

func WithBearerPipe

func WithBearerPipe() BearerOption

WithBearerPipe permits the pipe character in an opaque bearer credential.

RFC 6750 bearer syntax rejects pipes by default. Enable this option only for an existing credential contract that uses a pipe-delimited opaque token.

type CredentialExtractor

type CredentialExtractor interface {
	// Extract must refuse malformed/ambiguous input and identify absent credentials
	// with ErrCredentialsAbsent. Borrow request/body without mutation or hidden IO;
	// providers reused across requests must support concurrency. The middleware
	// does not contain collaborator panics or preempt their blocking work.
	Extract(*http.Request) (authentication.Credential, error)
}

CredentialExtractor extracts one typed credential from an HTTP request.

type Extractor

type Extractor struct {
	// contains filtered or unexported fields
}

Extractor rejects ambiguous credentials across all enabled sources.

func NewExtractor

func NewExtractor(sources ...Source) (*Extractor, error)

NewExtractor validates/copies one or more sources; there is no source-count cap. Built-in source configurations are immutable. Requests must not mutate concurrently with Extract; the extractor owns no request/body lifecycle.

func (*Extractor) Extract

func (e *Extractor) Extract(request *http.Request) (authentication.Credential, error)

Extract returns exactly one credential or a classified failure, evaluating enabled sources in order. Nil request fails invalid. The first source error takes precedence; otherwise multiple enabled credentials fail ambiguous. It does not mutate the request, honor its cancellation or normalize credentials.

type MiddlewareOption

type MiddlewareOption func(*middlewareConfig) error

MiddlewareOption configures HTTP authentication middleware.

func WithChallenges

func WithChallenges(challenges ...authentication.Challenge) MiddlewareOption

WithChallenges configures fallback challenges for authentication failures.

func WithOptionalAnonymous

func WithOptionalAnonymous() MiddlewareOption

WithOptionalAnonymous permits anonymous access only when credentials are absent.

Example
package main

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

	authentication "github.com/faustbrian/go-authentication/v2"
	authhttp "github.com/faustbrian/go-authentication/v2/adapters/http"
	"github.com/faustbrian/go-authentication/v2/bearer"
)

func main() {
	extractor, _ := authhttp.NewExtractor(authhttp.BearerAuthorization())
	authenticator, _ := bearer.New(bearer.ValidatorFunc(
		func(context.Context, string) (authentication.Principal, error) {
			return authentication.Principal{}, authentication.NewFailure(authentication.FailureRejected)
		},
	))
	middleware, _ := authhttp.NewMiddleware(extractor, authenticator, authhttp.WithOptionalAnonymous())
	handler := middleware(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) {
		principal, found := authentication.PrincipalFromContext(request.Context())
		fmt.Println(found, principal.IsAnonymous())
	}))
	handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
}
Output:
true true

type Source

type Source interface {
	// contains filtered or unexported methods
}

Source is an explicitly enabled HTTP credential location. Its private methods restrict implementations to this package; factory options are validated when passed to NewExtractor, not necessarily at factory invocation.

func APIKeyCookie

func APIKeyCookie(idCookie, keyCookie string, options ...APIKeyOption) Source

APIKeyCookie explicitly enables API-key extraction from two cookies.

func APIKeyHeader

func APIKeyHeader(idHeader, keyHeader string, options ...APIKeyOption) Source

APIKeyHeader explicitly enables API-key extraction from two headers.

func APIKeyQuery deprecated

func APIKeyQuery(idParameter, keyParameter string, options ...APIKeyOption) Source

APIKeyQuery explicitly enables API-key extraction from two query parameters.

Deprecated: credentials in URLs can be retained by logs, proxies, and browser history. Prefer APIKeyHeader for new designs.

func BasicAuthorization

func BasicAuthorization() Source

BasicAuthorization enables strict padded Base64 extraction with an inclusive 8 KiB decoded username/password total bound. Split at the first colon; empty password is representable, though Static rejects it. Bytes are not transcoded or normalized. AUTH-DEC-001/002 preserve scheme/encoding policy.

func BearerAuthorization

func BearerAuthorization(options ...BearerOption) Source

BearerAuthorization enables bearer extraction from the Authorization header.

func BearerCookie

func BearerCookie(name string, options ...BearerOption) Source

BearerCookie explicitly enables bearer extraction from a cookie.

func BearerQuery deprecated

func BearerQuery(name string, options ...BearerOption) Source

BearerQuery explicitly enables bearer extraction from a query parameter.

Deprecated: credentials in URLs can be retained by logs, proxies, and browser history. Prefer BearerAuthorization for new designs.

Jump to

Keyboard shortcuts

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