在 Go-Zero 中实现 JWT 校验的 API 接口组,可以通过以下步骤进行设置。下面将提供一个完整的示例,演示如何创建带有 JWT 校验的 API 接口。
1. 安装依赖
确保你已经安装了 go-zero
和 jwt-go
库:
go get github.com/zeromicro/go-zero
go get github.com/dgrijalva/jwt-go
2. 创建 JWT 中间件
首先,我们需要创建一个中间件来处理 JWT 的验证逻辑。
// middleware/jwt.go
package middleware
import (
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
)
var jwtSecret = []byte("your_secret_key") // 替换为你的密钥
func JwtMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("Authorization")
if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
tokenString = strings.TrimPrefix(tokenString, "Bearer ")
claims := &jwt.StandardClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil || !token.Valid {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// 可以根据需要将用户信息添加到上下文中,这里仅作为示例
ctx := r.Context()
ctx = context.WithValue(ctx, "userID", claims.Subject)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
3. 创建 API 接口和路由
然后我们可以定义一些接口并应用上面的 JWT 中间件。
// main.go
package main
import (
"net/http"
"github.com/gorilla/mux"
"your_project_path/middleware" // 修改为实际路径
)
func main() {
r := mux.NewRouter()
// 定义受保护的路由,并应用JWT中间件
r.Handle("/api/protected", middleware.JwtMiddleware(http.HandlerFunc(protectedHandler))).Methods("GET")
// 启动HTTP服务器
http.ListenAndServe(":8080", r)
}
func protectedHandler(w http.ResponseWriter, r *http.Request) {
userID := r.Context().Value("userID") // 从上下文获取用户信息(如果有的话)
w.Write([]byte("This is a protected route for user ID: " + userID.(string)))
}
4. 生成和签发 JWT Token 的函数(可选)
你可能还想要一个函数来生成和返回有效的 JWT Token,以便进行身份验证。这可以在你需要登录的地方调用:
// auth.go
package auth
import (
"time"
"github.com/dgrijalva/jwt-go"
)
var jwtSecret = []byte("your_secret_key") // 替换为你的密钥
func GenerateToken(userID string) (string, error) {
expirationTime := time.Now().Add(24 * time.Hour)
clams := &jwt.StandardClaims{
Subject: userID,
ExpiresAt: expirationTime.Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, clams)
return token.SignedString(jwtSecret)
}
5. 使用 Postman 或 Curl 测试接口
登录并获取 Token 示例:
假设你已经实现了用户登录并生成了 Token,你可以使用如下方式测试获取 Token:
curl -X POST -d '{"username": "test", "password": "password"}' -H 'Content-Type: application/json' http://localhost:8080/api/login
这将返回一个有效的 Bearer Token。
调用受保护的接口:
curl -H "Authorization: Bearer your_jwt_token" http://localhost:8080/api/protected
如果 token 有效,你会看到类似于 "This is a protected route for user ID: ..."
的响应。
注意事项:
- 安全性:请勿将敏感信息(如 secret key)硬编码在代码中,建议使用环境变量。
- 错误处理:生产代码应包含详细的错误处理机制,以帮助调试和追踪问题。
- Token管理:可以考虑实现 Token 刷新、失效等功能,根据业务需求增加更多功能。
这样,你就成功地在 Go-Zero 框架中实现了带有 JWT 校验的 API 接口。如果有任何疑问或其他需求,请随时询问!
内容由零声教学AI助手提供,问题来源于学员提问