auth

package
v5.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: BSD-3-Clause Imports: 22 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.

README

go-http/v4/auth

Go package to provide a simple interface for enforcing authentication in HTTP handlers.

Motivation

The go-http-auth package aims to provide a simple interface for enforcing authentication in Go-based web applications in a way that those applications don't need to know anything about how authentication happens.

// type Authenticator is a simple interface for	enforcing authentication in HTTP handlers.
type Authenticator interface {
	// WrapHandler wraps a `http.Handler` with any implementation-specific middleware.
	WrapHandler(http.Handler) http.Handler
	// GetAccountForRequest returns an `Account` instance  for an HTTP request.
	GetAccountForRequest(*http.Request) (Account, error)
	// SigninHandler returns a `http.Handler` for implementing account signin.
	SigninHandler() http.Handler
	// SignoutHandler returns a `http.Handler` for implementing account signout.
	SignoutHandler() http.Handler
	// SignupHandler returns a `http.Handler` for implementing account signups.
	SignupHandler() http.Handler
}

All the web application (specifically its net/http.Handler instances) know is that it has an implementation of the auth.Authenticator interface which exposes a GetAccountForRequest method which returns an implementation of the auth.Account interface or an error.

// type Account is an interface that defines minimal information for an account.
type Account interface {
	// The unique ID associated with this account.	
	Id() string
	// The name associated with this account.
	Name() string
}

Account interfaces/implementations meant to be accurate reflections of the underlying implementation's account structure but rather a minimalist struct containing on an account name and unique identifier.

Here is a simplified example, with error handling omitted for brevity, that uses the built-in null:// Authenticator implementation (that will always return a Account instance with ID "-1"):

package main

import (
     "context"	
     "log"
     "net/http"

     "github.com/aaronland/go-http/v5/auth"
)

type HandlerOptions struct {
     Authenticator auth.Authenticator
}

func Handler(opts *HandlerOptions) (http.Handler, error) {

	fn := func(rsp http.ResponseWriter, req *http.Request) {

		acct, err := opts.Authenticator.GetAccountForRequest(req)

		if err != nil {
			switch err.(type) {
			case auth.NotLoggedIn:
				signin_handler := opts.Authenticator.SigninHandler()
				signin_handler.ServeHTTP(rsp, req)
				return

			default:
				http.Error(rsp, "Internal server error", http.StatusInternalServerError)
				return
			}
		}

		log.Printf("Authenticated as %s (%d)\n", acct.Name(), acct.Id())
		
		... carry on with handler
	}

	return http.HandlerFunc(fn), nil
}

func main (){

     ctx := context.Background()
     
     authenticator, _ := auth.NewAuthenticator(ctx, "null://")

     handler_opts := &HandlerOptions{
     	Authenticator: authenticator,
     }
     
     handler, _ := Handler(handler_opts)
     handler = authenticator.WrapHandler(handler)
     
     mux := http.NewServeMux()

     mux.Handle("/", handler)

     http.ListenAndServe(":8080", mux)
}

Note the use the of the authenticator.WrapHandler() method. This is a net/http "middleware" handler where implementation-specific logic for checking whether a user is authenticated is expected to happen. That information is expected to be retrievable using the GetAccountForRequest method in the subsequent handlers that WrapHandler serves. The details of how authentication information is stored and retrieved between handlers is left to individual implmentations.

For concrete examples, have a look at the code for cmd/auth/example/main.go.

Authenticators

The following Authenticator implementations are included by default:

jwt://

Generate signing secrets with go run ./cmd/auth/jwt-secret (256 characters by default, or -length from 1 to 1048576). The command uses github.com/aaronland/go-string/random.Bytes, backed by crypto/rand, and maps bytes without bias to the URL-safe alphabet a-zA-Z0-9-_. Each output character contributes 6 bits of entropy; use at least 43 characters for 256 bits. Rotate any signing secrets generated by older versions of this command, which used timestamp-seeded pseudorandomness. Rotation invalidates JWTs signed with the old secret.

