auth

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2020 License: Apache-2.0 Imports: 16 Imported by: 0

README

HTTP Authentication implementation in Go

Build Status codecov

This is an implementation of HTTP Basic in Go language. Which is basically a mash-up of abbot/go-http-auth and GehirnInc/crypt

Features

  • Supports HTTP Basic
  • Supports htpasswd formatted files.
  • Automatic reloading of password files.
  • Pluggable interface for user/password storage.
  • Supports MD5, SHA1 and BCrypt for Basic authentication password storage.
  • Configurable Digest nonce cache size with expiration.
  • Wrapper for legacy http handlers (http.HandlerFunc interface)

Example usage

This is a complete working example for Basic auth:

package main

import (
        "fmt"
        "net/http"

        auth "github.com/wolviecb/basic-auth"
)

func Secret(user, realm string) string {
        if user == "john" {
                // password is "hello"
                return "$apr1$Xfu5Jqwg$DYvBqzdcW84tnuq5SbnZE/"
        }
        return ""
}

func handle(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
        fmt.Fprintf(w, "<html><body><h1>Hello, %s!</h1></body></html>", r.Username)
}

func main() {
        authenticator := auth.NewBasicAuthenticator("example.com", Secret)
        http.HandleFunc("/", authenticator.Wrap(handle))
        http.ListenAndServe(":8080", nil)
}

See more examples in the "examples" directory.

Documentation

Overview

Package auth is an implementation of HTTP Basic and HTTP Digest authentication.

Package auth is a implementation of HTTP Basic in Go language.

Package auth is a implementation of HTTP Basic in Go language.

Index

Constants

View Source
const AuthUsernameHeader = "X-Authenticated-Username"

AuthUsernameHeader is the header set by JustCheck functions. It contains an authenticated username (if authentication was successful).

Variables

View Source
var (
	// NormalHeaders are the regular Headers used by an HTTP Server for
	// request authentication.
	NormalHeaders = &Headers{
		Authenticate:      "WWW-Authenticate",
		Authorization:     "Authorization",
		AuthInfo:          "Authentication-Info",
		UnauthCode:        http.StatusUnauthorized,
		UnauthContentType: "text/plain",
		UnauthResponse:    fmt.Sprintf("%d %s\n", http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized)),
	}

	// ProxyHeaders are Headers used by an HTTP Proxy server for proxy
	// access authentication.
	ProxyHeaders = &Headers{
		Authenticate:      "Proxy-Authenticate",
		Authorization:     "Proxy-Authorization",
		AuthInfo:          "Proxy-Authentication-Info",
		UnauthCode:        http.StatusProxyAuthRequired,
		UnauthContentType: "text/plain",
		UnauthResponse:    fmt.Sprintf("%d %s\n", http.StatusProxyAuthRequired, http.StatusText(http.StatusProxyAuthRequired)),
	}
)

Functions

func CheckSecret added in v0.5.0

func CheckSecret(password, secret string) bool

CheckSecret returns true if the password matches the encrypted secret.

func H

func H(data string) string

H function for MD5 algorithm (returns a lower-case hex MD5 digest)

func JustCheck

func JustCheck(auth AuthenticatorInterface, wrapped http.HandlerFunc) http.HandlerFunc

JustCheck returns a new http.HandlerFunc, which requires authenticator to successfully authenticate a user before calling wrapped http.HandlerFunc.

func ParseList

func ParseList(value string) []string

ParseList parses a comma-separated list of values as described by RFC 2068 and returns list elements.

Lifted from https://code.google.com/p/gorilla/source/browse/http/parser/parser.go which was ported from urllib2.parse_http_list, from the Python standard library.

func ParsePairs

func ParsePairs(value string) map[string]string

ParsePairs extracts key/value pairs from a comma-separated list of values as described by RFC 2068 and returns a map[key]value. The resulting values are unquoted. If a list element doesn't contain a "=", the key is the element itself and the value is an empty string.

Lifted from https://code.google.com/p/gorilla/source/browse/http/parser/parser.go

Types

type AuthenticatedHandlerFunc

type AuthenticatedHandlerFunc func(http.ResponseWriter, *AuthenticatedRequest)

AuthenticatedHandlerFunc is like http.HandlerFunc, but takes AuthenticatedRequest instead of http.Request

type AuthenticatedRequest

type AuthenticatedRequest struct {
	http.Request
	// Username is the authenticated user name. Current API implies that
	// Username is never empty, which means that authentication is
	// always done before calling the request handler.
	Username string
}

AuthenticatedRequest is passed to AuthenticatedHandlerFunc instead of *http.Request.

type Authenticator

type Authenticator func(AuthenticatedHandlerFunc) http.HandlerFunc

Authenticator wraps an AuthenticatedHandlerFunc with authentication-checking code.

Typical Authenticator usage is something like:

authenticator := SomeAuthenticator(...)
http.HandleFunc("/", authenticator(my_handler))

Authenticator wrapper checks the user authentication and calls the wrapped function only after authentication has succeeded. Otherwise, it returns a handler which initiates the authentication procedure.

type AuthenticatorInterface deprecated

type AuthenticatorInterface interface {
	// NewContext returns a new context carrying authentication
	// information extracted from the request.
	NewContext(ctx context.Context, r *http.Request) context.Context

	// Wrap returns an http.HandlerFunc which wraps
	// AuthenticatedHandlerFunc with this authenticator's
	// authentication checks.
	Wrap(AuthenticatedHandlerFunc) http.HandlerFunc
}

