feat(server): CORS 中间件(白名单跨域,支持用户中心/官网前端)
控制面无 CORS 导致 pangolin.yanmeiai.com 的用户中心跨域打 api.yanmeiai.com 被浏览器拦(Network error)。 加白名单 CORS(env CORS_ALLOWED_ORIGINS,默认 https://pangolin.yanmeiai.com):回显 Origin、应答预检 OPTIONS、 放行 Authorization/Content-Type;不用 '*'、不放行 credentials(走 Bearer token)。
This commit is contained in:
@@ -123,6 +123,7 @@ func main() {
|
||||
r := chi.NewRouter()
|
||||
r.Use(chimw.Logger)
|
||||
r.Use(chimw.Recoverer)
|
||||
r.Use(corsMiddleware(corsAllowedOrigins()))
|
||||
r.Use(apierr.Middleware)
|
||||
|
||||
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -590,3 +591,40 @@ func (a authDeviceRegistrar) CheckDeviceLimit(ctx context.Context, userID int64)
|
||||
}
|
||||
return &auth.DeviceLimit{MaxDevices: st.MaxDevices, Devices: briefs}, nil
|
||||
}
|
||||
|
||||
// corsAllowedOrigins 从 env CORS_ALLOWED_ORIGINS(逗号分隔)读跨域白名单;默认放行官网/
|
||||
// 用户中心域。控制面走 Bearer token(无 cookie 会话),故不放行 credentials,只白名单回显 Origin。
|
||||
func corsAllowedOrigins() map[string]bool {
|
||||
raw := os.Getenv("CORS_ALLOWED_ORIGINS")
|
||||
if raw == "" {
|
||||
raw = "https://pangolin.yanmeiai.com"
|
||||
}
|
||||
out := map[string]bool{}
|
||||
for _, o := range strings.Split(raw, ",") {
|
||||
if o = strings.TrimSpace(o); o != "" {
|
||||
out[o] = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// corsMiddleware 按白名单回显 Access-Control-Allow-Origin 并应答预检 OPTIONS。只放行白名单内
|
||||
// Origin(不用 "*"),允许 Authorization/Content-Type 头。非白名单来源不加任何 CORS 头(浏览器自然拦)。
|
||||
func corsMiddleware(allowed map[string]bool) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if origin := r.Header.Get("Origin"); origin != "" && allowed[origin] {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Add("Vary", "Origin")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
|
||||
w.Header().Set("Access-Control-Max-Age", "600")
|
||||
}
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user