Documentation
¶
Index ¶
- Constants
- Variables
- func AuthorizedAt(r *http.Request) (time.Time, bool)
- func BCRYPT[U any](opts *UserAuthOptions[U])
- func DefaultErrorHandler(w http.ResponseWriter, r *http.Request, err error)
- func Func(auth Middleware) func(http.HandlerFunc) http.HandlerFunc
- func GetUser[U any](r *http.Request) (U, bool)
- func HandlerFunc(auth Middleware, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc
- func Logout(r *http.Request) *http.Request
- type AuthFunc
- type BasicAuth
- func (b *BasicAuth[U]) AuthorizedAt(r *http.Request) (time.Time, bool)
- func (b *BasicAuth[U]) HandlerFunc(handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc
- func (b *BasicAuth[U]) Logout(r *http.Request) *http.Request
- func (b *BasicAuth[U]) Middleware() Middleware
- func (b *BasicAuth[U]) User(r *http.Request) (U, bool)
- func (b *BasicAuth[U]) Wrap(next http.Handler) http.Handler
- type ErrCredentialsExpired
- type ErrCredentialsForbidden
- type ErrCredentialsInvalid
- type ErrCredentialsMissing
- type ErrHTTPVersion
- type ErrorHandler
- type GC
- type Map
- type Middleware
- type Options
- type SimpleUser
- type User
- type UserAuthOption
- type UserAuthOptions
Constants ¶
const ( // DefaultRealm is the default realm directive value on Default and Load functions. DefaultRealm = "Authorization Required" // DefaultMaxTriesCookie is the default cookie name to store the // current amount of login failures when MaxTries > 0. DefaultMaxTriesCookie = "basicmaxtries" // DefaultCookieMaxAge is the default cookie max age on MaxTries, // when the Options.MaxAge is zero. DefaultCookieMaxAge = time.Hour )
Variables ¶
var ReadFile = os.ReadFile
ReadFile can be used to customize the way the AllowUsersFile function is loading the filename from. Example of usage: embedded users.yml file. Defaults to the `os.ReadFile` which reads the file from the physical disk.
Functions ¶
func AuthorizedAt ¶ added in v0.0.8
AuthorizedAt returns the time the request's credentials were first accepted by a BasicAuth middleware, as implied by its Options.MaxAge entry. It reports false when the request was not authenticated or when MaxAge is zero, as the middleware keeps no per-login time without an expiration.
Usage:
at, ok := basicauth.AuthorizedAt(r)
func BCRYPT ¶
func BCRYPT[U any](opts *UserAuthOptions[U])
BCRYPT it is a UserAuthOption, it compares a bcrypt hashed password with its user input. Reports true on success and false on failure.
Useful when the users passwords are encrypted using the Provos and Mazières's bcrypt adaptive hashing algorithm. See https://www.usenix.org/legacy/event/usenix99/provos/provos.pdf.
Usage:
Default(..., BCRYPT) OR Load(..., BCRYPT) OR Options.Allow = AllowUsers(..., BCRYPT) OR Options.Allow = AllowUsersFile[Map](..., BCRYPT)
func DefaultErrorHandler ¶
func DefaultErrorHandler(w http.ResponseWriter, r *http.Request, err error)
DefaultErrorHandler is the default error handler for the Options.ErrorHandler field. Custom handlers can inspect the error with a type switch as below or with errors.AsType, e.g. errors.AsType[ErrCredentialsInvalid](err).
func Func ¶
func Func(auth Middleware) func(http.HandlerFunc) http.HandlerFunc
Func converts a Middleware of func(http.Handler) http.Handler to a func(HandlerFunc) http.HandlerFunc. Maybe useful for some third-party handlers chaining.
Usage:
mux.HandleFunc("/", basicauth.Func(auth.Middleware())(index))
func GetUser ¶
GetUser returns the authenticated user stored in the request by a BasicAuth middleware, as the type U that its Options.Allow returned. It reports false when the request was not authenticated or when the stored user is not a U.
Prefer the BasicAuth.User method when the middleware instance is at hand, as it needs no explicit type argument. GetUser exists for handlers in other packages.
Usage:
user, ok := basicauth.GetUser[MyUser](r)
func HandlerFunc ¶
func HandlerFunc(auth Middleware, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc
HandlerFunc accepts a Middleware (http.Handler) http.Handler and a handler and returns a HandlerFunc. See the BasicAuth.HandlerFunc method for the shorter form.
Usage:
mux.HandleFunc("/", basicauth.HandlerFunc(auth.Middleware(), index))
Types ¶
type AuthFunc ¶
AuthFunc accepts the current request and the username and password user inputs and it should return the user value of type U and report whether the login succeeded or not. Look the Options.Allow field.
Default implementations are: AllowUsers, AllowUsersMap and AllowUsersFile functions.
func AllowUsers ¶
func AllowUsers[U any](users []U, opts ...UserAuthOption[U]) AuthFunc[U]
AllowUsers is an AuthFunc which authenticates user input based on a (static) user list. The credentials of each element are resolved once, when AllowUsers is called, so serving a request costs a map lookup and a password comparison. The element type U can be:
a type which completes the User interface, a struct (or pointer to struct) with Username and Password string fields, or with fields tagged `json:"username"` and `json:"password"`, embedded structs included, a Map (map[string]any) with "username" and "password" keys, any other type, when the Credentials option is given.
Elements without both a username and a password are skipped. The authenticated user returned to the handlers is the matching list element.
Usage:
New(Options[MyUser]{Allow: AllowUsers(users, [BCRYPT])})
func AllowUsersFile ¶
func AllowUsersFile[U any](jsonOrYamlFilename string, opts ...UserAuthOption[U]) AuthFunc[U]
AllowUsersFile is an AuthFunc which authenticates user input based on a (static) user list loaded from a JSON or YAML file on initialization. The file is decoded into a []U, so U can be any struct with the matching json/yaml tags, or Map to keep every field as is. The username and password are then resolved as documented on AllowUsers.
Example Code:
New(Options[Map]{Allow: AllowUsersFile[Map]("users.yml", BCRYPT)})
New(Options[Member]{Allow: AllowUsersFile[Member]("users.yml", BCRYPT)})
The users.yml file looks like the following:
- username: kataras password: kataras_pass age: 27 role: admin
- username: makis password: makis_password ...
The short form below is supported as well, when U is Map or SimpleUser:
kataras: kataras_pass makis: makis_password
It panics when the file cannot be read or decoded.
func AllowUsersMap ¶ added in v0.0.7
func AllowUsersMap(users map[string]string, opts ...UserAuthOption[SimpleUser]) AuthFunc[SimpleUser]
AllowUsersMap is an AuthFunc which authenticates user input based on a (static) username:password map. The map is copied, later changes to it are not seen. The authenticated user returned to the handlers is a SimpleUser holding the username and the password the client sent.
Usage:
New(Options[SimpleUser]{Allow: AllowUsersMap(map[string]string{"admin": "admin"}, [BCRYPT])})
type BasicAuth ¶
type BasicAuth[U any] struct { // contains filtered or unexported fields }
BasicAuth implements the basic access authentication. It is a method for an HTTP client (e.g. a web browser) to provide a user name and password when making a request. Basic authentication implementation is the simplest technique for enforcing access controls to web resources because it does not require cookies, session identifiers, or login pages; rather, HTTP Basic authentication uses standard fields in the HTTP header.
As the username and password are passed over the network as clear text the basic authentication scheme is not secure on plain HTTP communication. It is base64 encoded, but base64 is a reversible encoding. HTTPS/TLS should be used with basic authentication. Without these additional security enhancements, basic authentication should NOT be used to protect sensitive or valuable information.
The type parameter U is the authenticated user type, see Options. Wrap a handler with the Wrap or HandlerFunc methods and read the user back inside the handlers with the User method.
Read https://tools.ietf.org/html/rfc2617 and https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication for details.
func Default ¶
func Default(users map[string]string, userOpts ...UserAuthOption[SimpleUser]) *BasicAuth[SimpleUser]
Default returns a new basic authentication middleware based on a pre-defined username:password list. The authenticated user is a SimpleUser. For custom user types use New with AllowUsers or AllowUsersFile.
Usage:
auth := Default(map[string]string{
"admin": "admin",
"john": "p@ss",
})
func Load ¶
func Load(jsonOrYamlFilename string, userOpts ...UserAuthOption[Map]) *BasicAuth[Map]
Load same as Default but instead of a hard-coded user list it accepts a filename to load the users from. The authenticated user is a Map. For a typed user use New with AllowUsersFile[MyUser].
Usage:
auth := Load("users.yml")
func New ¶
New returns a new basic authentication middleware. Wrap an existing handler or the HTTP application's root router with its Wrap method.
Example Code:
auth := basicauth.New(basicauth.Options[MyUser]{
Realm: basicauth.DefaultRealm,
ErrorHandler: basicauth.DefaultErrorHandler,
MaxAge: 2 * time.Hour,
GC: basicauth.GC{
Every: 3 * time.Hour,
},
Allow: basicauth.AllowUsers(users),
})
mux := http.NewServeMux()
[...routes]
http.ListenAndServe(":8080", auth.Wrap(mux))
Access the user in the route handler with:
user, ok := auth.User(r) // user is a MyUser.
Look the BasicAuth type docs for more information.
func (*BasicAuth[U]) AuthorizedAt ¶ added in v0.0.8
AuthorizedAt returns the time the request's credentials were first accepted. It reports false when Options.MaxAge is zero, as the middleware keeps no per-login time without an expiration, and when the request did not pass through this middleware. See the package-level AuthorizedAt function for handlers without the instance.
func (*BasicAuth[U]) HandlerFunc ¶ added in v0.0.7
func (b *BasicAuth[U]) HandlerFunc(handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc
HandlerFunc wraps a single route handler function.
Usage:
mux.HandleFunc("/", auth.HandlerFunc(index))
func (*BasicAuth[U]) Logout ¶ added in v0.0.7
Logout deletes the authenticated user entry from the backend. The client should login again on the next request. It returns the request to use from now on, which differs from the given one only when Options.OnLogoutClearContext is enabled.
func (*BasicAuth[U]) Middleware ¶ added in v0.0.7
func (b *BasicAuth[U]) Middleware() Middleware
Middleware returns the Wrap method as a Middleware value, useful for third-party handler chains that accept func(http.Handler) http.Handler.
type ErrCredentialsExpired ¶
type ErrCredentialsExpired struct {
Username string
Password string
AuthenticateHeader string
AuthenticateHeaderValue string
Code int
}
ErrCredentialsExpired is fired when the username:password combination is valid but the memory stored user has been expired.
func (ErrCredentialsExpired) Error ¶
func (e ErrCredentialsExpired) Error() string
type ErrCredentialsForbidden ¶
ErrCredentialsForbidden is fired when Options.MaxTries have been consumed by the user and the client is forbidden to retry at least for "Age" time.
func (ErrCredentialsForbidden) Error ¶
func (e ErrCredentialsForbidden) Error() string
type ErrCredentialsInvalid ¶
type ErrCredentialsInvalid struct {
Username string
Password string
CurrentTries int
AuthenticateHeader string
AuthenticateHeaderValue string
Code int
}
ErrCredentialsInvalid is fired when the user input does not match with an existing user.
func (ErrCredentialsInvalid) Error ¶
func (e ErrCredentialsInvalid) Error() string
type ErrCredentialsMissing ¶
type ErrCredentialsMissing struct {
Header string
AuthenticateHeader string
AuthenticateHeaderValue string
Code int
}
ErrCredentialsMissing is fired when the authorization header is empty or malformed.
func (ErrCredentialsMissing) Error ¶
func (e ErrCredentialsMissing) Error() string
type ErrHTTPVersion ¶
type ErrHTTPVersion struct{}
ErrHTTPVersion is fired when Options.HTTPSOnly was enabled and the current request is a plain http one.
func (ErrHTTPVersion) Error ¶
func (e ErrHTTPVersion) Error() string
type ErrorHandler ¶
type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)
ErrorHandler should handle the given request credentials failure. See Options.ErrorHandler and DefaultErrorHandler for details.
type GC ¶
GC holds the context and the tick duration to clear expired stored credentials. See the Options.GC field.
type Map ¶
Map is just a type alias of the map[string]any. It is the user type of users loaded from a file through Load and AllowUsersFile[Map].
type Middleware ¶
Middleware is just a type alias of func(http.Handler) http.Handler
type Options ¶
type Options[U any] struct { // Realm directive, read http://tools.ietf.org/html/rfc2617#section-1.2 for details. // E.g. "Authorization Required". Realm string // In the case of proxies, the challenging status code is 407 (Proxy Authentication Required), // the Proxy-Authenticate response header contains at least one challenge applicable to the proxy, // and the Proxy-Authorization request header is used for providing the credentials to the proxy server. // // Proxy should be used to gain access to a resource behind a proxy server. // It authenticates the request to the proxy server, which then forwards it. Proxy bool // If set to true then any request that is not served over TLS // is immediately dropped with a 505 status code (StatusHTTPVersionNotSupported) response. // A request counts as TLS when the connection state is present (r.TLS) // or when the URL scheme is https. The HTTP version does not matter, // HTTPS over HTTP/1.1 is accepted. // // Defaults to false. HTTPSOnly bool // Allow is the only one required field for the Options type. // Can be customized to validate a username and password combination // and return a user object, e.g. fetch from database. // // There are three builtin implementations, AllowUsers, AllowUsersMap and AllowUsersFile. // All of them decode a static list of users and compare it with the user input (see the BCRYPT option too). // Usage: // - Allow: AllowUsers([]MyUser{...}, [BCRYPT]) // - Allow: AllowUsersMap(map[string]string{"username": "password"}, [BCRYPT]) // - Allow: AllowUsersFile[Map]("users.yml", [BCRYPT]) // Look the user.go source file for details. Allow AuthFunc[U] // MaxAge sets expiration duration for the in-memory credentials map. // The expiration is counted from the first successful login and it is not // refreshed by later requests: after MaxAge the client is challenged again // (ErrCredentialsExpired) and the next successful login starts a new period. // An expired entry is removed when its user visits a page again, // in order to remove old entries automatically please take a look at the `GC` option too. // // Usage: // MaxAge: 30 * time.Minute MaxAge time.Duration // If greater than zero then the server will send 403 forbidden status code after // MaxTries amount of sign in failures. // The counter is kept on the server side per client address and username // (see ClientAddr), and it is mirrored to a client cookie (see MaxTriesCookie) // which is not authoritative: a client that does not send the cookie back is still counted. // By default the server will re-ask for credentials on invalid credentials, each time. MaxTries int // MaxTriesCookie is the cookie name the middleware uses to // store the failures amount on the client side. // The lifetime of the cookie is the same as the configured MaxAge or one hour, // therefore a forbidden client can request for authentication again after expiration. // // You can always set custom logic on the Allow field as you have access to the current request instance. // // Defaults to "basicmaxtries". // The MaxTries should be set to greater than zero. MaxTriesCookie string // ClientAddr returns the address the MaxTries counter is keyed by, together with the username. // It defaults to the host part of the request's RemoteAddr. // Behind a reverse proxy every request carries the proxy's address, // so one client's failures would lock the username out for everyone; // set it to read the real client address from the header your proxy sets, e.g. // // ClientAddr: func(r *http.Request) string { return r.Header.Get("X-Forwarded-For") } // // Only used when MaxTries > 0. ClientAddr func(r *http.Request) string // ErrorHandler handles the given request credentials failure. // E.g when the client tried to access a protected resource // with empty or invalid or expired credentials or // when Allow returned false and MaxTries consumed. // // Defaults to the DefaultErrorHandler, do not modify if you don't need to. ErrorHandler ErrorHandler // ErrorLogger if not nil then it logs any credentials failure errors // that are going to be sent to the client. Set it on debug development state. // The error messages name the user but never contain the password. // Usage: // ErrorLogger = log.New(os.Stderr, "", log.LstdFlags) // // Defaults to nil. ErrorLogger *log.Logger // GC automatically clears old entries every x duration. // Note that, by old entries we mean expired credentials therefore // the `MaxAge` option should be already set, // if it's not then all entries will be removed on "every" duration. // The standard context can be used for the internal ticker cancelation, it can be nil. // // Usage: // GC: basicauth.GC{Every: 2 * time.Hour} GC GC // OnLogoutClearContext will clear the context values stored by // the middleware when Logout is called. // This means that the User and GetUser will report false after a Logout call was made. // // Defaults to false. OnLogoutClearContext bool }
Options holds the necessary information that the BasicAuth instance needs to perform. The only required value is the Allow field. The type parameter U is the type of the authenticated user that Allow returns and that BasicAuth.User (or GetUser) gives back to the handlers.
Usage:
opts := Options[MyUser]{ ... }
auth := New(opts)
type SimpleUser ¶
SimpleUser implements the User interface. It is the user type of the Default function and the AllowUsersMap AuthFunc.
func (SimpleUser) GetPassword ¶
func (u SimpleUser) GetPassword() string
GetPassword returns the Password field.
func (SimpleUser) GetUsername ¶
func (u SimpleUser) GetUsername() string
GetUsername returns the Username field.
type User ¶
User can be implemented by custom struct values to provide the username and the password as basic authentication credentials for a user list.
Look AllowUsers package-level function and the Options.Allow field.
type UserAuthOption ¶
type UserAuthOption[U any] func(*UserAuthOptions[U])
UserAuthOption is the option function type for the Default and Load (and AllowUsers, AllowUsersMap, AllowUsersFile) functions.
See BCRYPT and Credentials for implementations.
func Credentials ¶ added in v0.0.7
func Credentials[U any](fn func(user U) (username, password string)) UserAuthOption[U]
Credentials is a UserAuthOption which tells AllowUsers how to read the username and the stored password out of a user list element, instead of relying on the User interface or on the struct field names.
Usage:
AllowUsers(members, Credentials(func(m Member) (string, string) {
return m.Email, m.Hash
}), BCRYPT)
type UserAuthOptions ¶
type UserAuthOptions[U any] struct { // ComparePassword compares the stored password of a user with the user input. // Defaults to a constant-time equality check, can be modified for encrypted passwords, // see the BCRYPT optional function. ComparePassword func(stored, userPassword string) bool // Credentials returns the username and the stored password of a user list element. // When nil, AllowUsers reads them from the User interface methods // or from the Username and Password struct fields (or their json tags). // See the Credentials optional function. Credentials func(user U) (username, password string) // contains filtered or unexported fields }
UserAuthOptions holds optional user authentication options that can be given to the builtin Default and Load (and AllowUsers, AllowUsersMap, AllowUsersFile) functions.