auth_middleware.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package utils
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/beego/beego/v2/server/web/context"
  6. )
  7. // 不需要认证的路径
  8. var skipPaths = []string{
  9. "/stream-test",
  10. "/simple-stream-test",
  11. "/stream-chat-with-db-test",
  12. "/assets/",
  13. "/static/",
  14. "/src/",
  15. "/apiv1/oss/parse",
  16. "/apiv1/auth/local_login",
  17. }
  18. // AuthMiddleware Token认证中间件
  19. func AuthMiddleware(ctx *context.Context) {
  20. path := ctx.Request.URL.Path
  21. // 跳过根路径
  22. if path == "/" {
  23. return
  24. }
  25. // 检查跳过路径
  26. for _, skip := range skipPaths {
  27. if path == skip || strings.HasPrefix(path, skip) {
  28. return
  29. }
  30. }
  31. // 仅对API请求验证token
  32. if !strings.HasPrefix(path, "/apiv1") {
  33. return
  34. }
  35. // 提取token
  36. token := extractToken(ctx)
  37. if token == "" {
  38. ctx.Output.SetStatus(401)
  39. ctx.Output.JSON(map[string]interface{}{
  40. "statusCode": 401,
  41. "msg": "未提供认证token",
  42. }, false, false)
  43. return
  44. }
  45. // 优先验证本地token
  46. if localClaims, err := VerifyLocalToken(token); err == nil && localClaims != nil {
  47. ctx.Input.SetData("userInfo", ConvertLocalClaimsToTokenUserInfo(localClaims))
  48. return
  49. }
  50. // 统一认证token验证
  51. userInfo, err := VerifyToken(token)
  52. if err != nil {
  53. ctx.Output.SetStatus(401)
  54. ctx.Output.JSON(map[string]interface{}{
  55. "statusCode": 401,
  56. "msg": fmt.Sprintf("token验证失败: %v", err),
  57. }, false, false)
  58. return
  59. }
  60. ctx.Input.SetData("userInfo", userInfo)
  61. }
  62. // extractToken 从请求头提取token
  63. func extractToken(ctx *context.Context) string {
  64. token := ctx.Input.Header("token")
  65. if token == "" {
  66. token = ctx.Input.Header("Token")
  67. }
  68. if token == "" {
  69. token = ctx.Input.Header("Authorization")
  70. if strings.HasPrefix(token, "Bearer ") {
  71. token = token[7:]
  72. }
  73. }
  74. return token
  75. }