middleware

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 4 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package middleware adapts authentication.Authenticator to transports. It depends only on the standard library and the authentication contracts so that it can be imported without pulling in protocol implementations.

Index

Examples

Constants

View Source
const (
	// SourceAttribute names the transport location the credential came from.
	SourceAttribute = "source"
	// SourceAuthorization marks credentials from an Authorization value.
	SourceAuthorization = "authorization"
	// SourceCookie marks credentials from a cookie.
	SourceCookie = "cookie"
)

Credential attribute names and values set by this package.

View Source
const MaxAuthorizationBytes = 16 << 10

MaxAuthorizationBytes bounds Authorization values accepted by CredentialFromAuthorizationHeader.

Variables

This section is empty.

Functions

func CredentialFromAuthorizationHeader

func CredentialFromAuthorizationHeader(value string) (authentication.Credential, error)

CredentialFromAuthorizationHeader parses an RFC 6750 "Bearer" Authorization value, as used by HTTP headers and gRPC "authorization" metadata. Tokens in JWS compact form are returned with Kind authentication.CredentialKindJWT; all other tokens with authentication.CredentialKindBearer. The scheme is case-insensitive and the token must be an RFC 6750 b64token.

It returns authentication.ErrUnauthenticated for an empty value, authentication.ErrUnsupportedCredential for another scheme, and authentication.ErrInvalidCredential for a malformed bearer value. Errors never contain the value.

func HTTP

func HTTP(next http.Handler, auth authentication.Authenticator, options ...Option) http.Handler

HTTP returns a handler that authenticates requests with auth and stores the principal with authentication.ContextWithPrincipal before calling next.

Credentials come from a single "Authorization: Bearer" header (see CredentialFromAuthorizationHeader) or, when configured, a single cookie. Missing credentials and other Authorization schemes yield 401 (a scheme other than Bearer is rejected even WithAnonymous), malformed or ambiguous credentials 400, and rejected credentials 401, each with an RFC 6750 WWW-Authenticate challenge and a generic body that never includes credential material or authenticator errors.

HTTP panics when next or auth is nil or an option is invalid.

Example
package main

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

	"github.com/justusschock/auth/authentication"
	"github.com/justusschock/auth/authentication/middleware"
)

// staticAuthenticator accepts one fixed bearer token.
type staticAuthenticator struct{}

func (staticAuthenticator) Authenticate(_ context.Context, credential authentication.Credential) (authentication.Principal, error) {
	if string(credential.Token) != "let-me-in" {
		return authentication.Principal{}, authentication.ErrUnauthenticated
	}
	return authentication.Principal{ID: "issuer|alice", Subject: "alice"}, nil
}

func main() {
	app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		principal, _ := authentication.PrincipalFromContext(r.Context())
		_, _ = fmt.Fprintf(w, "hello %s", principal.Subject)
	})
	handler := middleware.HTTP(app, authentication.Chain(staticAuthenticator{}), middleware.WithRealm("example"))

	for _, header := range []string{"Bearer let-me-in", "Bearer wrong"} {
		request := httptest.NewRequest(http.MethodGet, "/", nil)
		request.Header.Set("Authorization", header)
		recorder := httptest.NewRecorder()
		handler.ServeHTTP(recorder, request)
		if recorder.Code == http.StatusOK {
			fmt.Println(recorder.Code, recorder.Body.String())
			continue
		}
		fmt.Println(recorder.Code, recorder.Header().Get("WWW-Authenticate"))
	}
}
Output:
200 hello alice
401 Bearer realm="example", error="invalid_token"

Types

type Option

type Option func(*config)

Option configures HTTP.

func WithAnonymous

func WithAnonymous() Option

WithAnonymous passes requests that carry no credential to the next handler without a principal. Requests that carry an invalid credential are still rejected.

func WithCookie

func WithCookie(name string, kind string) Option

WithCookie also reads credentials of the given kind from the named cookie when no Authorization header is present. Cookie authentication is vulnerable to cross-site request forgery; callers must add CSRF protection (for example SameSite cookies plus origin checks) for state-changing routes.

func WithMaxTokenBytes

func WithMaxTokenBytes(limit int) Option

WithMaxTokenBytes bounds accepted token sizes. The default is 8 KiB.

func WithRealm

func WithRealm(realm string) Option

WithRealm sets the realm reported in WWW-Authenticate challenges. It must be printable ASCII without quotes or backslashes.

Jump to

Keyboard shortcuts

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