middlewares

package
v4.37.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2022 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// UserValueKeyBaseURL is the User Value key where we store the Base URL.
	UserValueKeyBaseURL = []byte("base_url")
)

Functions

func AssetOverride added in v4.35.2

func AssetOverride(root string, strip int, next fasthttp.RequestHandler) fasthttp.RequestHandler

AssetOverride allows overriding and serving of specific embedded assets from disk.

func LogRequest added in v4.35.2

LogRequest provides trace logging for all requests.

func NewRequestLogger

func NewRequestLogger(ctx *AutheliaCtx) *logrus.Entry

NewRequestLogger create a new request logger for the given request.

func SecurityHeaders added in v4.35.2

func SecurityHeaders(next fasthttp.RequestHandler) fasthttp.RequestHandler

SecurityHeaders middleware adds several modern recommended security headers with safe values.

func SecurityHeadersCSPNone added in v4.35.2

func SecurityHeadersCSPNone(next fasthttp.RequestHandler) fasthttp.RequestHandler

SecurityHeadersCSPNone middleware adds the Content-Security-Policy header with the value "default-src 'none';".

func SecurityHeadersNoStore added in v4.35.2

func SecurityHeadersNoStore(next fasthttp.RequestHandler) fasthttp.RequestHandler

SecurityHeadersNoStore middleware adds the Pragma no-cache and Cache-Control no-store headers.

func SetContentTypeApplicationJSON added in v4.36.3

func SetContentTypeApplicationJSON(ctx *fasthttp.RequestCtx)

SetContentTypeApplicationJSON sets the Content-Type header to `application/json; charset=utf8`.

func SetContentTypeTextPlain added in v4.36.3

func SetContentTypeTextPlain(ctx *fasthttp.RequestCtx)

SetContentTypeTextPlain sets the Content-Type header to `text/plain; charset=utf8`.

func Wrap added in v4.36.0

func Wrap(middleware Basic, next fasthttp.RequestHandler) (handler fasthttp.RequestHandler)

Wrap a handler with another middleware if it isn't nil.

Types

type AutheliaCtx

type AutheliaCtx struct {
	*fasthttp.RequestCtx

	Logger        *logrus.Entry
	Providers     Providers
	Configuration schema.Configuration

	Clock utils.Clock
}

AutheliaCtx contains all server variables related to Authelia.

func NewAutheliaCtx

func NewAutheliaCtx(requestCTX *fasthttp.RequestCtx, configuration schema.Configuration, providers Providers) (ctx *AutheliaCtx)

NewAutheliaCtx instantiate an AutheliaCtx out of a RequestCtx.

func (*AutheliaCtx) AcceptsMIME

func (ctx *AutheliaCtx) AcceptsMIME(mime string) (acceptsMime bool)

AcceptsMIME takes a mime type and returns true if the request accepts that type or the wildcard type.

func (*AutheliaCtx) AvailableSecondFactorMethods added in v4.34.6

func (ctx *AutheliaCtx) AvailableSecondFactorMethods() (methods []string)

AvailableSecondFactorMethods returns the available 2FA methods.

func (*AutheliaCtx) BasePath

func (ctx *AutheliaCtx) BasePath() (base string)

BasePath returns the base_url as per the path visited by the client.

func (*AutheliaCtx) Error

func (ctx *AutheliaCtx) Error(err error, message string)

Error reply with an error and display the stack trace in the logs.

func (*AutheliaCtx) ExternalRootURL

func (ctx *AutheliaCtx) ExternalRootURL() (string, error)

ExternalRootURL gets the X-Forwarded-Proto, X-Forwarded-Host headers and the BasePath and forms them into a URL.

func (*AutheliaCtx) GetOriginalURL

func (ctx *AutheliaCtx) GetOriginalURL() (*url.URL, error)

GetOriginalURL extract the URL from the request headers (X-Original-URL or X-Forwarded-* headers).

func (*AutheliaCtx) GetSession

func (ctx *AutheliaCtx) GetSession() session.UserSession

GetSession return the user session. Any update will be saved in cache.

func (*AutheliaCtx) IsXHR

func (ctx *AutheliaCtx) IsXHR() (xhr bool)

IsXHR returns true if the request is a XMLHttpRequest.

func (*AutheliaCtx) IssuerURL added in v4.37.0

