createCORSMiddleware creates middleware that handles CORS policies
(corsManager *CORSManager)
| 235 | |
| 236 | // createCORSMiddleware creates middleware that handles CORS policies |
| 237 | func createCORSMiddleware(corsManager *CORSManager) func(http.Handler) http.Handler { |
| 238 | return func(next http.Handler) http.Handler { |
| 239 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 240 | origin := r.Header.Get("Origin") |
| 241 | |
| 242 | // Handle preflight requests (OPTIONS method) |
| 243 | if r.Method == "OPTIONS" { |
| 244 | // Set secure CORS headers for preflight |
| 245 | w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") |
| 246 | w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-CSRF-Token") |
| 247 | w.Header().Set("Access-Control-Allow-Credentials", "false") // Secure default |
| 248 | w.Header().Set("Access-Control-Max-Age", "3600") // Cache preflight for 1 hour |
| 249 | |
| 250 | // Only set Access-Control-Allow-Origin if origin is allowed |
| 251 | if origin != "" && corsManager.IsOriginAllowed(origin) { |
| 252 | w.Header().Set("Access-Control-Allow-Origin", origin) |
| 253 | } |
| 254 | |
| 255 | w.WriteHeader(http.StatusNoContent) |
| 256 | return |
| 257 | } |
| 258 | |
| 259 | // For non-preflight requests, set CORS headers if origin is allowed |
| 260 | if origin != "" && corsManager.IsOriginAllowed(origin) { |
| 261 | w.Header().Set("Access-Control-Allow-Origin", origin) |
| 262 | w.Header().Set("Access-Control-Allow-Credentials", "false") // Secure default |
| 263 | } |
| 264 | |
| 265 | // Add security headers |
| 266 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 267 | w.Header().Set("X-Frame-Options", "DENY") |
| 268 | w.Header().Set("X-XSS-Protection", "1; mode=block") |
| 269 | |
| 270 | next.ServeHTTP(w, r) |
| 271 | }) |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | // Global CORS manager instance |
| 276 | var corsManager = NewCORSManager() |
no test coverage detected