Files
grafana/pkg/middleware/cookie.go
T
Jeffrey Descan c5f906f472 Security: refactor 'redirect_to' cookie to use 'Secure' flag (#19787)
* Refactor redirect_to cookie with secure flag in middleware

* Refactor redirect_to cookie with secure flag in api/login

* Refactor redirect_to cookie with secure flag in api/login_oauth

* Removed the deletion of 'Set-Cookie' header to prevent logout

* Removed the deletion of 'Set-Cookie' at top of api/login.go

* Add HttpOnly flag on redirect_to cookies where missing

* Refactor duplicated code

* Add tests

* Refactor cookie options

* Replace local function for deleting cookie

* Delete redundant calls

Co-authored-by: Sofia Papagiannaki <papagian@users.noreply.github.com>
2020-01-10 15:55:30 +02:00

44 lines
988 B
Go

package middleware
import (
"net/http"
"github.com/grafana/grafana/pkg/setting"
)
type CookieOptions struct {
Path string
Secure bool
SameSite http.SameSite
}
func newCookieOptions() CookieOptions {
return CookieOptions{
Path: setting.AppSubUrl + "/",
Secure: setting.CookieSecure,
SameSite: setting.CookieSameSite,
}
}
type GetCookieOptionsFunc func() CookieOptions
func DeleteCookie(w http.ResponseWriter, name string, getCookieOptionsFunc GetCookieOptionsFunc) {
WriteCookie(w, name, "", -1, getCookieOptionsFunc)
}
func WriteCookie(w http.ResponseWriter, name string, value string, maxAge int, getCookieOptionsFunc GetCookieOptionsFunc) {
options := getCookieOptionsFunc()
cookie := http.Cookie{
Name: name,
MaxAge: maxAge,
Value: value,
HttpOnly: true,
Path: options.Path,
Secure: options.Secure,
}
if options.SameSite != http.SameSiteDefaultMode {
cookie.SameSite = options.SameSite
}
http.SetCookie(w, &cookie)
}