Documentation ¶
Index ¶
- Constants
- Variables
- func BCRYPT(opts *UserAuthOptions)
- func Default(users interface{}, userOpts ...UserAuthOption) context.Handler
- func DefaultErrorHandler(ctx *context.Context, err error)
- func Load(jsonOrYamlFilename string, userOpts ...UserAuthOption) context.Handler
- func New(opts Options) context.Handler
- type AuthFunc
- type BasicAuth
- type ErrCredentialsExpired
- type ErrCredentialsForbidden
- type ErrCredentialsInvalid
- type ErrCredentialsMissing
- type ErrHTTPVersion
- type ErrorHandler
- type GC
- type Options
- 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 = ioutil.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 `ioutil.ReadFile` which reads the file from the physical disk.
Functions ¶
func BCRYPT ¶ added in v12.2.0
func BCRYPT(opts *UserAuthOptions)
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(..., BCRYPT)
func Default ¶
func Default(users interface{}, userOpts ...UserAuthOption) context.Handler
Default returns a new basic authentication middleware based on pre-defined user list. A user can hold any custom fields but the username and password are required as they are compared against the user input when access to protected resource is requested. A user list can defined with one of the following values:
map[string]string form of: {username:password, ...} map[string]interface{} form of: {"username": {"password": "...", "other_field": ...}, ...} []T which T completes the User interface, where T is a struct value []T which T contains at least Username and Password fields.
Usage:
auth := Default(map[string]string{ "admin": "admin", "john": "p@ss", })
func DefaultErrorHandler ¶ added in v12.2.0
DefaultErrorHandler is the default error handler for the Options.ErrorHandler field.
func Load ¶ added in v12.2.0
func Load(jsonOrYamlFilename string, userOpts ...UserAuthOption) context.Handler
Load same as Default but instead of a hard-coded user list it accepts a filename to load the users from.
Usage:
auth := Load("users.yml")
func New ¶
New returns a new basic authentication middleware. The result should be used to wrap an existing handler or the HTTP application's root router.
Example Code:
opts := basicauth.Options{ Realm: basicauth.DefaultRealm, ErrorHandler: basicauth.DefaultErrorHandler, MaxAge: 2 * time.Hour, GC: basicauth.GC{ Every: 3 * time.Hour, }, Allow: basicauth.AllowUsers(users), } auth := basicauth.New(opts) app.Use(auth)
Access the user in the route handler with: ctx.User().GetRaw().(*myCustomType).
Look the BasicAuth type docs for more information.
Types ¶
type AuthFunc ¶ added in v12.2.0
AuthFunc accepts the current request and the username and password user inputs and it should optionally return a user value and report whether the login succeed or not. Look the Options.Allow field.
Default implementations are: AllowUsers and AllowUsersFile functions.
func AllowUsers ¶ added in v12.2.0
func AllowUsers(users interface{}, opts ...UserAuthOption) AuthFunc
AllowUsers is an AuthFunc which authenticates user input based on a (static) user list. The "users" input parameter can be one of the following forms:
map[string]string e.g. {username: password, username: password...}. []map[string]interface{} e.g. []{"username": "...", "password": "...", "other_field": ...}, ...}. []T which T completes the User interface. []T which T contains at least Username and Password fields.
Usage: New(Options{Allow: AllowUsers(..., BCRYPT)})
func AllowUsersFile ¶ added in v12.2.0
func AllowUsersFile(jsonOrYamlFilename string, opts ...UserAuthOption) AuthFunc
AllowUsersFile is an AuthFunc which authenticates user input based on a (static) user list loaded from a file on initialization.
Example Code:
New(Options{Allow: AllowUsersFile("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 ...
type BasicAuth ¶ added in v12.2.0
type BasicAuth 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.
Read https://tools.ietf.org/html/rfc2617 and https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication for details.
type ErrCredentialsExpired ¶ added in v12.2.0
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 ¶ added in v12.2.0
func (e ErrCredentialsExpired) Error() string
type ErrCredentialsForbidden ¶ added in v12.2.0
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 ¶ added in v12.2.0
func (e ErrCredentialsForbidden) Error() string
type ErrCredentialsInvalid ¶ added in v12.2.0
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 ¶ added in v12.2.0
func (e ErrCredentialsInvalid) Error() string
type ErrCredentialsMissing ¶ added in v12.2.0
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 ¶ added in v12.2.0
func (e ErrCredentialsMissing) Error() string
type ErrHTTPVersion ¶ added in v12.2.0
type ErrHTTPVersion struct{}
ErrHTTPVersion is fired when Options.HTTPSOnly was enabled and the current request is a plain http one.
func (ErrHTTPVersion) Error ¶ added in v12.2.0
func (e ErrHTTPVersion) Error() string
type ErrorHandler ¶ added in v12.2.0
ErrorHandler should handle the given request credentials failure. See Options.ErrorHandler and DefaultErrorHandler for details.
type GC ¶ added in v12.2.0
type GC struct { Context stdContext.Context Every time.Duration }
GC holds the context and the tick duration to clear expired stored credentials. See the Options.GC field.
type Options ¶ added in v12.2.0
type Options 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, allowing it to transmit the request further. Proxy bool // If set to true then any non-https request will immediately // dropped with a 505 status code (StatusHTTPVersionNotSupported) response. // // 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 two available builtin values, the AllowUsers and AllowUsersFile, // both of them decode a static list of users and compares with the user input (see BCRYPT function too). // Usage: // - Allow: AllowUsers(iris.Map{"username": "...", "password": "...", "other_field": ...}, [BCRYPT]) // - Allow: AllowUsersFile("users.yml", [BCRYPT]) // Look the user.go source file for details. Allow AuthFunc // MaxAge sets expiration duration for the in-memory credentials map. // By default an old map entry will be removed when the user visits a page. // 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 afer // MaxTries amount of sign in failures (see MaxTriesCookie). // Note that the client can modify the cookie and its value, // do NOT depend for any type of custom domain logic based on this field. // 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 // If not empty then this session key will be used to store // the current tries of login failures. If not a session manager // was registered then the application will log an error. // Note that this field has a priority over the MaxTriesCookie. MaxTriesSession 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 // 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 }
Options holds the necessary information that the BasicAuth instance needs to perform. The only required value is the Allow field.
Usage:
opts := Options { ... } auth := New(opts)
type User ¶ added in v12.2.0
type User interface { context.UserGetUsername context.UserGetPassword }
User is a partial part of the iris.User interface. It's used to declare a static slice of registered User for authentication.
type UserAuthOption ¶ added in v12.2.0
type UserAuthOption func(*UserAuthOptions)
UserAuthOption is the option function type for the Default and Load (and AllowUsers, AllowUsersFile) functions.
See BCRYPT for an implementation.
type UserAuthOptions ¶ added in v12.2.0
type UserAuthOptions struct { // Defaults to plain check, can be modified for encrypted passwords, // see the BCRYPT optional function. ComparePassword func(stored, userPassword string) bool }
UserAuthOptions holds optional user authentication options that can be given to the builtin Default and Load (and AllowUsers, AllowUsersFile) functions.