basicauth

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: MIT Imports: 20 Imported by: 4 modules, 5 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

Basic Authentication

build status report card godocs

A Go HTTP middleware for basic authentication with a typed user. It works with the net/http package and with third-party routers that accept func(http.Handler) http.Handler.

In the context of an HTTP transaction, basic access authentication is a method for an HTTP user agent (e.g. a web browser) to provide a user name and password when making a request RFC 7617.

Looking for JWT? Navigate through kataras/jwt instead.

Installation

The only requirement is the Go Programming Language, version 1.27 or newer.

$ go get github.com/kataras/basicauth

Please star this open source project to attract more developers so that together we can improve it even more!

Examples

Getting Started

Import the package:

import "github.com/kataras/basicauth"

Initialize the middleware with a simple map of username:password:

auth := basicauth.Default(map[string]string{
	"admin":       "admin",
	"my_username": "my_password",
})

Wrap any http.Handler with the auth middleware, e.g. *http.ServeMux:

mux := http.NewServeMux()
// [...routes]

http.ListenAndServe(":8080", auth.Wrap(mux))

Or register the middleware to a single http.HandlerFunc route:

mux.HandleFunc("/", auth.HandlerFunc(routeHandlerFunc))

Third-party chains that want a func(http.Handler) http.Handler get one from auth.Middleware(). The package-level basicauth.Func and basicauth.HandlerFunc adapt that value further.

Access the authenticated User entry. Default stores a basicauth.SimpleUser, so that is what User returns, no type assertion needed:

routeHandlerFunc := func(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.User(r)
	// user.Username
	// user.Password
}

Handlers that live in another package and do not hold the auth value can use the package-level accessor with the user type as a type argument:

user, ok := basicauth.GetUser[basicauth.SimpleUser](r)
Your own user type

The middleware is generic over the user type. Whatever Allow returns is what the handlers get back:

type User struct {
	Username string   `json:"username"`
	Password string   `json:"password"`
	Roles    []string `json:"roles"`
}

auth := basicauth.New(basicauth.Options[User]{
	Realm:  basicauth.DefaultRealm,
	MaxAge: 10 * time.Minute,
	Allow:  basicauth.AllowUsers(users), // users is a []User
})

func index(w http.ResponseWriter, r *http.Request) {
	user, _ := auth.User(r) // user is a User.
}

AllowUsers reads the username and password from the basicauth.User interface when the type implements it, otherwise from the Username and Password fields (json tags count too). For anything else pass the basicauth.Credentials option and tell it where to look. All of this happens once, at startup; a request costs one map lookup and one password comparison.

For a database or any other backend, write the Allow function yourself. It returns your type directly:

auth := basicauth.New(basicauth.Options[*User]{
	Realm: basicauth.DefaultRealm,
	Allow: func(r *http.Request, username, password string) (*User, bool) {
		user, err := db.find(r.Context(), username, password)
		return user, err == nil
	},
})

Users from a YAML or JSON file, with bcrypt-hashed passwords:

auth := basicauth.Load("users.yml", basicauth.BCRYPT)             // users are basicauth.Map (map[string]any)
auth := basicauth.New(basicauth.Options[User]{
	Allow: basicauth.AllowUsersFile[User]("users.yml", basicauth.BCRYPT), // or decode straight into your type
})

The file holds either a list of users (- username: ... entries with any extra fields) or the short username: password form. Set the basicauth.ReadFile variable to read it from somewhere other than the disk, an embedded filesystem for example.

The *http.Request.BasicAuth() works too, but it only gives you the raw username and password, not your custom user.

Options

Allow is the only required field. The rest of basicauth.Options[U]:

