You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.3 KiB

  1. package middleware
  2. import (
  3. "github.com/flipped-aurora/gin-vue-admin/server/config"
  4. "github.com/flipped-aurora/gin-vue-admin/server/global"
  5. "github.com/gin-gonic/gin"
  6. "net/http"
  7. )
  8. // Cors 直接放行所有跨域请求并放行所有 OPTIONS 方法
  9. func Cors() gin.HandlerFunc {
  10. return func(c *gin.Context) {
  11. method := c.Request.Method
  12. origin := c.Request.Header.Get("Origin")
  13. c.Header("Access-Control-Allow-Origin", origin)
  14. c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
  15. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
  16. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
  17. c.Header("Access-Control-Allow-Credentials", "true")
  18. // 放行所有OPTIONS方法
  19. if method == "OPTIONS" {
  20. c.AbortWithStatus(http.StatusNoContent)
  21. }
  22. // 处理请求
  23. c.Next()
  24. }
  25. }
  26. // CorsByRules 按照配置处理跨域请求
  27. func CorsByRules() gin.HandlerFunc {
  28. // 放行全部
  29. if global.GVA_CONFIG.Cors.Mode == "allow-all" {
  30. return Cors()
  31. }
  32. return func(c *gin.Context) {
  33. whitelist := checkCors(c.GetHeader("origin"))
  34. // 通过检查, 添加请求头
  35. if whitelist != nil {
  36. c.Header("Access-Control-Allow-Origin", whitelist.AllowOrigin)
  37. c.Header("Access-Control-Allow-Headers", whitelist.AllowHeaders)
  38. c.Header("Access-Control-Allow-Methods", whitelist.AllowMethods)
  39. c.Header("Access-Control-Expose-Headers", whitelist.ExposeHeaders)
  40. if whitelist.AllowCredentials {
  41. c.Header("Access-Control-Allow-Credentials", "true")
  42. }
  43. }
  44. // 严格白名单模式且未通过检查,直接拒绝处理请求
  45. if whitelist == nil && global.GVA_CONFIG.Cors.Mode == "strict-whitelist" && !(c.Request.Method == "GET" && c.Request.URL.Path == "/health") {
  46. c.AbortWithStatus(http.StatusForbidden)
  47. } else {
  48. // 非严格白名单模式,无论是否通过检查均放行所有 OPTIONS 方法
  49. if c.Request.Method == "OPTIONS" {
  50. c.AbortWithStatus(http.StatusNoContent)
  51. }
  52. }
  53. // 处理请求
  54. c.Next()
  55. }
  56. }
  57. func checkCors(currentOrigin string) *config.CORSWhitelist {
  58. for _, whitelist := range global.GVA_CONFIG.Cors.Whitelist {
  59. // 遍历配置中的跨域头,寻找匹配项
  60. if currentOrigin == whitelist.AllowOrigin {
  61. return &whitelist
  62. }
  63. }
  64. return nil
  65. }