AuthenticatorInterface is the interface implemented by BasicAuth and DigestAuth authenticators.

Deprecated: this interface is not coherent. New code should define and use your own interfaces with a required subset of authenticator methods.

type BasicAuth

type BasicAuth struct {
	Realm   string
	Secrets SecretProvider
	// Headers used by authenticator. Set to ProxyHeaders to use with
	// proxy server. When nil, NormalHeaders are used.
	Headers *Headers
}

BasicAuth is an authenticator implementation for 'Basic' HTTP Authentication scheme (RFC 7617).

func NewBasicAuthenticator deprecated

func NewBasicAuthenticator(realm string, secrets SecretProvider) *BasicAuth

NewBasicAuthenticator returns a BasicAuth initialized with provided realm and secrets.

Deprecated: new code should construct BasicAuth values directly.

func (*BasicAuth) CheckAuth

func (a *BasicAuth) CheckAuth(r *http.Request) string

CheckAuth checks the username/password combination from the request. Returns either an empty string (authentication failed) or the name of the authenticated user.

func (*BasicAuth) NewContext

func (a *BasicAuth) NewContext(ctx context.Context, r *http.Request) context.Context

NewContext returns a context carrying authentication information for the request.

func (*BasicAuth) RequireAuth

func (a *BasicAuth) RequireAuth(w http.ResponseWriter, r *http.Request)

RequireAuth is an http.HandlerFunc for BasicAuth which initiates the authentication process (or requires reauthentication).

func (*BasicAuth) Wrap deprecated

Wrap returns an http.HandlerFunc, which wraps AuthenticatedHandlerFunc with this BasicAuth authenticator's authentication checks. Once the request contains valid credentials, it calls wrapped AuthenticatedHandlerFunc.

Deprecated: new code should use NewContext instead.

type File

type File struct {
	Path string
	Info os.FileInfo
	/* must be set in inherited types during initialization */
	Reload func()
	// contains filtered or unexported fields
}

File handles automatic file reloading on changes.

func (*File) ReloadIfNeeded

func (f *File) ReloadIfNeeded()

ReloadIfNeeded checks file Stat and calls Reload() if any changes were detected. File mutex is Locked for the duration of Reload() call.

This function will panic() if Stat fails.

type Headers

type Headers struct {
	Authenticate      string // WWW-Authenticate
	Authorization     string // Authorization
	AuthInfo          string // Authentication-Info
	UnauthCode        int    // 401
	UnauthContentType string // text/plain
	UnauthResponse    string // Unauthorized.
}

Headers contains header and error codes used by authenticator.

func (*Headers) V

func (h *Headers) V() *Headers

V returns NormalHeaders when h is nil, or h otherwise. Allows to use uninitialized *Headers values in structs.

type HtpasswdFile

type HtpasswdFile struct {
	// File is used for automatic reloading of the authentication data.
	File
	// Users is a map of users to their secrets (salted encrypted
	// passwords).
	Users map[string]string
	// contains filtered or unexported fields
}

HtpasswdFile is a File holding basic authentication data.

type Info

type Info struct {
	// Authenticated is set to true when request was authenticated
	// successfully, i.e. username and password passed in request did
	// pass the check.
	Authenticated bool

	// Username contains a user name passed in the request when
	// Authenticated is true. It's value is undefined if Authenticated
	// is false.
	Username string

	// ResponseHeaders contains extra headers that must be set by server
	// when sending back HTTP response.
	ResponseHeaders http.Header
}

Info contains authentication information for the request.

func FromContext

func FromContext(ctx context.Context) *Info

FromContext returns authentication information from the context or nil if no such information present.

func (*Info) UpdateHeaders

func (i *Info) UpdateHeaders(headers http.Header)

UpdateHeaders updates headers with this Info's ResponseHeaders. It is safe to call this function on nil Info.

type SecretProvider

type SecretProvider func(user, realm string) string

SecretProvider is used by authenticators. Takes user name and realm as an argument, returns secret required for authentication (HA1 for digest authentication, properly encrypted password for basic).

Returning an empty string means failing the authentication.

func HtpasswdFileProvider

func HtpasswdFileProvider(filename string) SecretProvider

HtpasswdFileProvider is a SecretProvider implementation based on htpasswd-formated files. It will automatically reload htpasswd file on changes. It panics on syntax errors in htpasswd files. Realm argument of the SecretProvider is ignored.

Directories

Path Synopsis
Package crypt provides interface for password crypt functions and collects common constants.
Package crypt provides interface for password crypt functions and collects common constants.
apr1crypt
Package apr1crypt implements the standard Unix MD5-crypt algorithm created by Poul-Henning Kamp for FreeBSD, and modified by the Apache project.
Package apr1crypt implements the standard Unix MD5-crypt algorithm created by Poul-Henning Kamp for FreeBSD, and modified by the Apache project.
common
Package common contains routines used by multiple password hashing algorithms.
Package common contains routines used by multiple password hashing algorithms.
md5crypt
Package md5crypt implements the standard Unix MD5-crypt algorithm created by Poul-Henning Kamp for FreeBSD.
Package md5crypt implements the standard Unix MD5-crypt algorithm created by Poul-Henning Kamp for FreeBSD.

Jump to

Keyboard shortcuts

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