Field What it does
Realm The realm of the WWW-Authenticate: Basic challenge. Default and Load use basicauth.DefaultRealm.
Proxy Challenge with 407 and Proxy-Authenticate, read the credentials from Proxy-Authorization.
HTTPSOnly Reject any request that did not arrive over TLS with a 505. HTTPS over HTTP/1.1 counts as TLS.
MaxAge How long a successful login stays valid. Counted from the first login, not refreshed by later requests. After that the client is challenged again.
MaxTries Answer 403 after this many failed logins. The counter is kept on the server per client address and username. A cookie mirrors it for browsers but is not trusted.
MaxTriesCookie Name of that cookie. Defaults to basicmaxtries.
ClientAddr Which address the counter is keyed by. Defaults to the host part of r.RemoteAddr. Behind a reverse proxy, return the real client address from the header your proxy sets, otherwise one client's typos lock the username out for everyone.
ErrorHandler Receives every failure as a typed error (ErrCredentialsMissing, ErrCredentialsInvalid, ErrCredentialsExpired, ErrCredentialsForbidden, ErrHTTPVersion). The default writes the matching status and, for the first three, the WWW-Authenticate challenge. A custom handler must set that header itself or browsers will not prompt.
ErrorLogger A *log.Logger that gets every failure before the handler runs. Messages name the user, never the password.
GC A ticker that drops expired entries from memory every GC.Every, cancellable through GC.Context. Without MaxAge every entry counts as expired.
OnLogoutClearContext Make User and GetUser report false on the request returned by Logout.
Logout and authorization time

auth.Logout(r) (or the package-level basicauth.Logout(r) from another package) forgets the stored login and strips the Authorization header from the request, so the client is challenged on its next request. It returns the request to use afterwards, which is a new one only with OnLogoutClearContext.

basicauth.AuthorizedAt(r) (or auth.AuthorizedAt(r)) returns when the current credentials were first accepted. It reports false without MaxAge, because the middleware keeps no per-login time when nothing expires.

Security

Passwords are compared in constant time, and an unknown username is compared against a decoy so the response takes the same time whether or not the user exists. With BCRYPT the decoy is a real bcrypt hash. Logged-in credentials are kept in memory as a SHA-256 digest of the username:password pair, never as cleartext. The MaxTries lockout is enforced on the server, so a client that drops the cookie is still counted, and the cookie itself is HttpOnly, SameSite=Lax and Secure over TLS. Error messages name the user but never contain the password or the raw header.

Basic authentication itself sends the password with every request, base64-encoded but not encrypted. Serve it over TLS. HTTPSOnly enforces that at the middleware.

For a more detailed technical documentation you can head over to our godocs.

License

This software is licensed under the MIT License.

Documentation

Index

Constants

View Source
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

View Source
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

func AuthorizedAt(r *http.Request) (time.Time, bool)

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

func GetUser[U any](r *http.Request) (U, bool)

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))

func Logout

func Logout(r *http.Request) *http.Request

Logout deletes the authenticated user entry from the backend. The client should login again on the next request. See BasicAuth.Logout and Options.OnLogoutClearContext for details.

Types

type AuthFunc

type AuthFunc[U any] func(r *http.Request, username, password string) (U, bool)

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

func New[U any](opts Options[U]) *BasicAuth[U]

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

func (b *BasicAuth[U]) AuthorizedAt(r *http.Request) (time.Time, bool)

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

func (b *BasicAuth[U]) Logout(r *http.Request) *http.Request

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.

func (*BasicAuth[U]) User added in v0.0.7

func (b *BasicAuth[U]) User(r *http.Request) (U, bool)

User returns the authenticated user of the request as stored by this middleware. It reports false when the request did not pass through this middleware or when the user was cleared by Logout with Options.OnLogoutClearContext enabled.

func (*BasicAuth[U]) Wrap added in v0.0.7

func (b *BasicAuth[U]) Wrap(next http.Handler) http.Handler

Wrap returns a handler that authenticates the request and calls "next" only when the client is allowed to continue.

Usage:

http.ListenAndServe(":8080", auth.Wrap(mux))

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

type ErrCredentialsForbidden struct {
	Username string
	Password string
	Tries    int
	Age      time.Duration
}

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

type GC struct {
	Context context.Context
	Every   time.Duration
}

GC holds the context and the tick duration to clear expired stored credentials. See the Options.GC field.

type Map

type Map = map[string]any

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

type Middleware = func(http.Handler) http.Handler

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

type SimpleUser struct {
	Username string
	Password string
}

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

type User interface {
	GetUsername() string
	GetPassword() string
}

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.

Directories

Path Synopsis
_examples
basic command
users_list command

Jump to

Keyboard shortcuts

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