auth.go 809 B

123456789101112131415161718192021222324
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "icloudapp.cn/tools/controller"
  5. "icloudapp.cn/tools/entity"
  6. )
  7. // JWTAuthMiddleware 基于JWT的认证中间件
  8. func AuthMiddleware() func(c *gin.Context) {
  9. return func(c *gin.Context) {
  10. // 客户端携带Token有三种方式 1.放在请求头 2.放在请求体 3.放在URI
  11. // token验证成功,返回c.Next继续,否则返回c.Abort()直接返回
  12. authHeader := c.Request.Header.Get("Authorization")
  13. if authHeader == "" {
  14. controller.ResponseError(c, entity.CodeNeedLogin)
  15. c.Abort()
  16. return
  17. }
  18. // 将当前请求的userID信息保存到请求的上下文c上
  19. //c.Set(controller.CtxUserIDKey, mc.UserID)
  20. c.Next() // 后续的处理请求的函数中 可以用过c.Get(CtxUserIDKey) 来获取当前请求的用户信息
  21. }
  22. }