authhttp

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 16 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 BearerAuthenticator. jwt.Manager satisfies it. Use MustRequireBearer only when you intentionally want constructor-style panic behavior.

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, pass routes.WithAuth(authHandler.AuthResolver()). Omitting that resolver is a mount-time error for protected routes.

err := routes.Mount(r, "", authHandler.Routes(), routes.WithAuth(authHandler.AuthResolver()))

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.
  • NewStaticPasswordAuthenticator requires a non-empty user ID and password.
  • 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 ErrBearerAuthenticatorMissing = errors.New("bearer authenticator is required")

Functions

func LoginRateLimit

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

LoginRateLimit returns a middleware when enabled, otherwise nil. LoginRateLimit 在启用时返回中间件,否则返回 nil。

func MustRequireBearer added in v0.1.3

func MustRequireBearer(auth BearerAuthenticator) func(stdhttp.Handler) stdhttp.Handler

MustRequireBearer panics when RequireBearer returns an error. MustRequireBearer 在 RequireBearer 返回错误时 panic。

func RequireBearer

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

RequireBearer enforces a valid Bearer token. RequireBearer 强制要求有效的 Bearer token。 Example / 示例:

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

func ValidateStaticPasswordVisibleASCII

func ValidateStaticPasswordVisibleASCII(password string) error

ValidateStaticPasswordVisibleASCII validates a static password using visible ASCII only. ValidateStaticPasswordVisibleASCII 使用仅可见 ASCII 规则校验静态密码。 This helper is optional and is not called by NewHandler. 这是可选 helper;NewHandler 不会自动调用它。

func VerifyCredential

func VerifyCredential(expected, got string) bool

VerifyCredential compares two credential strings using an exact byte match. VerifyCredential 使用精确字节匹配比较两段凭据。

Types

type BearerAuthenticator

type BearerAuthenticator = auth.BearerAuthenticator

BearerAuthenticator describes the bearer validation required by auth middleware. BearerAuthenticator 描述认证中间件所需的 Bearer 校验能力。

type Handler

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

Handler exposes auth endpoints for login/refresh/logout. Handler 暴露登录/刷新/登出端点。

func NewHandler

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

NewHandler builds a Handler with optional overrides. NewHandler 构建 Handler,可选覆盖默认配置。

func (*Handler) AuthResolver

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

AuthResolver returns the auth middleware mapping required by Routes. AuthResolver 返回 Routes 所需的认证中间件映射。

func (*Handler) Register

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

Register mounts auth routes onto the router with the required auth middleware. Register 将认证路由及其所需的认证中间件一起挂载到路由器。

func (*Handler) Routes

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

Routes returns auth routes for export or manual mounting. Manual mounts must pass routes.WithAuth(h.AuthResolver()) so protected routes receive their required middleware. Routes 返回认证路由,供导出或手工挂载。 手工挂载时必须同时传入 routes.WithAuth(h.AuthResolver()),否则受保护路由无法完成装配。

type LoginAuthenticator

type LoginAuthenticator = auth.LoginAuthenticator

LoginAuthenticator verifies login credentials and returns the authenticated user ID. Implementations may ignore username when the host application does not need it. LoginAuthenticator 负责校验登录凭据并返回认证成功后的用户 ID; 当宿主项目不需要用户名时,实现可以忽略 username。

func NewStaticPasswordAuthenticator

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

NewStaticPasswordAuthenticator builds a LoginAuthenticator backed by one fixed password. NewStaticPasswordAuthenticator 构造一个使用固定密码的 LoginAuthenticator。

type LoginAuthenticatorFunc

type LoginAuthenticatorFunc = auth.LoginAuthenticatorFunc

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

type Options

type Options struct {
	// LoginAuthenticator verifies login credentials and returns the authenticated user ID.
	// LoginAuthenticator 负责校验登录凭据,并返回认证成功后的用户 ID。
	LoginAuthenticator LoginAuthenticator
	// BasePath is the auth route prefix relative to the current router mount.
	// BasePath 是相对于当前路由挂载点的认证路由前缀。
	BasePath string
	// RefreshCookiePath is the final public cookie path visible to the browser.
	// When empty, it defaults to BasePath.
	// RefreshCookiePath 是浏览器可见的最终公开 cookie 路径;为空时默认等于 BasePath。
	RefreshCookiePath string
	CSRFCookiePath    string

	RefreshCookieName string
	CSRFCookieName    string
	CSRFHeaderName    string
	TrustedProxies    []netip.Prefix

	MaxBodyBytes int64
	RateLimit    *RateLimitOptions
}

Options controls auth HTTP behavior. Options 控制认证 HTTP 行为。

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns safe defaults aligned with the existing handlers. DefaultOptions 返回与现有处理器一致的安全默认值。

type RateLimitOptions

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

RateLimitOptions configures login rate limiting. RateLimitOptions 配置登录限流。

Disabled disables rate limiting when true (default: false). Disabled 为 true 时禁用限流(默认:false)。

func DefaultRateLimitOptions

func DefaultRateLimitOptions() RateLimitOptions

DefaultRateLimitOptions returns the default login rate limit configuration. DefaultRateLimitOptions 返回默认的登录限流配置。

type TokenManager

type TokenManager = auth.TokenManager

TokenManager describes the auth functions required by the HTTP handler. TokenManager 描述 HTTP 处理器需要的认证能力。

Jump to

Keyboard shortcuts

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