auth_middleware.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. "/apiv1/recommend_question",
  18. }
  19. // AuthMiddleware Token认证中间件
  20. func AuthMiddleware(ctx *context.Context) {
  21. path := ctx.Request.URL.Path
  22. // 跳过根路径
  23. if path == "/" {
  24. return
  25. }
  26. // 检查跳过路径
  27. for _, skip := range skipPaths {
  28. if path == skip || strings.HasPrefix(path, skip) {
  29. return
  30. }
  31. }
  32. // 仅对API请求验证token
  33. if !strings.HasPrefix(path, "/apiv1") {
  34. return
  35. }
  36. // 提取token
  37. token := extractToken(ctx)
  38. if token == "" {
  39. ctx.Output.SetStatus(401)
  40. ctx.Output.JSON(map[string]interface{}{
  41. "statusCode": 401,
  42. "msg": "未提供认证token",
  43. }, false, false)
  44. return
  45. }
  46. // 优先验证本地token
  47. if localClaims, err := VerifyLocalToken(token); err == nil && localClaims != nil {
  48. ctx.Input.SetData("userInfo", ConvertLocalClaimsToTokenUserInfo(localClaims))
  49. return
  50. }
  51. // 统一认证token验证
  52. userInfo, err := VerifyToken(token)
  53. if err != nil {
  54. ctx.Output.SetStatus(401)
  55. ctx.Output.JSON(map[string]interface{}{
  56. "statusCode": 401,
  57. "msg": fmt.Sprintf("token验证失败: %v", err),
  58. }, false, false)
  59. return
  60. }
  61. ctx.Input.SetData("userInfo", userInfo)
  62. }
  63. // extractToken 从请求头提取token
  64. func extractToken(ctx *context.Context) string {
  65. token := ctx.Input.Header("token")
  66. if token == "" {
  67. token = ctx.Input.Header("Token")
  68. }
  69. if token == "" {
  70. token = ctx.Input.Header("Authorization")
  71. if strings.HasPrefix(token, "Bearer ") {
  72. token = token[7:]
  73. }
  74. }
  75. return token
  76. }