ZBLOG

go-zero 实现jwt 校验token 的api接口 包含api文件

使用 go-zero 实现 JWT 校验的 API 接口可以参考以下步骤。假设你已经安装了 go-zero 和相关依赖。

1. 安装依赖

首先,你需要确保你的项目中已安装 JWT 库,可以使用如下命令:

  1. go get github.com/dgrijalva/jwt-go

2. 创建 API 文件结构

假设我们创建一个简单的 JWT 验证接口,目录结构如下:

  1. your_project/
  2. ├── api/
  3. └── auth.api
  4. ├── handler/
  5. └── auth_handler.go
  6. ├── logic/
  7. └── auth_logic.go
  8. ├── model/
  9. └── user.go
  10. └── main.go

3. 定义 API 接口

api/auth.api 文件中定义我们的接口:

  1. syntax = "proto3";
  2. package auth;
  3. service Auth {
  4. rpc ValidateToken(ValidateTokenRequest) returns (ValidateTokenResponse);
  5. }
  6. message ValidateTokenRequest {
  7. string token = 1;
  8. }
  9. message ValidateTokenResponse {
  10. bool valid = 1;
  11. string message = 2;
  12. }

4. 生成代码

在项目根目录下运行以下命令生成对应的代码:

  1. goctl rpc proto -src api/auth.api -dir .

5. 实现逻辑

接下来,在 logic/auth_logic.go 中实现 JWT 校验逻辑:

  1. package logic
  2. import (
  3. "context"
  4. "github.com/dgrijalva/jwt-go"
  5. "your_project/rpc/auth/internal/svc"
  6. "your_project/rpc/auth/types"
  7. )
  8. type AuthLogic struct {
  9. ctx context.Context
  10. svcCtx *svc.ServiceContext
  11. }
  12. func NewAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AuthLogic {
  13. return &AuthLogic{
  14. ctx: ctx,
  15. svcCtx: svcCtx,
  16. }
  17. }
  18. func (l *AuthLogic) ValidateToken(req *types.ValidateTokenRequest) (*types.ValidateTokenResponse, error) {
  19. tokenStr := req.Token
  20. // Parse the token
  21. token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
  22. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  23. return nil, ErrInvalidSigningMethod
  24. }
  25. return []byte("your-secret-key"), nil // 使用你的密钥进行验证
  26. })
  27. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
  28. // Token 有效,可以添加更多业务逻辑,例如角色检查等。
  29. return &types.ValidateTokenResponse{Valid: true, Message: "Token is valid"}, nil
  30. } else {
  31. return &types.ValidateTokenResponse{Valid: false, Message: err.Error()}, nil // 返回错误信息
  32. }
  33. }

6. 实现 Handler

handler/auth_handler.go 中定义处理请求的函数:

  1. package handler
  2. import (
  3. "net/http"
  4. "github.com/zeromicro/go-zero/rest/httpx"
  5. "your_project/rpc/auth/internal/logic"
  6. "your_project/rpc/auth/internal/svc"
  7. "your_project/rpc/auth/types"
  8. )
  9. func ValidateTokenHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
  10. return func(w http.ResponseWriter, r *http.Request) {
  11. var req types.ValidateTokenRequest
  12. if err := httpx.Parse(r, &req); err != nil {
  13. httpx.Error(w, err)
  14. return
  15. }
  16. l := logic.NewAuthLogic(r.Context(), svcCtx)
  17. resp, err := l.ValidateToken(&req)
  18. if err != nil {
  19. httpx.Error(w, err)
  20. return
  21. }
  22. httpx.OkJson(w, resp)
  23. }
  24. }

7. 启动服务

最后,在 main.go 中启动 HTTP 服务并注册路由:

  1. package main
  2. import (
  3. "fmt"
  4. logic "your_project/rpc/auth/internal/logic"
  5. svc "your_project/rpc/auth/internal/svc"
  6. "github.com/zeromicro/go-zero/rest"
  7. )
  8. func main() {
  9. c := rest.RestConf{
  10. Port: 8080,
  11. // ... other configurations ...
  12. }
  13. srv := rest.MustNewServer(c)
  14. defer srv.Stop()
  15. ctx := svc.NewServiceContext()
  16. srv.AddRoute(rest.Route{
  17. Method: http.MethodPost,
  18. Path: "/auth/validate",
  19. Handler: handler.ValidateTokenHandler(ctx),
  20. })
  21. fmt.Println("Starting server at port", c.Port)
  22. srv.Start()
  23. }

总结

以上就是使用 go-zero 框架实现一个简单的 JWT 校验接口的基本步骤。确保用你自己的密钥替换 "your-secret-key" 并根据需要调整代码。如果有任何问题或需进一步定制功能,请随时询问!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=22320

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?