Fix: Add Secure attribute to session cookie for HTTPS deployments

Co-authored-by: hsluoyz <3787410+hsluoyz@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2026-03-18 09:51:34 +00:00
parent 602e82cf62
commit dad7de87fa
3 changed files with 59 additions and 0 deletions

View File

@@ -23,6 +23,7 @@ isDemoMode = false
batchSize = 100
enableErrorMask = false
enableGzip = true
cookieSecure = false
inactiveTimeoutMinutes =
ldapServerPort = 389
ldapsCertId = ""

View File

@@ -99,6 +99,7 @@ func main() {
web.InsertFilter("*", web.BeforeRouter, routers.RecordMessage)
web.InsertFilter("*", web.BeforeRouter, routers.FieldValidationFilter)
web.InsertFilter("*", web.AfterExec, routers.AfterRecordMessage, web.WithReturnOnOutput(false))
web.InsertFilter("*", web.AfterExec, routers.SecureCookieFilter, web.WithReturnOnOutput(false))
var logAdapter string
logConfigMap := make(map[string]interface{})

57
routers/secure_filter.go Normal file
View File

@@ -0,0 +1,57 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package routers
import (
"strings"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
"github.com/casdoor/casdoor/conf"
)
// SecureCookieFilter adds the "Secure" attribute to the session cookie when the
// deployment is configured to use HTTPS. This is determined by either the
// "cookieSecure" config option being set to true, or the "origin" config starting
// with "https://". This approach ensures the Secure flag is set even when Casdoor
// runs behind a TLS-terminating reverse proxy.
func SecureCookieFilter(ctx *context.Context) {
if !conf.GetConfigBool("cookieSecure") && !strings.HasPrefix(conf.GetConfigString("origin"), "https://") {
return
}
sessionCookieName := web.BConfig.WebConfig.Session.SessionName
if sessionCookieName == "" {
return
}
cookies := ctx.ResponseWriter.Header()["Set-Cookie"]
for i, cookie := range cookies {
if !strings.HasPrefix(cookie, sessionCookieName+"=") {
continue
}
// Check if Secure is already present (case-insensitive, handles variants like ";Secure" and "; Secure")
alreadySecure := false
for _, part := range strings.Split(cookie, ";") {
if strings.EqualFold(strings.TrimSpace(part), "secure") {
alreadySecure = true
break
}
}
if !alreadySecure {
cookies[i] = cookie + "; Secure"
}
}
}