jwt.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/golang-jwt/jwt/v4"
  5. "net/http"
  6. "newaterobot-process/utils"
  7. )
  8. // JWTAuthMiddleware JWT认证中间件
  9. func JWTAuthMiddleware() gin.HandlerFunc {
  10. return func(c *gin.Context) {
  11. if c.Keys == nil {
  12. c.Keys = make(map[string]any)
  13. }
  14. //判断
  15. var code int
  16. var data interface{}
  17. code = http.StatusOK
  18. //分别从Header和Query Param当中获取 jwt-token
  19. token := c.GetHeader("JWT-TOKEN")
  20. if token == "" {
  21. token = c.Query("JWT-TOKEN")
  22. }
  23. // session未中断
  24. if _, ok := c.Keys[utils.SessionUserIdKey]; ok {
  25. c.Next()
  26. }
  27. if token == "" {
  28. code = http.StatusUnauthorized
  29. data = "无法获取token参数"
  30. } else {
  31. claim, err := utils.ParseTokenWithDep(token)
  32. if err != nil {
  33. switch err.(*jwt.ValidationError).Errors {
  34. case jwt.ValidationErrorExpired:
  35. code = http.StatusUnauthorized
  36. default:
  37. code = http.StatusUnauthorized
  38. }
  39. }
  40. if code == http.StatusOK {
  41. c.Keys[utils.SessionUserIdKey] = claim.ID
  42. c.Keys[utils.SessionDepIdKey] = claim.Dep
  43. }
  44. }
  45. if code != http.StatusOK {
  46. c.JSON(http.StatusUnauthorized, gin.H{
  47. "code": code,
  48. "msg": "token 验证失败",
  49. "data": data,
  50. })
  51. c.Abort()
  52. return
  53. }
  54. c.Next()
  55. }
  56. }