Documentation ¶
Overview ¶
Package hashauth provides a means of creating a cookie- and url-friendly token containing arbitrary encoded information, with an embedded authentication code that ensures that it was created by you (not forged) and is in its original form (not tampered with).
Primary use-cases are login sessions, password reset tokens, and the like. Any situation where you need to provide to the user a token they can present back to you which contains a small amount of data and authentication guarantees.
The package provides methods for Encoding, Validating, and Decoding tokens, and also a higher-level API for interacting with HTTP request and response cookies for sessions.
Login session example:
var Signer = hashauth.New([]byte("secret key"), nil) type LoginSession struct { UserID int Expiration time.Time } // implementing this method causes hashauth to set the Expires cookie attr func (sess *LoginSession) Expires() time.Time { return sess.Expiration } func AuthRequired(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { sess := new(LoginSession) err := Signer.Authenticate(r, sess) if err != nil { http.Error(w, "Login Required", http.StatusForbidden) } else { h.ServeHTTP(w, r) } }) } func LogUserIn(w http.ResponseWriter, uid int) error { return Signer.SetCookie(w, &LoginSession{ UserID: uid, Expiration: time.Now().UTC().Add(7*24*time.Hour), }) } func LogUserOut(w http.ResponseWriter) { Signer.ClearCookie(w) }
Index ¶
- Variables
- type Expirer
- type HashAuth
- func (ha *HashAuth) Authenticate(r *http.Request, container interface{}) error
- func (ha *HashAuth) CheckPin(pin string, token []byte) bool
- func (ha *HashAuth) ClearCookie(w http.ResponseWriter)
- func (ha *HashAuth) Decode(token []byte, container interface{}) error
- func (ha *HashAuth) Encode(session interface{}) ([]byte, error)
- func (ha *HashAuth) Pin(token []byte) (string, error)
- func (ha *HashAuth) SetCookie(w http.ResponseWriter, session interface{}) error
- func (ha *HashAuth) Validate(token []byte) bool
- type MaxAger
- type Options
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalid is returned when an authentication check fails. ErrInvalid = errors.New("hashauth: token validation failed") // ErrExpired is returned when an Expirer session indicates that // an authentication token's expiration time has passed. ErrExpired = errors.New("hashauth: expiration time has passed") )
Functions ¶
This section is empty.
Types ¶
type Expirer ¶
Expirer can be implemented by session data types, in which case their expiration time will be set as the cookie expiration time in HashAuth.SetCookie.
type HashAuth ¶
type HashAuth struct {
// contains filtered or unexported fields
}
HashAuth is an Encoder and Decoder of tokens.
func New ¶
New creates a new HashAuth En/Decoder. key should be a carefully guarded secret, with it anyone could forge a token. opts can be nil, in which case a sha256 hasher, a default cookie name, and no cookie attributes will be used.
func (*HashAuth) Authenticate ¶
Authenticate finds and decodes the auth token from a request, populating the container with the session data. It will return nil on success, or:
- http.ErrNoCookie if there is no auth header at all
- a decoding error if it is malformed
- ErrInvalid if there is a properly formatted token that is invalid
- ErrExpired if the session has expired
func (*HashAuth) ClearCookie ¶
func (ha *HashAuth) ClearCookie(w http.ResponseWriter)
ClearCookie adds a Set-Cookie header to a response that will remove the auth cookie.
func (*HashAuth) Decode ¶
Decode checks a token's validity and extracts the data encoded in it. May return ErrInvalid if the validity check fails. If the container is an Expirer and the token contains an expired session, it will return ErrExpired but still populate the container with token data.
func (*HashAuth) SetCookie ¶
func (ha *HashAuth) SetCookie(w http.ResponseWriter, session interface{}) error
SetCookie adds an encoded token as a cookie on an HTTP response. If the provided session data object implements the Expirer or MaxAger interfaces, then the corresponding cookie attribute will also be set. Other cookie attributes will be set according to the *Options with which the HashAuth was created.
type MaxAger ¶
MaxAger can be implemented by session data types, in which case the HashAuth.SetCookie method will set a max-age attribute (unless it also implements Expirer, which takes precedence).
type Options ¶
type Options struct { // The hash implementation to use. Defaults to sha256.New. Hash func() hash.Hash // A separate signing key to use for PIN codes (Pin() and CheckPin() // methods). Defaults to the main signing key. PINSignKey []byte // The length of PIN codes generated by this HashAuth. Defaults to 5, // has a maximum value of 18. PINLength int // The name of the cookie to use for Authenticate(), SetCookie(), and // ClearCookie(). Defaults to "_ha". CookieName string // The 'path' attribute to use for the cookie. Defaults to none/empty. CookiePath string // The 'domain' attribute for the cookie. Defaults to none/empty. CookieDomain string // Whether to include the 'secure' cookie attribute. Defaults to false. CookieSecure bool // Whether to include the 'httponly' cookie attribute. Defaults to false. CookieHTTPOnly bool }
Options is a simple container for various HashAuth options.