func (ctx *AutheliaCtx) IssuerURL() (issuerURL *url.URL, err error)

IssuerURL returns the expected Issuer.

func (*AutheliaCtx) ParseBody

func (ctx *AutheliaCtx) ParseBody(value any) error

ParseBody parse the request body into the type of value.

func (*AutheliaCtx) QueryArgRedirect added in v4.37.0

func (ctx *AutheliaCtx) QueryArgRedirect() (val []byte)

QueryArgRedirect return the content of the rd query argument.

func (*AutheliaCtx) RecordAuthentication added in v4.36.0

func (ctx *AutheliaCtx) RecordAuthentication(success, regulated bool, method string)

RecordAuthentication records authentication metrics.

func (*AutheliaCtx) RemoteIP

func (ctx *AutheliaCtx) RemoteIP() net.IP

RemoteIP return the remote IP taking X-Forwarded-For header into account if provided.

func (*AutheliaCtx) ReplyBadRequest

func (ctx *AutheliaCtx) ReplyBadRequest()

ReplyBadRequest response sent when bad request has been sent.

func (*AutheliaCtx) ReplyError

func (ctx *AutheliaCtx) ReplyError(err error, message string)

ReplyError reply with an error but does not display any stack trace in the logs.

func (*AutheliaCtx) ReplyForbidden

func (ctx *AutheliaCtx) ReplyForbidden()

ReplyForbidden response sent when access is forbidden to user.

func (*AutheliaCtx) ReplyJSON added in v4.36.3

func (ctx *AutheliaCtx) ReplyJSON(data any, statusCode int) (err error)

ReplyJSON writes a JSON response.

func (*AutheliaCtx) ReplyOK

func (ctx *AutheliaCtx) ReplyOK()

ReplyOK is a helper method to reply ok.

func (*AutheliaCtx) ReplyStatusCode added in v4.36.3

func (ctx *AutheliaCtx) ReplyStatusCode(statusCode int)

ReplyStatusCode resets a response and replies with the given status code and relevant message.

func (*AutheliaCtx) ReplyUnauthorized

func (ctx *AutheliaCtx) ReplyUnauthorized()

ReplyUnauthorized response sent when user is unauthorized.

func (*AutheliaCtx) SaveSession

func (ctx *AutheliaCtx) SaveSession(userSession session.UserSession) error

SaveSession save the content of the session.

func (*AutheliaCtx) SetJSONBody

func (ctx *AutheliaCtx) SetJSONBody(value any) error

SetJSONBody Set json body.

func (*AutheliaCtx) SetJSONError added in v4.33.0

func (ctx *AutheliaCtx) SetJSONError(message string)

SetJSONError sets the body of the response to an JSON error KO message.

func (*AutheliaCtx) SpecialRedirect

func (ctx *AutheliaCtx) SpecialRedirect(uri string, statusCode int)

SpecialRedirect performs a redirect similar to fasthttp.RequestCtx except it allows statusCode 401 and includes body content in the form of a link to the location.

func (*AutheliaCtx) XAutheliaURL added in v4.37.0

func (ctx *AutheliaCtx) XAutheliaURL() (autheliaURL []byte)

XAutheliaURL return the content of the X-Authelia-URL header.

func (*AutheliaCtx) XForwardedHost

func (ctx *AutheliaCtx) XForwardedHost() (host []byte)

XForwardedHost return the content of the X-Forwarded-Host header.

func (*AutheliaCtx) XForwardedMethod

func (ctx *AutheliaCtx) XForwardedMethod() (method []byte)

XForwardedMethod return the content of the X-Forwarded-Method header.

func (*AutheliaCtx) XForwardedProto

func (ctx *AutheliaCtx) XForwardedProto() (proto []byte)

XForwardedProto return the content of the X-Forwarded-Proto header.

func (*AutheliaCtx) XForwardedURI

func (ctx *AutheliaCtx) XForwardedURI() (uri []byte)

XForwardedURI return the content of the X-Forwarded-URI header.

func (*AutheliaCtx) XOriginalURL

func (ctx *AutheliaCtx) XOriginalURL() []byte

XOriginalURL return the content of the X-Original-URL header.

type AutheliaHandlerFunc

type AutheliaHandlerFunc func(ctx *AutheliaCtx, rw http.ResponseWriter, r *http.Request)

AutheliaHandlerFunc is used with the NewHTTPToAutheliaHandlerAdaptor to encapsulate a func.

