feat: add CORS filter to fix OPTION request failure (#826)

This commit is contained in:
aecra
2022-06-26 01:28:33 +08:00
committed by GitHub
parent 31b586e391
commit 7c9370ef90
3 changed files with 69 additions and 0 deletions

31
routers/cors_filter.go Normal file
View File

@ -0,0 +1,31 @@
package routers
import (
"net/http"
"github.com/astaxie/beego/context"
"github.com/casdoor/casdoor/object"
)
const (
headerOrigin = "Origin"
headerAllowOrigin = "Access-Control-Allow-Origin"
headerAllowMethods = "Access-Control-Allow-Methods"
headerAllowHeaders = "Access-Control-Allow-Headers"
)
func CorsFilter(ctx *context.Context) {
if ctx.Input.Method() == "OPTIONS" {
origin := ctx.Input.Header(headerOrigin)
if object.IsAllowOrigin(origin) {
ctx.Output.Header(headerAllowOrigin, origin)
ctx.Output.Header(headerAllowMethods, "POST, GET, OPTIONS")
ctx.Output.Header(headerAllowHeaders, "Content-Type, Authorization")
ctx.ResponseWriter.WriteHeader(http.StatusOK)
} else {
ctx.ResponseWriter.WriteHeader(http.StatusForbidden)
}
return
}
}