authhttp

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 17 Imported by: 0

README

auth/http

auth/http adapts auth.Service to chi routes, bearer middleware, cookies, and JSON responses. Import path: github.com/Ithildur/EiluneKit/auth/http; package name: authhttp.

Quick Start

manager, err := authjwt.New(signingKey, authstore.NewMemoryStore())
if err != nil {
	return err
}

authHandler, err := authhttp.NewHandler(manager, authhttp.Options{
	LoginAuthenticator: authhttp.LoginAuthenticatorFunc(func(ctx context.Context, username, password string) (string, bool, error) {
		user, err := repo.FindByUsername(ctx, username)
		if err != nil {
			return "", false, err
		}
		if user == nil {
			return "", false, nil
		}

		computedHash := hashPassword(password, user.Salt)
		if !authhttp.VerifyCredential(user.PasswordHash, computedHash) {
			return "", false, nil
		}
		return user.ID, true, nil
	}),
})
if err != nil {
	return err
}

if err := authHandler.Register(r); err != nil {
	return err
}

POST /auth/login accepts username, password, and a required persistence field with persistent or session. LoginAuthenticator verifies the credentials; the handler returns an access token and sets refresh/CSRF cookies with matching persistence.

Static Credential

For a fixed shared secret:

staticAuth, err := authhttp.NewStaticPasswordAuthenticator("dashboard-admin", adminPassword)
if err != nil {
	return err
}

authHandler, err := authhttp.NewHandler(manager, authhttp.Options{
	LoginAuthenticator: staticAuth,
})
if err != nil {
	return err
}
if err := authhttp.ValidateStaticPasswordVisibleASCII(adminPassword); err != nil {
	return err
}

Bearer Middleware

bearer, err := authhttp.RequireBearer(manager)
if err != nil {
	return err
}
r.Use(bearer)

RequireBearer accepts any AccessTokenValidator. It parses the HTTP Authorization: Bearer header in the HTTP layer, while jwt.Manager only validates the raw access token.

Routes

Default base path: /auth.

Route Auth
POST /auth/login routes.AuthNone
POST /auth/refresh routes.AuthRefreshCookie
POST /auth/logout routes.AuthRefreshCookie
DELETE /auth/sessions/current routes.AuthBearerRequired
DELETE /auth/sessions routes.AuthBearerRequired
DELETE /auth/sessions/{sid} routes.AuthBearerRequired

Handler.Routes() returns the same route set as declarative http/routes.Route values. When mounting them manually, first build the resolver with authHandler.AuthResolver(), then pass routes.WithAuth(resolver). Omitting that resolver is a mount-time error for protected routes.

resolver, err := authHandler.AuthResolver()
if err != nil {
	return err
}
err = routes.Mount(r, "", authHandler.Routes(), routes.WithAuth(resolver))

Options

  • LoginAuthenticator: required credential verification entrypoint
  • BasePath: auth route prefix relative to the current router mount; default /auth
  • RefreshCookiePath: browser-visible refresh-cookie path; default BasePath
  • CSRFCookiePath: CSRF cookie path; default /
  • RefreshCookieName, CSRFCookieName, CSRFHeaderName: cookie and header names
  • TrustedProxies: forwarded-header trust boundary for rate limiting and secure-cookie detection
  • MaxBodyBytes: request body size limit for auth endpoints
  • RateLimit: login rate-limit settings

Forwarded headers are trusted only when TrustedProxies is set. The default rate-limit key uses RemoteAddr.

Contracts

  • NewHandler requires both a TokenManager and Options.LoginAuthenticator.
  • NewHandler takes one Options struct; fields other than LoginAuthenticator fall back to defaults when left zero-valued.
  • NewStaticPasswordAuthenticator requires a non-empty user ID and password.
  • AuthResolver may fail when the handler is nil or the bearer middleware dependencies are missing.
  • VerifyCredential performs exact byte comparison and is suitable for pre-hashed or application-derived credentials.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrAccessTokenValidatorMissing = errors.New("access token validator is required")

Functions

func LoginRateLimit

func LoginRateLimit(opts *RateLimitOptions) func(stdhttp.Handler) stdhttp.Handler

LoginRateLimit returns a login rate-limit middleware. Disabled or nil options return nil. LoginRateLimit 返回登录限流中间件。 传入 nil 或 Disabled 时返回 nil。

func RequireBearer

func RequireBearer(auth AccessTokenValidator) (func(stdhttp.Handler) stdhttp.Handler, error)

RequireBearer returns a Bearer-token middleware. Call bearer, err := RequireBearer(auth) and then r.Use(bearer). RequireBearer 返回 Bearer token 中间件。 调用 bearer, err := RequireBearer(auth),再执行 r.Use(bearer)。 Example / 示例:

bearer, err := authhttp.RequireBearer(jwtManager)
if err != nil { ... }
r.Use(bearer)

func ValidateStaticPasswordVisibleASCII

func ValidateStaticPasswordVisibleASCII(password string) error