type AutheliaMiddleware

type AutheliaMiddleware = func(next RequestHandler) RequestHandler

AutheliaMiddleware represent an Authelia middleware.

type Basic added in v4.36.0

type Basic func(next fasthttp.RequestHandler) (handler fasthttp.RequestHandler)

Basic represents a middleware applied to a fasthttp.RequestHandler.

func NewMetricsRequest added in v4.36.0

func NewMetricsRequest(metrics metrics.Recorder) (middleware Basic)

NewMetricsRequest returns a middleware if provided with a metrics.Recorder, otherwise it returns nil.

func NewMetricsVerifyRequest added in v4.36.0

func NewMetricsVerifyRequest(metrics metrics.Recorder) (middleware Basic)

NewMetricsVerifyRequest returns a middleware if provided with a metrics.Recorder, otherwise it returns nil.

type Bridge added in v4.36.0

type Bridge = func(RequestHandler) fasthttp.RequestHandler

Bridge represents the func signature that returns a fasthttp.RequestHandler given a RequestHandler allowing it to bridge between the two handlers.

type BridgeBuilder added in v4.36.0

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

BridgeBuilder is used to build a Bridge.

func NewBridgeBuilder added in v4.36.0

func NewBridgeBuilder(config schema.Configuration, providers Providers) *BridgeBuilder

NewBridgeBuilder creates a new BridgeBuilder.

func (*BridgeBuilder) Build added in v4.36.0

func (b *BridgeBuilder) Build() Bridge

Build and return the Bridge configured by this BridgeBuilder.

func (*BridgeBuilder) WithConfig added in v4.36.0

func (b *BridgeBuilder) WithConfig(config schema.Configuration) *BridgeBuilder

WithConfig sets the schema.Configuration used with this BridgeBuilder.

func (*BridgeBuilder) WithPostMiddlewares added in v4.36.0

func (b *BridgeBuilder) WithPostMiddlewares(middlewares ...AutheliaMiddleware) *BridgeBuilder

WithPostMiddlewares sets the AutheliaMiddleware's used with this BridgeBuilder which are applied after the actual Bridge.

func (*BridgeBuilder) WithPreMiddlewares added in v4.36.0

func (b *BridgeBuilder) WithPreMiddlewares(middlewares ...Middleware) *BridgeBuilder

WithPreMiddlewares sets the Middleware's used with this BridgeBuilder which are applied before the actual Bridge.

func (*BridgeBuilder) WithProviders added in v4.36.0

func (b *BridgeBuilder) WithProviders(providers Providers) *BridgeBuilder

WithProviders sets the Providers used with this BridgeBuilder.

type CORSPolicy added in v4.35.0

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

CORSPolicy is a middleware that handles adding CORS headers.

func (CORSPolicy) HandleOPTIONS added in v4.35.0

func (p CORSPolicy) HandleOPTIONS(ctx *fasthttp.RequestCtx)

HandleOPTIONS is an OPTIONS handler that just adds CORS headers, the Allow header, and sets the status code to 204 without a body. This handler should generally not be used without using WithAllowedMethods.

func (CORSPolicy) HandleOnlyOPTIONS added in v4.35.0

func (p CORSPolicy) HandleOnlyOPTIONS(ctx *fasthttp.RequestCtx)

HandleOnlyOPTIONS is an OPTIONS handler that just handles the Allow header, and sets the status code to 204 without a body. This handler should generally not be used without using WithAllowedMethods.

func (CORSPolicy) Middleware added in v4.35.0

func (p CORSPolicy) Middleware(next fasthttp.RequestHandler) (handler fasthttp.RequestHandler)

Middleware provides a middleware that adds the appropriate CORS headers for this CORSPolicyBuilder.

type CORSPolicyBuilder added in v4.35.0

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

CORSPolicyBuilder is a special middleware which provides CORS headers via handlers and middleware methods which can be configured. It aims to simplify CORS configurations.

func NewCORSPolicyBuilder added in v4.35.0

func NewCORSPolicyBuilder() (policy *CORSPolicyBuilder)

