feat: bootstrap reusable GoOmni framework
This commit is contained in:
36
auth/README.md
Normal file
36
auth/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# auth
|
||||
|
||||
`auth` 只定义身份和权限边界,不把 JWT、Session、OAuth 或某个用户表绑定到核心框架。
|
||||
|
||||
## 核心用法
|
||||
|
||||
认证器把外部凭据转换成通用身份:
|
||||
|
||||
```go
|
||||
type Authenticator interface {
|
||||
Authenticate(context.Context, string) (Principal, error)
|
||||
}
|
||||
```
|
||||
|
||||
把认证放在路由组上:
|
||||
|
||||
```go
|
||||
private := app.Group("/api", auth.RequireAuth(authenticator))
|
||||
private.GET("/me", getMe)
|
||||
|
||||
admin := private.Group("/admin", auth.RequireRole("admin"))
|
||||
admin.POST("/users", createUser)
|
||||
```
|
||||
|
||||
Handler 可以读取身份,但不需要知道 Token 的格式:
|
||||
|
||||
```go
|
||||
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`。
|
||||
Reference in New Issue
Block a user