go-zero 框架通过 jwtmiddleware 中间件实现 jwt 权限校验,核心做法是在 goctl 生成的代码中配置 auth 字段并注入自定义的 tokensuccesshandler。该流程会自动拦截请求、解析 header 中的 token,验证通过后调用处理函数将用户信息存入 context,随后执行业务逻辑;若验证失败则直接返回 http 401 错误,无需在业务代码中手动判断。

如何配置 JWT 中间件以启用鉴权?
在 api 文件中声明 Auth 字段即可开启鉴权,框架会自动生成对应的中间件逻辑。开发者需要提供一个 TokenSuccessHandler 来定义验证成功后的行为,通常是将解析出的用户 ID 放入 Context 供后续服务使用。这一步决定了鉴权的入口和上下文数据的传递方式。

package main
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/rest/httpx"
)
type Config struct {
rest.RestConf
Auth struct {
AccessSecret string `json:"AccessSecret"`
AccessExpire int64 `json:"AccessExpire"`
}
}
func main() {
var c Config
// 假设已从配置文件加载 c
server := rest.MustNewServer(c.RestConf, rest.WithJwt(c.Auth.AccessSecret))
defer server.Stop()
// 注册路由
server.AddRoutes([]rest.Route{
{
Method: http.MethodGet,
Path: "/secure",
Handler: secureHandler(c),
Jwt: true, // 关键:在此路由启用 JWT
},
})
server.Start()
}
func secureHandler(c Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 获取 Context 中的 userId
ctx := r.Context()
userId := jwt.GetUserId(ctx)
logx.Info("User ID:", userId)
httpx.OkJson(w, map[string]interface{}{"userId": userId})
}
}
Token 验证失败或过期时如何处理?
当 Token 无效、签名错误或已过期时,go-zero 内置的中间件会拦截请求并直接返回 HTTP 401 Unauthorized 状态码及错误信息。此时不会进入任何业务 Handler。可以通过实现 TokenErrorHandler 来自定义返回的错误格式,例如记录日志或返回更友好的 JSON 结构,但默认行为已足够应对大多数场景。

package main
import (
"encoding/json"
"net/http"
"github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/rest/httpx"
)
// CustomError 定义自定义错误响应结构
type CustomError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func main() {
var c Config
server := rest.MustNewServer(c.RestConf, rest.WithJwt(c.Auth.AccessSecret))
defer server.Stop()
// 设置自定义错误处理器
server.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 这里可以添加全局错误捕获,但 JWT 错误通常在中间件层处理
h.ServeHTTP(w, r)
})
})
// 或者在 WithJwt 选项中传入自定义 handler (需根据具体版本 API 调整)
// 通常 go-zero 的 jwt middleware 允许传入 OnDenied 回调
server.AddRoutes([]rest.Route{
{
Method: http.MethodGet,
Path: "/public",
Handler: publicHandler,
},
})
server.Start()
}
func publicHandler(w http.ResponseWriter, r *http.Request) {
httpx.OkJson(w, map[string]string{"status": "ok"})
}
Context 中存储的用户信息是如何获取的?
在 TokenSuccessHandler 执行完毕后,解析出的用户标识(如 userId)会被存储在 context.Context 中。在后续的 Handler 或 Service 层,可以通过 jwt.GetUserId(r.Context()) 方法安全地提取该值。如果未设置或提取失败,该方法会返回一个默认零值(通常是空字符串或 0),因此建议在业务逻辑中对获取到的 ID 进行非空校验,以确保数据完整性。