ValidateStaticPasswordVisibleASCII validates a static password. NewHandler does not call it automatically. ValidateStaticPasswordVisibleASCII 校验静态密码。 NewHandler 不会自动调用它。

func VerifyCredential

func VerifyCredential(expected, got string) bool

VerifyCredential compares expected and got with an exact byte match. VerifyCredential 使用精确字节匹配比较 expected 和 got。

Types

type AccessTokenValidator added in v0.1.5

type AccessTokenValidator = auth.AccessTokenValidator

AccessTokenValidator validates access tokens for RequireBearer. AccessTokenValidator 为 RequireBearer 校验 access token。

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler serves auth endpoints. Handler 提供认证端点。

func NewHandler

func NewHandler(manager TokenManager, opts Options) (*Handler, error)

NewHandler returns a Handler. Call NewHandler(manager, opts). Zero-valued options fall back to DefaultOptions. NewHandler 返回 Handler。 调用 NewHandler(manager, opts)。 零值选项会回退到 DefaultOptions。

func (*Handler) AuthResolver

func (h *Handler) AuthResolver() (routes.AuthResolver, error)

AuthResolver returns the middleware mapping required by Routes. Call routes.WithAuth(resolver) when mounting Routes manually. AuthResolver 返回 Routes 所需的中间件映射。 手工挂载 Routes 时调用 routes.WithAuth(resolver)。

func (*Handler) Register

func (h *Handler) Register(r chi.Router) error

Register mounts the auth routes on r. Call Register(r) to mount routes with their auth middleware. Register 在 r 上挂载认证路由。 调用 Register(r) 挂载路由及其认证中间件。

func (*Handler) Routes

func (h *Handler) Routes() []routes.Route

Routes returns the auth routes. Call AuthResolver and routes.WithAuth when mounting them manually. Routes 返回认证路由。 手工挂载时先调用 AuthResolver,再配合 routes.WithAuth 使用。

type LoginAuthenticator

type LoginAuthenticator = auth.LoginAuthenticator

LoginAuthenticator validates login credentials. Implementations may ignore username. LoginAuthenticator 校验登录凭据。 实现可以忽略 username。

func NewStaticPasswordAuthenticator

func NewStaticPasswordAuthenticator(userID, expectedPassword string) (LoginAuthenticator, error)

NewStaticPasswordAuthenticator returns a LoginAuthenticator for one fixed password. NewStaticPasswordAuthenticator 返回基于固定密码的 LoginAuthenticator。

type LoginAuthenticatorFunc

type LoginAuthenticatorFunc = auth.LoginAuthenticatorFunc

LoginAuthenticatorFunc adapts a function to LoginAuthenticator. LoginAuthenticatorFunc 将函数适配为 LoginAuthenticator。

type Options

type Options struct {
	// LoginAuthenticator validates login credentials.
	// LoginAuthenticator 校验登录凭据。
	LoginAuthenticator LoginAuthenticator
	// BasePath is the auth route prefix.
	// BasePath 是认证路由前缀。
	BasePath string
	// RefreshCookiePath defaults to BasePath when empty.
	// RefreshCookiePath 为空时默认等于 BasePath。
	RefreshCookiePath string
	// CSRFCookiePath defaults to "/".
	// CSRFCookiePath 默认为 "/"。
	CSRFCookiePath string

	// RefreshCookieName is the refresh cookie name.
	// RefreshCookieName 是 refresh cookie 名。
	RefreshCookieName string
	// CSRFCookieName is the CSRF cookie name.
	// CSRFCookieName 是 CSRF cookie 名。
	CSRFCookieName string
	// CSRFHeaderName is the CSRF request header name.
	// CSRFHeaderName 是 CSRF 请求头名。
	CSRFHeaderName string
	// TrustedProxies enables forwarded-header trust.
	// TrustedProxies 启用转发头信任。
	TrustedProxies []netip.Prefix

	// MaxBodyBytes limits the login body size.
	// MaxBodyBytes 限制登录请求体大小。
	MaxBodyBytes int64
	// RateLimit configures login rate limiting.
	// RateLimit 配置登录限流。
	RateLimit *RateLimitOptions
}

Options configures NewHandler. Options 配置 NewHandler。

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns the default handler options. DefaultOptions 返回默认 handler 选项。

type RateLimitOptions

type RateLimitOptions struct {
	Disabled       bool
	Requests       int
	Window         time.Duration
	IPv4PrefixBits int
	IPv6PrefixBits int
	TrustedProxies []netip.Prefix
	KeyFunc        httprate.KeyFunc
}

RateLimitOptions configures LoginRateLimit. RateLimitOptions 配置 LoginRateLimit。

func DefaultRateLimitOptions

func DefaultRateLimitOptions() RateLimitOptions

DefaultRateLimitOptions returns the default login rate limit options. DefaultRateLimitOptions 返回默认登录限流选项。

type TokenManager

type TokenManager = auth.TokenManager

TokenManager provides the auth operations used by Handler. TokenManager 为 Handler 提供认证操作。

Jump to

Keyboard shortcuts

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