为什么注册都返回403
zhang14725804 opened this issue · 3 comments
zhang14725804 commented
| 403 | 0s | ::1 | POST /api/v1/user/register
zhang14725804 commented
zhang14725804 commented
func NewRouter() *gin.Engine {
r := gin.Default()
// 中间件, 顺序不能改
r.Use(middleware.Session(os.Getenv("SESSION_SECRET")))
r.Use(middleware.Cors())
r.Use(middleware.CurrentUser())
// 路由
v1 := r.Group("/api/v1")
{
v1.POST("ping", api.Ping)
// 用户登录
v1.POST("user/register", api.UserRegister)
// 用户登录
v1.POST("user/login", api.UserLogin)
// 需要登录保护的
auth := v1.Group("")
//auth.Use(middleware.AuthRequired())
{
// User Routing
auth.GET("user/me", api.UserMe)
auth.DELETE("user/logout", api.UserLogout)
}
}
return r
}
williammyuan commented
看下middleware下面的代码
把测试环境下的匹配返回改为true就行了。如下
func Cors() gin.HandlerFunc {
config := cors.DefaultConfig()
config.AllowMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
config.AllowHeaders = []string{"Origin", "Content-Length", "Content-Type", "Cookie"}
if gin.Mode() == gin.ReleaseMode {
// 生产环境需要配置跨域域名,否则403
config.AllowOrigins = []string{"http://www.example.com"}
} else {
// 测试环境下模糊匹配本地开头的请求
config.AllowOriginFunc = func(origin string) bool {
if regexp.MustCompile(`^http://127\.0\.0\.1:\d+$`).MatchString(origin) {
return true
}
if regexp.MustCompile(`^http://localhost:\d+$`).MatchString(origin) {
return true
}
return true
}
}
config.AllowCredentials = true
return cors.New(config)
}