JWTAuthenticator implements the Authenticator interface to ensure that requests contain a "Authorization: Bearer {JWT_TOKEN}"` HTTP header configured by 'uri' which is expected to take the form of:

jwt://{SECRET}

Where {SECRET} is expected to be the shared JWT signing secret passed by HTTP requests. Or:

jwt://runtimevar?runtimevar-uri={GOCLOUD_DEV_RUNTIMEVAR_URI}

Where {GOCLOUD_DEV_RUNTIMEVAR_URI} is a valid gocloud.dev/runtimevar URI used to dereference the JWT signing secret. Under the hood this method using the aaronland/gocloud/runtimevar.StringVar method to dereference runtimevar URIs.

By default a JWTAuthenticator instance looks for JWT Bearer tokens in the HTTP "Authorization" header (falling back to the legacy "Authentication" header). This behaviour can be customized by passing an "authorization-header" query parameter in 'uri'. For example:

jwt://?authorization-header=X-Custom-AuthHeader

JWT payloads are expected to conform to the JWTAuthenticatorClaims struct:

type JWTAuthenticatorClaims struct {
	// The unique ID associated with this account.
	AccountId   string  `json:"account_id"`
	// The name associated with this account.	
	AccountName string `json:"account_name"`
	jwt.RegisteredClaims
}
none://

NoneAuthenticator implements the Authenticator interface and always returns a "Not authorized" error. It is instantiated with the following URI construct:

none://
null://

NullAuthenticator implements the Authenticator interface such that no authentication is performed. It is instantiated with the following URI construct:

null://
sharedsecret://

SharedSecretAuthenticator implements the Authenticator interface to require a simple shared secret be passed with all requests. This is not a sophisticated handler. There are no nonces or hashing of requests or anything like that. It is a bare-bones supplementary authentication handler for environments that already implement their own measures of access control. It is instantiated with the following URI construct:

sharedsecret://{SECRET}

Where {SECRET} is expected to be the shared secret passed by HTTP requests in the X-Shared-Secret header.

See also

Documentation

Overview

Package auth provides a common interface for enforcing authentication in HTTP handlers, along with several implementations (JWT, OpenID Connect, shared secret, null and none).

Index

Constants

View Source
const AUTHORIZATION_HEADER string = "Authorization"

AUTHORIZATION_HEADER is the default name of the HTTP header that is checked for a bearer JWT.

View Source
const LEGACY_AUTHORIZATION_HEADER string = "Authentication"

LEGACY_AUTHORIZATION_HEADER is the non-standard header name that was the default in earlier releases. It is still accepted as a fallback when the default header is in use.

View Source
const SHARED_SECRET_ACCOUNT_ID string = "-1"

SHARED_SECRET_ACCOUNT_ID is the account ID used for `Account` instances when shared secret authentication validates.

View Source
const SHARED_SECRET_ACCOUNT_NAME string = "sharedsecret"

SHARED_SECRET_ACCOUNT_NAME is the account name used for `Account` instances when shared secret authentication validates.

View Source
const SHARED_SECRET_HEADER string = "X-Shared-Secret"

SHARED_SECRET_HEADER is the name of the HTTP header to check for "shared secret" authentication.

Variables

This section is empty.

Functions

func EnsureAccountHandler

func EnsureAccountHandler(authenticator Authenticator, next go_http.Handler) go_http.Handler

EnsureAccountHandler is a middleware `net/http` handler that wraps 'next' and ensures that the authenticator.GetAccountForRequest method does not return an error. If it does, an HTTP "500 Internal Server Error" is returned.

func MustRegisterAuthenticator

func MustRegisterAuthenticator(ctx context.Context, scheme string, init_func AuthenticatorInitializationFunc)

MustRegisterAuthenticator calls `RegisterAuthenticator` and panics if registration fails.

func RegisterAuthenticator

func RegisterAuthenticator(ctx context.Context, scheme string, init_func AuthenticatorInitializationFunc) error

RegisterAuthenticator registers 'scheme' as a key pointing to 'init_func' in an internal lookup table used to create new `Authenticator` instances by the `NewAuthenticator` method.

func Schemes

func Schemes() []string

Schemes returns the list of schemes that have been registered.

Types

type Account

type Account interface {
	// Id returns the unique ID associated with this account.
	Id() string
	// Name returns the name associated with this account.
	Name() string
}

Account is an interface that defines minimal information for an account.

func NewAccount

func NewAccount(id string, name string) Account

NewAccount returns a new instance of `BasicAccount` (which implements the `Account` interface) for 'id' and 'name'.

type AccountNotExist

type AccountNotExist struct{}

AccountNotExist defines a well-known error for signaling that a given account does not exist.

func (AccountNotExist) Error

func (e AccountNotExist) Error() string

Error returns a human-readable representation of the `AccountNotExist` error.

type Authenticator

type Authenticator interface {
	// WrapHandler wraps a `http.Handler` with any implementation-specific middleware.
	WrapHandler(http.Handler) http.Handler
	// GetAccountForRequest returns an `Account` instance for an HTTP request.
	GetAccountForRequest(*http.Request) (Account, error)
	// SigninHandler returns a `http.Handler` for implementing account signin.
	SigninHandler() http.Handler
	// SignoutHandler returns a `http.Handler` for implementing account signout.
	SignoutHandler() http.Handler
	// SignupHandler returns a `http.Handler` for implementing account signups.
	SignupHandler() http.Handler
}

Authenticator is a simple interface for enforcing authentication in HTTP handlers.

func NewAuthenticator

func NewAuthenticator(ctx context.Context, uri string) (Authenticator, error)

NewAuthenticator returns a new `Authenticator` instance configured by 'uri'. The value of 'uri' is parsed as a `url.URL` and its scheme is used as the key for a corresponding `AuthenticatorInitializationFunc` function used to instantiate the new `Authenticator`. It is assumed that the scheme (and initialization function) have been registered by the `RegisterAuthenticator` method.

func NewJWTAuthenticator

func NewJWTAuthenticator(ctx context.Context, uri string) (Authenticator, error)

NewJWTAuthenticator implements the Authenticator interface to ensure that requests contain a `Authorization: Bearer {JWT_TOKEN}` HTTP header configured by 'uri' which is expected to take the form of:

jwt://{SECRET}

Where {SECRET} is expected to be the shared JWT signing secret passed by HTTP requests. Or:

jwt://runtimevar?runtimevar-uri={GOCLOUD_DEV_RUNTIMEVAR_URI}

Where {GOCLOUD_DEV_RUNTIMEVAR_URI} is a valid `gocloud.dev/runtimevar` URI used to dereference the JWT signing secret. Under the hood this method uses the `github.com/aaronland/gocloud/runtimevar.StringVar` method to dereference runtimevar URIs.

By default a `JWTAuthenticator` instance looks for JWT Bearer tokens in the HTTP "Authorization" header (falling back to the legacy "Authentication" header). This behaviour can be customized by passing an "authorization-header" query parameter in 'uri'. For example:

jwt://?authorization-header=X-Custom-AuthHeader

func NewNoneAuthenticator

func NewNoneAuthenticator(ctx context.Context, uri string) (Authenticator, error)

NewNoneAuthenticator returns a new `NoneAuthenticator` that always returns a "not authorized" error. It is configured by 'uri' which is expected to take the form of:

none://

func NewNullAuthenticator

func NewNullAuthenticator(ctx context.Context, uri string) (Authenticator, error)

NewNullAuthenticator returns a new `NullAuthenticator` that performs no authentication. It is configured by 'uri' which is expected to take the form of:

null://

func NewOIDCAuthenticator

func NewOIDCAuthenticator(ctx context.Context, uri string) (Authenticator, error)

NewOIDCAuthenticator returns a new `OIDCAuthenticator` configured by 'uri' which is expected to take the form of:

oidc://?issuer={URL}&client_id={ID}&redirect_uri={URL}&cookie_secret={SECRET}&cookie_salt={SALT}

Required parameters:

  • issuer: the OpenID Connect issuer URL. Endpoints are found using {issuer}/.well-known/openid-configuration.
  • client_id: the registered client ID.
  • redirect_uri: the registered callback URL. Requests to its path are handled by this authenticator (see WrapHandler).
  • cookie_secret, cookie_salt: used to encrypt the session cookies. The secret must be exactly 32 bytes (see cookie.NewRandomEncryptedCookieSecret).

Optional parameters:

  • client_secret: the client secret, for confidential clients (omit for public clients).
  • scope: space-separated scopes (default "openid profile email").
  • cookie_name: the session cookie name (default "oidc_session"). Transient state is kept in "{name}_state".
  • session_ttl: how long a session lasts, as a Go duration (default 24h).
  • secure_cookies: set the "Secure" cookie flag (default true unless redirect_uri is http).
  • signup_uri: where SignupHandler redirects to (default: HTTP 404).
  • signout_uri: where SignoutHandler redirects to after clearing the session (default "/").

func NewSharedSecretAuthenticator

func NewSharedSecretAuthenticator(ctx context.Context, uri string) (Authenticator, error)

NewSharedSecretAuthenticator implements the Authenticator interface to ensure that requests contain a `X-Shared-Secret` HTTP header configured by 'uri' which is expected to take the form of:

sharedsecret://{SECRET}

Where {SECRET} is expected to be the shared secret passed by HTTP requests.

type AuthenticatorInitializationFunc

type AuthenticatorInitializationFunc = roster.Factory[Authenticator]

AuthenticatorInitializationFunc is a function defined by individual authenticator packages and used to create an instance of that authenticator.

type BasicAccount

type BasicAccount struct {
	Account `json:",omitempty"`
	// The unique ID associated with this account.
	AccountId string `json:"id"`
	// The name associated with this account.
	AccountName string `json:"name"`
}

BasicAccount is the simplest (most basic) implementation of the `Account` interface for wrapping a unique account ID and an account name.

func (*BasicAccount) Id

func (a *BasicAccount) Id() string

Id returns the unique ID associated with 'a'.

func (*BasicAccount) Name

func (a *BasicAccount) Name() string

Name returns the name associated with 'a'.

type JWTAuthenticator

type JWTAuthenticator struct {
	Authenticator
	// contains filtered or unexported fields
}

JWTAuthenticator implements the Authenticator interface to require a valid JSON Web Token (JWT) be passed with all requests.

func (*JWTAuthenticator) GetAccountForRequest

func (a *JWTAuthenticator) GetAccountForRequest(req *http.Request) (Account, error)

GetAccountForRequest returns a stub `Account` instance for requests that contain a valid `Authorization: Bearer {JWT_TOKEN}` HTTP header (or a custom header if defined in the `JWTAuthenticator` constructor URI).

func (*JWTAuthenticator) SigninHandler

func (a *JWTAuthenticator) SigninHandler() http.Handler

SigninHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*JWTAuthenticator) SignoutHandler

func (a *JWTAuthenticator) SignoutHandler() http.Handler

SignoutHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*JWTAuthenticator) SignupHandler

func (a *JWTAuthenticator) SignupHandler() http.Handler

SignupHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*JWTAuthenticator) WrapHandler

func (a *JWTAuthenticator) WrapHandler(next http.Handler) http.Handler

WrapHandler returns an `http.Handler` that wraps 'next' and responds with an HTTP "403 Forbidden" error if `GetAccountForRequest` fails for the request.

type JWTAuthenticatorClaims

type JWTAuthenticatorClaims struct {
	// AccountId is the unique ID associated with this account.
	AccountId string `json:"account_id"`
	// AccountName is the name associated with this account.
	AccountName string `json:"account_name"`
	jwt.RegisteredClaims
}

JWTAuthenticatorClaims are the custom claims for Authorization requests.

type NoneAuthenticator

type NoneAuthenticator struct {
	Authenticator
}

NoneAuthenticator implements the Authenticator interface that always returns a "not authorized" error.

func (*NoneAuthenticator) GetAccountForRequest

func (a *NoneAuthenticator) GetAccountForRequest(req *http.Request) (Account, error)

GetAccountForRequest always returns a `NotAuthorized` error.

func (*NoneAuthenticator) SigninHandler

func (a *NoneAuthenticator) SigninHandler() http.Handler

SigninHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*NoneAuthenticator) SignoutHandler

func (a *NoneAuthenticator) SignoutHandler() http.Handler

SignoutHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*NoneAuthenticator) SignupHandler

func (a *NoneAuthenticator) SignupHandler() http.Handler

SignupHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*NoneAuthenticator) WrapHandler

func (a *NoneAuthenticator) WrapHandler(h http.Handler) http.Handler

WrapHandler returns 'h' unchanged.

type NotAuthorized

type NotAuthorized struct{}

NotAuthorized defines a well-known error for signaling that the request is not authorized.

func (NotAuthorized) Error

func (e NotAuthorized) Error() string

Error returns a human-readable representation of the `NotAuthorized` error.

type NotLoggedIn

type NotLoggedIn struct{}

NotLoggedIn defines a well-known error for signaling that the account is not logged in.

func (NotLoggedIn) Error

func (e NotLoggedIn) Error() string

Error returns a human-readable representation of the `NotLoggedIn` error.

type NullAuthenticator

type NullAuthenticator struct {
	Authenticator
}

NullAuthenticator implements the Authenticator interface such that no authentication is performed.

func (*NullAuthenticator) GetAccountForRequest

func (a *NullAuthenticator) GetAccountForRequest(req *http.Request) (Account, error)

GetAccountForRequest returns a stub `Account` instance.

func (*NullAuthenticator) SigninHandler

func (a *NullAuthenticator) SigninHandler() http.Handler

SigninHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*NullAuthenticator) SignoutHandler

func (a *NullAuthenticator) SignoutHandler() http.Handler

SignoutHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*NullAuthenticator) SignupHandler

func (a *NullAuthenticator) SignupHandler() http.Handler

SignupHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*NullAuthenticator) WrapHandler

func (a *NullAuthenticator) WrapHandler(h http.Handler) http.Handler

WrapHandler returns 'h' unchanged.

type OIDCAccount

type OIDCAccount struct {
	// Subject is the "sub" claim.
	Subject string `json:"sub"`
	// EmailAddress is the "email" claim.
	EmailAddress string `json:"email,omitempty"`
	// ProfileName is the "name" claim.
	ProfileName string `json:"name,omitempty"`
	// Expires is the "exp" claim as a Unix timestamp.
	Expires int64 `json:"exp"`
}

OIDCAccount is the `Account` derived from the claims of an OpenID Connect ID token.

func (*OIDCAccount) Email

func (a *OIDCAccount) Email() string

Email returns the "email" claim.

func (*OIDCAccount) Id

func (a *OIDCAccount) Id() string

Id returns the "sub" claim.

func (*OIDCAccount) Name

func (a *OIDCAccount) Name() string

Name returns the "name" claim, falling back to "sub".

type OIDCAuthenticator

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

OIDCAuthenticator is an OpenID Connect relying party (authorization code flow with PKCE) that implements the `Authenticator` interface.

func (*OIDCAuthenticator) GetAccountForRequest

func (a *OIDCAuthenticator) GetAccountForRequest(req *http.Request) (Account, error)

GetAccountForRequest returns the `Account` for the session cookie in 'req' or a `NotLoggedIn` error.

func (*OIDCAuthenticator) SigninHandler

func (a *OIDCAuthenticator) SigninHandler() http.Handler

SigninHandler returns an `http.Handler` that starts the authorization code flow with PKCE.

func (*OIDCAuthenticator) SignoutHandler

func (a *OIDCAuthenticator) SignoutHandler() http.Handler

SignoutHandler returns an `http.Handler` that clears the local session. The provider's session is left intact. Only POST requests are accepted so that a cross-site link or image cannot force a signout. Sessions are stateless cookies, so a copy of the cookie remains valid until it expires.

func (*OIDCAuthenticator) SignupHandler

func (a *OIDCAuthenticator) SignupHandler() http.Handler

SignupHandler returns an `http.Handler` that redirects to the configured signup_uri (or returns a 404).

func (*OIDCAuthenticator) WrapHandler

func (a *OIDCAuthenticator) WrapHandler(next http.Handler) http.Handler

WrapHandler returns an `http.Handler` that serves the OIDC callback at the path of the configured redirect_uri and redirects unauthenticated requests to the provider; all other requests are passed to 'next'.

type SharedSecretAuthenticator

type SharedSecretAuthenticator struct {
	Authenticator
	// contains filtered or unexported fields
}

SharedSecretAuthenticator implements the Authenticator interface to require a simple shared secret be passed with all requests. This is not a sophisticated handler. There are no nonces or hashing of requests or anything like that. It is a bare-bones supplementary authentication handler for environments that already implement their own measures of access control.

func (*SharedSecretAuthenticator) GetAccountForRequest

func (a *SharedSecretAuthenticator) GetAccountForRequest(req *http.Request) (Account, error)

GetAccountForRequest returns a stub `Account` instance for requests that contain a valid `X-Shared-Secret` HTTP header.

func (*SharedSecretAuthenticator) SigninHandler

func (a *SharedSecretAuthenticator) SigninHandler() http.Handler

SigninHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*SharedSecretAuthenticator) SignoutHandler

func (a *SharedSecretAuthenticator) SignoutHandler() http.Handler

SignoutHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*SharedSecretAuthenticator) SignupHandler

func (a *SharedSecretAuthenticator) SignupHandler() http.Handler

SignupHandler returns an `http.Handler` instance that returns an HTTP "501 Not implemented" error.

func (*SharedSecretAuthenticator) WrapHandler

func (a *SharedSecretAuthenticator) WrapHandler(next http.Handler) http.Handler

WrapHandler returns an `http.Handler` that wraps 'next' and responds with an HTTP "403 Forbidden" error if `GetAccountForRequest` fails for the request.

Jump to

Keyboard shortcuts

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