Files
go-omni/auth/README.md

1.1 KiB

auth

auth 只定义身份和权限边界,不把 JWT、Session、OAuth 或某个用户表绑定到核心框架。

核心用法

认证器把外部凭据转换成通用身份:

type Authenticator interface {
    Authenticate(context.Context, string) (Principal, error)
}

把认证放在路由组上:

private := app.Group("/api", auth.RequireAuth(authenticator))
private.GET("/me", getMe)

admin := private.Group("/admin", auth.RequireRole("admin"))
admin.POST("/users", createUser)

Handler 可以读取身份,但不需要知道 Token 的格式:

principal, ok := auth.FromContext(ctx)
if !ok {
    return omni.Unauthorized("UNAUTHENTICATED", "authentication is required")
}

认证失败统一返回 401 UNAUTHENTICATED,身份存在但角色不满足统一返回 403 FORBIDDEN。无效 Token 的详细原因保留在错误链中,不出现在 HTTP 响应里。

StaticAuthenticator 只用于本地开发和测试,不能作为生产认证方案。生产项目实现 Authenticator,在实现内部校验 JWT、Session 或其他凭据,并返回 Principal。