Documentation
¶
Overview ¶
Package auth provides transport-neutral authentication flows. Package auth 提供与传输层无关的认证流程。
Index ¶
- Variables
- func ValidateStaticPassword(password string) error
- func VerifyCredential(expected, got string) bool
- func WithPrincipal(ctx context.Context, p Principal) context.Context
- type AccessTokenValidator
- type IssueOptions
- type LockedError
- type Lockout
- type LoginAuthenticator
- type LoginAuthenticatorFunc
- type MemoryLockout
- type MemoryLockoutOptions
- type Principal
- type PrincipalKind
- type RefreshResult
- type Service
- func (s *Service) ClearAllSessions(ctx context.Context) error
- func (s *Service) ClearUserSessions(ctx context.Context, userID string) error
- func (s *Service) Login(ctx context.Context, username, password string, opts IssueOptions) (Tokens, bool, error)
- func (s *Service) Logout(ctx context.Context, refresh string) error
- func (s *Service) Refresh(ctx context.Context, refresh string) (RefreshResult, bool, error)
- func (s *Service) RevokeAllSessions(ctx context.Context, userID string) error
- func (s *Service) RevokeSession(ctx context.Context, userID, sessionID string) (bool, error)
- func (s *Service) Sessions(ctx context.Context, userID string) ([]SessionInfo, error)
- type SessionCleaner
- type SessionInfo
- type SessionLister
- type TokenManager
- type Tokens
- type UserSessionCleaner
Constants ¶
This section is empty.
Variables ¶
var ( // ErrLockoutMissing reports a missing login lockout. // ErrLockoutMissing 表示缺少登录锁定器。 ErrLockoutMissing = errors.New("login lockout is required") // ErrLockoutKeyRequired reports an empty login lockout key. // ErrLockoutKeyRequired 表示缺少登录锁定 key。 ErrLockoutKeyRequired = errors.New("login lockout key is required") // ErrLoginLocked reports a locked login key. // ErrLoginLocked 表示登录 key 已锁定。 ErrLoginLocked = errors.New("login locked") )
var ( // ErrStaticPasswordUserIDEmpty reports an empty user ID for static password auth. // ErrStaticPasswordUserIDEmpty 表示固定密码认证使用了空 user ID。 ErrStaticPasswordUserIDEmpty = errors.New("static password user id is required") // ErrPasswordEmpty reports an empty password. // ErrPasswordEmpty 表示密码为空。 ErrPasswordEmpty = errors.New("password is empty") // ErrPasswordContainsSpace reports whitespace in a static password. // ErrPasswordContainsSpace 表示固定密码中包含空白字符。 ErrPasswordContainsSpace = errors.New("password must not contain whitespace") // ErrPasswordInvalidCharacter reports a character outside visible ASCII. // ErrPasswordInvalidCharacter 表示存在可见 ASCII 之外的字符。 ErrPasswordInvalidCharacter = errors.New("password must contain only ASCII letters, digits, and common symbols") )
var ( // ErrServiceMisconfigured reports missing Service dependencies. // ErrServiceMisconfigured 表示 Service 缺少依赖。 ErrServiceMisconfigured = errors.New("auth service is misconfigured") // ErrTokenManagerMissing reports a missing token manager. // ErrTokenManagerMissing 表示缺少 token manager。 ErrTokenManagerMissing = errors.New("token manager is required") // ErrLoginAuthenticatorMissing reports a missing login authenticator. // ErrLoginAuthenticatorMissing 表示缺少登录校验器。 ErrLoginAuthenticatorMissing = errors.New("login authenticator is required") // ErrUserIDEmpty reports a successful login without a user ID. // ErrUserIDEmpty 表示登录成功但缺少 user ID。 ErrUserIDEmpty = errors.New("authenticated user id is required") )
var ErrSessionClearUnsupported = authjwt.ErrSessionClearUnsupported
ErrSessionClearUnsupported reports a manager that cannot clear sessions. ErrSessionClearUnsupported 表示 manager 不支持清理 session。
var ErrSessionListUnsupported = authjwt.ErrSessionListUnsupported
ErrSessionListUnsupported reports a manager that cannot list sessions. ErrSessionListUnsupported 表示 manager 不支持列出 session。
Functions ¶
func ValidateStaticPassword ¶ added in v0.1.8
ValidateStaticPassword validates a static password using visible ASCII only. ValidateStaticPassword 使用仅可见 ASCII 规则校验静态密码。
func VerifyCredential ¶
VerifyCredential compares two credential strings using an exact byte match. VerifyCredential 使用精确字节匹配比较两段凭据。
Types ¶
type AccessTokenValidator ¶ added in v0.1.5
type AccessTokenValidator interface {
ValidateAccessToken(ctx context.Context, token string) (authjwt.Claims, bool, error)
}
AccessTokenValidator validates access tokens. AccessTokenValidator 校验 access token。
type IssueOptions ¶ added in v0.1.3
type IssueOptions = authjwt.IssueOptions
IssueOptions controls token issuance behavior. IssueOptions 控制 token 签发行为。
type LockedError ¶ added in v0.2.6
LockedError carries the lockout expiration for ErrLoginLocked. LockedError 携带 ErrLoginLocked 的锁定过期时间。
func (LockedError) Error ¶ added in v0.2.6
func (e LockedError) Error() string
func (LockedError) Is ¶ added in v0.2.6
func (e LockedError) Is(target error) bool
Is reports whether target is ErrLoginLocked. Is 返回 target 是否为 ErrLoginLocked。
type Lockout ¶ added in v0.2.6
type Lockout interface {
Check(ctx context.Context, key string) (until time.Time, locked bool, err error)
RecordFailure(ctx context.Context, key string) (until time.Time, locked bool, err error)
Clear(ctx context.Context, key string) error
}
Lockout tracks failed login attempts for a caller-provided non-empty key. Empty keys should return ErrLockoutKeyRequired. RecordFailure must report an active lock without resetting or extending it. Lockout 跟踪调用方提供的非空 key 的失败登录尝试。 空 key 应返回 ErrLockoutKeyRequired。 RecordFailure 必须返回已有且未到期的锁定,不得重置或延长它。
type LoginAuthenticator ¶
type LoginAuthenticator interface {
Authenticate(ctx context.Context, username, password string) (userID string, ok bool, err error)
}
LoginAuthenticator verifies login credentials. Implementations may ignore username. LoginAuthenticator 校验登录凭据。 实现可以忽略 username。
func NewStaticPassword ¶ added in v0.1.8
func NewStaticPassword(userID, expectedPassword string) (LoginAuthenticator, error)
NewStaticPassword builds a LoginAuthenticator backed by one fixed password. NewStaticPassword 构造一个使用固定密码的 LoginAuthenticator。
type LoginAuthenticatorFunc ¶
type LoginAuthenticatorFunc func(ctx context.Context, username, password string) (userID string, ok bool, err error)
LoginAuthenticatorFunc adapts a function to LoginAuthenticator. LoginAuthenticatorFunc 将函数适配为 LoginAuthenticator。
func (LoginAuthenticatorFunc) Authenticate ¶ added in v0.1.8
type MemoryLockout ¶ added in v0.2.6
type MemoryLockout struct {
// contains filtered or unexported fields
}
MemoryLockout tracks login failures in memory. It stores fixed-size hashes of caller-provided keys. Use NewMemoryLockout to create it; the zero value is not ready for use. MemoryLockout 在内存中跟踪登录失败。 它存储调用方提供 key 的固定长度 hash。 使用 NewMemoryLockout 创建;零值不可直接使用。
func NewMemoryLockout ¶ added in v0.2.6
func NewMemoryLockout(opts MemoryLockoutOptions) *MemoryLockout
NewMemoryLockout returns an in-memory Lockout. NewMemoryLockout 返回内存版 Lockout。
func (*MemoryLockout) Check ¶ added in v0.2.6
Check reports whether key is currently locked. Empty key returns ErrLockoutKeyRequired. Check 返回 key 当前是否已锁定。 空 key 返回 ErrLockoutKeyRequired。
func (*MemoryLockout) Clear ¶ added in v0.2.6
func (l *MemoryLockout) Clear(ctx context.Context, key string) error
Clear removes key from the lockout state. Empty key returns ErrLockoutKeyRequired. Clear 从锁定状态中移除 key。 空 key 返回 ErrLockoutKeyRequired。
func (*MemoryLockout) RecordFailure ¶ added in v0.2.6
RecordFailure records a failed attempt and reports whether it locked key. An active lock keeps its original expiration regardless of the failure window. Empty key returns ErrLockoutKeyRequired. RecordFailure 记录一次失败尝试并返回 key 是否被锁定。 已生效的锁定保持原过期时间,不受失败统计窗口影响。 空 key 返回 ErrLockoutKeyRequired。
type MemoryLockoutOptions ¶ added in v0.2.6
type MemoryLockoutOptions struct {
MaxFailures int
Window time.Duration
Lockout time.Duration
MaxKeys int
Now func() time.Time
}
MemoryLockoutOptions configures NewMemoryLockout. MemoryLockoutOptions 配置 NewMemoryLockout。
type Principal ¶ added in v0.2.4
type Principal struct {
Subject string `json:"subject"`
Username string `json:"username,omitempty"`
Role string `json:"role,omitempty"`
Scopes []string `json:"scopes,omitempty"`
Kind PrincipalKind `json:"kind"`
}
Principal is the authenticated subject attached to request contexts. Scopes is owned by the Principal value and is copied when stored. Principal 是写入请求 context 的已认证主体。 Scopes 归 Principal 值所有,写入时会复制。
func PrincipalFromContext ¶ added in v0.2.4
PrincipalFromContext returns the Principal stored by WithPrincipal. PrincipalFromContext 返回 WithPrincipal 写入的 Principal。
type PrincipalKind ¶ added in v0.2.4
type PrincipalKind string
PrincipalKind describes the authenticated subject type. PrincipalKind 描述已认证主体类型。
const ( // PrincipalKindUser identifies a user session. // PrincipalKindUser 表示用户 session。 PrincipalKindUser PrincipalKind = "user" // PrincipalKindAPIToken identifies an API token. // PrincipalKindAPIToken 表示 API token。 PrincipalKindAPIToken PrincipalKind = "api_token" )
type RefreshResult ¶ added in v0.1.3
type RefreshResult = authjwt.RefreshResult
RefreshResult carries refreshed tokens. RefreshResult 保存刷新后的 token。
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service runs authentication flows without transport code. Service 执行与传输层无关的认证流程。
func New ¶
func New(auth TokenManager, login LoginAuthenticator) (*Service, error)
New returns a Service. Call New(tokenManager, loginAuthenticator). New 返回 Service。 调用 New(tokenManager, loginAuthenticator)。
func (*Service) ClearAllSessions ¶ added in v0.1.9
ClearAllSessions removes all stored sessions. Callers must restrict this operation to trusted operators. ClearAllSessions 清理全部已保存的 session。 调用方必须限制可信操作方才能执行该操作。
func (*Service) ClearUserSessions ¶ added in v0.1.9
ClearUserSessions revokes and removes stored sessions for userID. Callers must authorize userID before calling. ClearUserSessions 吊销并清理 userID 已保存的 session。 调用方必须在调用前完成 userID 授权。
func (*Service) Login ¶
func (s *Service) Login(ctx context.Context, username, password string, opts IssueOptions) (Tokens, bool, error)
Login verifies credentials and issues tokens. ok reports whether the credentials were accepted. Login 校验凭据并签发 token。 ok 表示凭据是否通过校验。
func (*Service) Refresh ¶
Refresh rotates a refresh token. ok reports whether the refresh token was accepted. Refresh 轮换 refresh token。 ok 表示 refresh token 是否通过校验。
func (*Service) RevokeAllSessions ¶
RevokeAllSessions revokes all sessions for userID. RevokeAllSessions 吊销 userID 的全部 session。
func (*Service) RevokeSession ¶
RevokeSession revokes one session. ok reports whether the session belonged to userID. RevokeSession 吊销一个 session。 ok 表示该 session 是否属于 userID。
type SessionCleaner ¶ added in v0.1.9
SessionCleaner removes all stored sessions. Callers must restrict this operation to trusted operators. SessionCleaner 清理全部已保存的 session。 调用方必须限制可信操作方才能执行该操作。
type SessionInfo ¶ added in v0.1.9
type SessionInfo = authjwt.SessionInfo
SessionInfo is public session metadata for a user. SessionInfo 是用户可见的 session 元数据。
type SessionLister ¶ added in v0.1.9
type SessionLister interface {
Sessions(ctx context.Context, userID string) ([]SessionInfo, error)
}
SessionLister lists stored sessions for one user. SessionLister 列出单个用户已保存的 session。
type TokenManager ¶
type TokenManager interface {
AccessTokenValidator
IssueSessionTokens(ctx context.Context, userID string, opts IssueOptions) (access string, accessExp time.Time, refresh string, refreshExp time.Time, err error)
RotateRefreshTokens(ctx context.Context, oldRefresh string) (RefreshResult, bool, error)
RevokeRefresh(ctx context.Context, refresh string) error
RevokeSession(ctx context.Context, userID, sessionID string) (bool, error)
RevokeAllSessions(ctx context.Context, userID string) error
}
TokenManager provides token and session operations for Service. TokenManager 为 Service 提供 token 与 session 操作。
Directories
¶
| Path | Synopsis |
|---|---|
|
Package jwt provides JWT issuance and validation backed by user/session state.
|
Package jwt provides JWT issuance and validation backed by user/session state. |
|
Package rbac provides role and scope based authentication primitives.
|
Package rbac provides role and scope based authentication primitives. |
|
Package session provides cookie helpers for auth flows.
|
Package session provides cookie helpers for auth flows. |
|
Package store defines auth session persistence used by auth/jwt.
|
Package store defines auth session persistence used by auth/jwt. |
|
redissession
Package redissession provides Redis-backed auth session storage.
|
Package redissession provides Redis-backed auth session storage. |