From 976c13cf62551c708a7ea5a2f4c6f1dd43f8f891 Mon Sep 17 00:00:00 2001 From: Ilja Neumann Date: Fri, 27 Mar 2020 10:57:32 +0100 Subject: [PATCH] Redirect http-requests to https (#29) --- changelog/unreleased/redirect_to_https.md | 4 ++++ pkg/command/server.go | 3 +++ pkg/middleware/https_redirect.go | 19 +++++++++++++++++++ 3 files changed, 26 insertions(+) create mode 100644 changelog/unreleased/redirect_to_https.md create mode 100644 pkg/middleware/https_redirect.go diff --git a/changelog/unreleased/redirect_to_https.md b/changelog/unreleased/redirect_to_https.md new file mode 100644 index 0000000000..d8a139fbeb --- /dev/null +++ b/changelog/unreleased/redirect_to_https.md @@ -0,0 +1,4 @@ +Change: Insecure http-requests are now redirected to https + +https://github.com/owncloud/ocis-proxy/pull/29 + diff --git a/pkg/command/server.go b/pkg/command/server.go index 3ea351d0c4..fe02b26f60 100644 --- a/pkg/command/server.go +++ b/pkg/command/server.go @@ -236,6 +236,9 @@ func Server(cfg *config.Config) *cli.Command { func loadMiddlewares(cfg *config.Config, l log.Logger) []func(handler http.Handler) http.Handler { var configuredMiddlewares = make([]func(handler http.Handler) http.Handler, 0) + + configuredMiddlewares = append(configuredMiddlewares, middleware.RedirectToHTTPS) + if cfg.OIDC != nil { l.Info().Msg("Loading OIDC-Middleware") l.Debug().Interface("oidc_config", cfg.OIDC).Msg("OIDC-Config") diff --git a/pkg/middleware/https_redirect.go b/pkg/middleware/https_redirect.go new file mode 100644 index 0000000000..60b4684469 --- /dev/null +++ b/pkg/middleware/https_redirect.go @@ -0,0 +1,19 @@ +package middleware + +import ( + "fmt" + "net/http" +) + +// RedirectToHTTPS redirects insecure requests to https +func RedirectToHTTPS(next http.Handler) http.Handler { + return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + proto := req.Header.Get("x-forwarded-proto") + if proto == "http" || proto == "HTTP" { + http.Redirect(res, req, fmt.Sprintf("https://%s%s", req.Host, req.URL), http.StatusPermanentRedirect) + return + } + + next.ServeHTTP(res, req) + }) +}