NewCORSPolicyBuilder returns a new CORSPolicyBuilder which is used to build a CORSPolicy which adds the Vary header with a value reflecting that the Origin header will Vary this response, then if the Origin header has a https scheme it makes the following additional adjustments: copies the Origin header to the Access-Control-Allow-Origin header effectively allowing all origins, sets the Access-Control-Allow-Credentials header to false which disallows CORS requests from sending cookies etc, sets the Access-Control-Allow-Headers header to the value specified by Access-Control-Request-Headers in the request excluding the Cookie/Authorization/Proxy-Authorization and special * values, sets Access-Control-Allow-Methods to the value specified by the Access-Control-Request-Method header, sets the Access-Control-Max-Age header to 100.

These behaviours can be overridden by the With methods on the returned policy.

func (*CORSPolicyBuilder) Build added in v4.35.0

func (b *CORSPolicyBuilder) Build() (policy *CORSPolicy)

Build reads the CORSPolicyBuilder configuration and generates a CORSPolicy.

func (*CORSPolicyBuilder) WithAllowCredentials added in v4.35.0

func (b *CORSPolicyBuilder) WithAllowCredentials(allow bool) (policy *CORSPolicyBuilder)

WithAllowCredentials takes bool and alters the default Access-Control-Allow-Credentials header.

func (*CORSPolicyBuilder) WithAllowedHeaders added in v4.35.0

func (b *CORSPolicyBuilder) WithAllowedHeaders(headers ...string) (policy *CORSPolicyBuilder)

WithAllowedHeaders takes a list of header strings and alters the default Access-Control-Allow-Headers header.

func (*CORSPolicyBuilder) WithAllowedMethods added in v4.35.0

func (b *CORSPolicyBuilder) WithAllowedMethods(methods ...string) (policy *CORSPolicyBuilder)

WithAllowedMethods takes a list or HTTP methods and adjusts the Access-Control-Allow-Methods header to respond with that value.

func (*CORSPolicyBuilder) WithAllowedOrigins added in v4.35.0

func (b *CORSPolicyBuilder) WithAllowedOrigins(origins ...string) (policy *CORSPolicyBuilder)

WithAllowedOrigins takes a list of origin strings and only applies the CORS policy if the origin matches one of these.

func (*CORSPolicyBuilder) WithEnabled added in v4.35.0

func (b *CORSPolicyBuilder) WithEnabled(enabled bool) (policy *CORSPolicyBuilder)

WithEnabled changes the enabled state of the middleware. If the middleware is initialized with NewCORSPolicyBuilder this value will be true but this function can override the value. Setting it to false prevents the middleware from adding any CORS headers. The only effect this middleware has after disabling this is the HandleOPTIONS and HandleOnlyOPTIONS handlers still function to return a HTTP 204 No Content, with the Allow header communicating the available HTTP method verbs. The main benefit of this option is that you don't have to implement complex logic to add/remove the middleware, you can just add it with the Middleware method, and adjust it using the WithEnabled method.

func (*CORSPolicyBuilder) WithMaxAge added in v4.35.0

func (b *CORSPolicyBuilder) WithMaxAge(age int) (policy *CORSPolicyBuilder)

WithMaxAge takes an integer and alters the default Access-Control-Max-Age header.

func (*CORSPolicyBuilder) WithVary added in v4.35.0

func (b *CORSPolicyBuilder) WithVary(headers ...string) (policy *CORSPolicyBuilder)

WithVary takes a list of header strings and alters the default Vary header.

func (*CORSPolicyBuilder) WithVaryOnly added in v4.35.0

func (b *CORSPolicyBuilder) WithVaryOnly(varyOnly bool) (policy *CORSPolicyBuilder)

WithVaryOnly just adds the Vary header.

type ErrorResponse

type ErrorResponse struct {
	Status  string `json:"status"`
	Message string `json:"message"`
}

ErrorResponse model of an error response.

type IdentityVerificationFinishArgs

type IdentityVerificationFinishArgs struct {
	// The action claim that should be in the token to consider the action legitimate.
	ActionClaim string

	// The function for checking the user in the token is valid for the current action.
	IsTokenUserValidFunc func(ctx *AutheliaCtx, username string) bool
}

IdentityVerificationFinishArgs represent the arguments used to customize the finishing phase of the identity verification process.

type IdentityVerificationFinishBody

type IdentityVerificationFinishBody struct {
	Token string `json:"token"`
}

IdentityVerificationFinishBody type of the body received by the finish endpoint.

type IdentityVerificationStartArgs

