Documentation
¶
Overview ¶
Package httpauth adapts an iam.Service to net/http.
It depends only on the iam.Service interface, so it works the same with the in-process service and with a remote one.
Typical use:
auth, _ := httpauth.New(httpauth.Config{Service: svc})
mux.Handle("GET /books", auth.RequirePermission("read", "book", nil)(books))
http.ListenAndServe(addr, auth.Protect(mux))
Protect identifies the caller on every request (session cookie or bearer token), applies cross-origin protection to unsafe methods, and requires a CSRF token for cookie-authenticated unsafe requests. The Require* middlewares then reject anonymous or unauthorized callers.
Index ¶
- Variables
- func SessionFrom(ctx context.Context) (*iam.SessionInfo, bool)
- func SubjectFrom(ctx context.Context) (*iam.Subject, bool)
- func WithSubject(ctx context.Context, subject *iam.Subject, sess *iam.SessionInfo) context.Context
- type CSRFConfig
- type Config
- type CookieConfig
- type Middleware
- func (m *Middleware) CSRFToken(r *http.Request) string
- func (m *Middleware) ClientInfo(r *http.Request) iam.ClientInfo
- func (m *Middleware) EndSession(w http.ResponseWriter, r *http.Request) error
- func (m *Middleware) Protect(next http.Handler) http.Handler
- func (m *Middleware) RequireAuth(next http.Handler) http.Handler
- func (m *Middleware) RequirePermission(action policy.Action, resourceType string, ...) func(http.Handler) http.Handler
- func (m *Middleware) RequireRole(roles ...string) func(http.Handler) http.Handler
- func (m *Middleware) StartSession(w http.ResponseWriter, res *iam.LoginResult) string
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUnauthenticated is passed to the ErrorHandler for anonymous // requests to protected handlers. ErrUnauthenticated = errors.New("httpauth: authentication required") // ErrForbidden is passed to the ErrorHandler for denied requests. ErrForbidden = errors.New("httpauth: forbidden") // ErrCSRF is passed to the ErrorHandler when the CSRF token is missing // or wrong. ErrCSRF = errors.New("httpauth: invalid CSRF token") )
Functions ¶
func SessionFrom ¶
func SessionFrom(ctx context.Context) (*iam.SessionInfo, bool)
SessionFrom returns the authenticated session, if any.
func SubjectFrom ¶
SubjectFrom returns the authenticated subject, if any.
func WithSubject ¶
WithSubject returns a context carrying subject and session, as Protect would set them. Intended for tests of handlers.
Types ¶
type CSRFConfig ¶
type CSRFConfig struct {
// Disabled turns off both checks. Only do this if another layer
// provides CSRF protection.
Disabled bool
// Key derives per-session CSRF tokens (HMAC-SHA256). At least 32
// bytes. If empty, a random key is generated at startup, so tokens do
// not survive restarts and differ between instances.
Key []byte
// TrustedOrigins are additional origins (scheme://host[:port]) allowed
// to make cross-origin unsafe requests.
TrustedOrigins []string
// HeaderName defaults to "X-CSRF-Token"; FieldName (form field) to
// "csrf_token".
HeaderName string
FieldName string
}
CSRFConfig configures cross-site request forgery protection.
type Config ¶
type Config struct {
Service iam.Service
// Modes the middleware accepts. Default: cookie only.
Modes []session.Mode
Cookie CookieConfig
CSRF CSRFConfig
// TrustedProxies are the networks of reverse proxies whose
// X-Forwarded-For header is believed. Empty: RemoteAddr is used.
TrustedProxies []netip.Prefix
// ErrorHandler writes error responses. Default: JSON {"error": "..."}.
ErrorHandler func(w http.ResponseWriter, r *http.Request, status int, err error)
}
Config configures the middleware.
type CookieConfig ¶
type CookieConfig struct {
// Name defaults to "__Host-session", or "session" when Insecure is set
// (the __Host- prefix requires Secure).
Name string
// Insecure drops the Secure attribute. Only for local development over
// plain HTTP; never in production.
Insecure bool
// SameSite defaults to http.SameSiteLaxMode. Strict is also supported;
// None is rejected.
SameSite http.SameSite
}
CookieConfig configures the session cookie.
type Middleware ¶
type Middleware struct {
// contains filtered or unexported fields
}
Middleware is the configured HTTP layer.
func New ¶
func New(cfg Config) (*Middleware, error)
New validates the configuration and returns the middleware.
func (*Middleware) CSRFToken ¶
func (m *Middleware) CSRFToken(r *http.Request) string
CSRFToken returns the CSRF token for the request's cookie session, or "" if the request is not cookie-authenticated. Send it to the page (meta tag, JSON) and echo it back in the X-CSRF-Token header or csrf_token field.
func (*Middleware) ClientInfo ¶
func (m *Middleware) ClientInfo(r *http.Request) iam.ClientInfo
ClientInfo returns the client's IP and user agent for iam requests.
X-Forwarded-For is only used when the direct peer is a trusted proxy; the client IP is then the rightmost address not in TrustedProxies.
func (*Middleware) EndSession ¶
func (m *Middleware) EndSession(w http.ResponseWriter, r *http.Request) error
EndSession logs out the cookie session of r (if any) and clears the cookie.
func (*Middleware) Protect ¶
func (m *Middleware) Protect(next http.Handler) http.Handler
Protect wraps the whole handler tree. It:
- rejects cross-origin unsafe requests (http.CrossOriginProtection, based on Sec-Fetch-Site / Origin), including unauthenticated ones such as login forms;
- identifies the caller from the session cookie or the Authorization header; invalid credentials make the request anonymous;
- for unsafe methods authenticated by cookie, requires the per-session CSRF token (header or form field).
Bearer-authenticated requests are not subject to CSRF checks: browsers do not attach Authorization headers automatically.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/kararnab/iam/v2"
"github.com/kararnab/iam/v2/audit"
"github.com/kararnab/iam/v2/httpauth"
"github.com/kararnab/iam/v2/memstore"
"github.com/kararnab/iam/v2/password"
"github.com/kararnab/iam/v2/policy"
"github.com/kararnab/iam/v2/provider"
)
func main() {
ctx := context.Background()
users := memstore.NewUsers()
hasher, _ := password.NewArgon2id(password.DefaultParams, 0)
passwords, _ := password.NewProvider(users, hasher, password.DefaultPolicy)
rbac, _ := policy.NewRBAC(map[string][]policy.Permission{"member": {policy.P("read", "note")}})
svc, _ := iam.New(iam.Config{
Providers: []provider.AuthProvider{passwords},
Users: users,
Sessions: memstore.NewSessions(),
Policy: rbac,
Audit: audit.Func(func(context.Context, audit.Event) error { return nil }),
})
// Seed one member (normally done by sign-up).
users.PutSubject(iam.Subject{ID: "ana", Roles: []string{"member"}})
id, _ := passwords.Register(ctx, map[string]string{"username": "ana@example.com", "password": "correct horse battery staple"})
_ = users.LinkIdentity(ctx, "ana", *id)
auth, _ := httpauth.New(httpauth.Config{Service: svc})
mux := http.NewServeMux()
mux.Handle("GET /notes", auth.RequirePermission("read", "note", nil)(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s, _ := httpauth.SubjectFrom(r.Context())
fmt.Fprint(w, "notes for ", s.ID)
})))
handler := auth.Protect(mux)
// Anonymous request.
w := httptest.NewRecorder()
handler.ServeHTTP(w, httptest.NewRequest("GET", "/notes", nil))
fmt.Println(w.Code)
// Log in; StartSession sets the __Host-session cookie.
res, _ := svc.Login(ctx, iam.AuthRequest{Provider: password.ProviderName,
Params: map[string]string{"username": "ana@example.com", "password": "correct horse battery staple"}})
login := httptest.NewRecorder()
auth.StartSession(login, res)
cookie := login.Result().Cookies()[0]
fmt.Println(cookie.Name, cookie.HttpOnly, cookie.Secure, cookie.SameSite == http.SameSiteLaxMode)
r := httptest.NewRequest("GET", "/notes", nil)
r.AddCookie(cookie)
w = httptest.NewRecorder()
handler.ServeHTTP(w, r)
fmt.Println(w.Code, w.Body.String())
}
Output: 401 __Host-session true true true 200 notes for ana
func (*Middleware) RequireAuth ¶
func (m *Middleware) RequireAuth(next http.Handler) http.Handler
RequireAuth rejects anonymous requests with 401. Use inside Protect.
func (*Middleware) RequirePermission ¶
func (m *Middleware) RequirePermission(action policy.Action, resourceType string, resource func(*http.Request) policy.Resource) func(http.Handler) http.Handler
RequirePermission asks the policy engine whether the caller may perform action on resourceType. resource, if non-nil, fills in the resource ID and attributes from the request (for example r.PathValue("id")).
func (*Middleware) RequireRole ¶
RequireRole rejects anonymous requests (401) and subjects without any of the roles (403). Prefer RequirePermission, which goes through the policy engine and is audited.
func (*Middleware) StartSession ¶
func (m *Middleware) StartSession(w http.ResponseWriter, res *iam.LoginResult) string
StartSession sets the session cookie for a cookie-mode login result and returns the CSRF token for the new session. It does nothing for other modes.