basicauth

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2024 License: MIT Imports: 15 Imported by: 5

README

Basic Authentication

build status report card godocs

The most advanced and powerful Go HTTP middleware to handle basic authentication. It is fully compatible with the net/http package and third-party frameworks.

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.

$ 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 (see Options type and New function for real-world scenarios):

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

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

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

Access the authenticated User entry:

routeHandlerFunc := func(w http.ResponseWriter, r *http.Request) {
	user := basicauth.GetUser(r).(*basicauth.SimpleUser)
	// user.Username
	// user.Password
}

The *http.Request.BasicAuth() works too, but it has limitations when it comes to a custom user struct.

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

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 DefaultErrorHandler

func DefaultErrorHandler(w http.ResponseWriter, r *http.Request, err error)

DefaultErrorHandler is the default error handler for the Options.ErrorHandler field.

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

func GetUser

func GetUser(r *http.Request) interface{}

GetUser returns the current authenticated User. If no custom user was set then it should be a type of *basicauth.SimpleUser.

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.

Usage:

mux.HandleFunc("/", basicauth.HandlerFunc(auth, 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.

Types

type AuthFunc

type AuthFunc func(r *http.Request, username, password string) (interface{}, bool)

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

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

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

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

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]interface{}

Map is just a type alias of the map[string]interface{}.

type Middleware

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

Middleware is just a type alias of func(http.Handler) http.Handler

func Default

func Default(users interface{}, userOpts ...UserAuthOption) Middleware

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 Load

func Load(jsonOrYamlFilename string, userOpts ...UserAuthOption) Middleware

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

func New(opts Options) Middleware

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)
mux := http.NewServeMux()
[...routes]
http.ListenAndServe(":8080", auth(mux))

Access the user in the route handler with:

basicauth.GetUser(r).(*myCustomType) / (*basicauth.SimpleUser).

Look the BasicAuth type docs for more information.

type Options

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(map[string]interface{}{"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
	// 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.
	// 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 GetUser will return nil 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.

Usage:

opts := Options { ... }
auth := New(opts)

type SimpleUser

type SimpleUser struct {
	Username string
	Password string
}

SimpleUser implements the User interface and it is used internally to store the current authenticated user to the HTTP request value when the Options.Allow does not return any value.

func (*SimpleUser) GetPassword

func (u *SimpleUser) GetPassword() string

GetPassword returns the Username 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 func(*UserAuthOptions)

UserAuthOption is the option function type for the Default and Load (and AllowUsers, AllowUsersFile) functions.

See BCRYPT for an implementation.

type UserAuthOptions

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.

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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