type IdentityVerificationStartArgs struct {
	// Email template needs a subject, a title and the content of the button.
	MailTitle         string
	MailButtonContent string

	// The target endpoint where to redirect the user when verification process
	// is completed successfully.
	TargetEndpoint string

	// The action claim that will be stored in the JWT token.
	ActionClaim string

	// The function retrieving the identity to who the email will be sent.
	IdentityRetrieverFunc func(ctx *AutheliaCtx) (*session.Identity, error)

	// The function for checking the user in the token is valid for the current action.
	IsTokenUserValidFunc func(ctx *AutheliaCtx, username string) bool
}

IdentityVerificationStartArgs represent the arguments used to customize the starting phase of the identity verification process.

type Middleware

type Middleware = func(next fasthttp.RequestHandler) (handler fasthttp.RequestHandler)

Middleware represents a fasthttp middleware.

func StripPath added in v4.35.2

func StripPath(path string) (middleware Middleware)

StripPath strips the first level of a path.

type OKResponse

type OKResponse struct {
	Status string `json:"status"`
	Data   any    `json:"data,omitempty"`
}

OKResponse model of a status OK response.

type PasswordPolicyProvider added in v4.35.0

type PasswordPolicyProvider interface {
	Check(password string) (err error)
}

PasswordPolicyProvider represents an implementation of a password policy provider.

func NewPasswordPolicyProvider added in v4.35.0

func NewPasswordPolicyProvider(config schema.PasswordPolicyConfiguration) (provider PasswordPolicyProvider)

NewPasswordPolicyProvider returns a new password policy provider.

type Providers

type Providers struct {
	Authorizer      *authorization.Authorizer
	SessionProvider *session.Provider
	Regulator       *regulation.Regulator
	OpenIDConnect   *oidc.OpenIDConnectProvider
	Metrics         metrics.Provider
	NTP             *ntp.Provider
	UserProvider    authentication.UserProvider
	StorageProvider storage.Provider
	Notifier        notification.Notifier
	Templates       *templates.Provider
	TOTP            totp.Provider
	PasswordPolicy  PasswordPolicyProvider
}

Providers contain all provider provided to Authelia.

type RequestHandler

type RequestHandler = func(*AutheliaCtx)

RequestHandler represents an Authelia request handler.

func IdentityVerificationFinish

func IdentityVerificationFinish(args IdentityVerificationFinishArgs, next func(ctx *AutheliaCtx, username string)) RequestHandler

IdentityVerificationFinish the middleware for finishing the identity validation process.

func IdentityVerificationStart

func IdentityVerificationStart(args IdentityVerificationStartArgs, delayFunc TimingAttackDelayFunc) RequestHandler

IdentityVerificationStart the handler for initiating the identity validation process.

func NewHTTPToAutheliaHandlerAdaptor

func NewHTTPToAutheliaHandlerAdaptor(h AutheliaHandlerFunc) RequestHandler

NewHTTPToAutheliaHandlerAdaptor creates a new adaptor given the AutheliaHandlerFunc.

func Require1FA added in v4.35.0

func Require1FA(next RequestHandler) RequestHandler

Require1FA check if user has enough permissions to execute the next handler.

type StandardPasswordPolicyProvider added in v4.35.0

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

StandardPasswordPolicyProvider handles standard password policy checking.

func (StandardPasswordPolicyProvider) Check added in v4.35.0

func (p StandardPasswordPolicyProvider) Check(password string) (err error)

Check checks the password against the policy.

type TimingAttackDelayFunc added in v4.33.2

type TimingAttackDelayFunc func(ctx *AutheliaCtx, requestTime time.Time, successful *bool)

TimingAttackDelayFunc describes a function for preventing timing attacks via a delay.

func TimingAttackDelay added in v4.33.2

func TimingAttackDelay(history int, minDelayMs float64, maxRandomMs int64, initialDelay time.Duration, record bool) TimingAttackDelayFunc

TimingAttackDelay creates a new standard timing delay func.

type ZXCVBNPasswordPolicyProvider added in v4.35.0

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

ZXCVBNPasswordPolicyProvider handles zxcvbn password policy checking.

func (ZXCVBNPasswordPolicyProvider) Check added in v4.35.0

func (p ZXCVBNPasswordPolicyProvider) Check(password string) (err error)

Check checks the password against the policy.

Jump to

Keyboard shortcuts

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