使用 go-zero
实现 JWT 校验的 API 接口可以参考以下步骤。假设你已经安装了 go-zero
和相关依赖。
1. 安装依赖
首先,你需要确保你的项目中已安装 JWT 库,可以使用如下命令:
go get github.com/dgrijalva/jwt-go
2. 创建 API 文件结构
假设我们创建一个简单的 JWT 验证接口,目录结构如下:
your_project/
├── api/
│ └── auth.api
├── handler/
│ └── auth_handler.go
├── logic/
│ └── auth_logic.go
├── model/
│ └── user.go
└── main.go
3. 定义 API 接口
在 api/auth.api
文件中定义我们的接口:
syntax = "proto3";
package auth;
service Auth {
rpc ValidateToken(ValidateTokenRequest) returns (ValidateTokenResponse);
}
message ValidateTokenRequest {
string token = 1;
}
message ValidateTokenResponse {
bool valid = 1;
string message = 2;
}
4. 生成代码
在项目根目录下运行以下命令生成对应的代码:
goctl rpc proto -src api/auth.api -dir .
5. 实现逻辑
接下来,在 logic/auth_logic.go
中实现 JWT 校验逻辑:
package logic
import (
"context"
"github.com/dgrijalva/jwt-go"
"your_project/rpc/auth/internal/svc"
"your_project/rpc/auth/types"
)
type AuthLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AuthLogic {
return &AuthLogic{
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AuthLogic) ValidateToken(req *types.ValidateTokenRequest) (*types.ValidateTokenResponse, error) {
tokenStr := req.Token
// Parse the token
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, ErrInvalidSigningMethod
}
return []byte("your-secret-key"), nil // 使用你的密钥进行验证
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// Token 有效,可以添加更多业务逻辑,例如角色检查等。
return &types.ValidateTokenResponse{Valid: true, Message: "Token is valid"}, nil
} else {
return &types.ValidateTokenResponse{Valid: false, Message: err.Error()}, nil // 返回错误信息
}
}
6. 实现 Handler
在 handler/auth_handler.go
中定义处理请求的函数:
package handler
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"your_project/rpc/auth/internal/logic"
"your_project/rpc/auth/internal/svc"
"your_project/rpc/auth/types"
)
func ValidateTokenHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ValidateTokenRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.Error(w, err)
return
}
l := logic.NewAuthLogic(r.Context(), svcCtx)
resp, err := l.ValidateToken(&req)
if err != nil {
httpx.Error(w, err)
return
}
httpx.OkJson(w, resp)
}
}
7. 启动服务
最后,在 main.go
中启动 HTTP 服务并注册路由:
package main
import (
"fmt"
logic "your_project/rpc/auth/internal/logic"
svc "your_project/rpc/auth/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func main() {
c := rest.RestConf{
Port: 8080,
// ... other configurations ...
}
srv := rest.MustNewServer(c)
defer srv.Stop()
ctx := svc.NewServiceContext()
srv.AddRoute(rest.Route{
Method: http.MethodPost,
Path: "/auth/validate",
Handler: handler.ValidateTokenHandler(ctx),
})
fmt.Println("Starting server at port", c.Port)
srv.Start()
}
总结
以上就是使用 go-zero
框架实现一个简单的 JWT 校验接口的基本步骤。确保用你自己的密钥替换 "your-secret-key"
并根据需要调整代码。如果有任何问题或需进一步定制功能,请随时询问!
内容由零声教学AI助手提供,问题来源于学员提问