Compare commits

..

2 commits

Author SHA1 Message Date
Stefan Kürzeder
9b3558f598 File refactor 2020-06-04 18:46:33 +02:00
Stefan Kürzeder
8807ea42bb Started with logout 2020-06-04 18:14:16 +02:00
12 changed files with 167 additions and 106 deletions

View file

@ -16,4 +16,4 @@ Please select relevant options:
- [ ] I have added tests that prove my fix is effective or that my feature works - [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] I have checked my code and corrected any misspellings - [ ] I have checked my code and corrected any misspellings
Reviewer: @stiviik Reviewer: @nmeisenzahl

View file

@ -31,7 +31,7 @@ RUN go mod download
RUN go mod verify RUN go mod verify
# Build the binary. # Build the binary.
RUN CGO_ENABLED=0 go build -a -installsuffix cgo -ldflags="-w -s" -o /go/bin/oidc-forward-auth RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -ldflags="-w -s" -o /go/bin/oidc-forward-auth
# Runner # Runner
FROM scratch FROM scratch
@ -52,10 +52,10 @@ USER appuser:appuser
ARG BUILD_DATE ARG BUILD_DATE
ARG VCS_REF ARG VCS_REF
# Good docker practice # Good docker practice, plus we get microbadger badges
LABEL org.opencontainers.image.created=$BUILD_DATE \ LABEL org.label-schema.build-date=$BUILD_DATE \
org.opencontainers.image.authors="StiviiK" \ org.label-schema.vcs-url="https://github.com/StiviiK/oidc-forward-auth.git" \
org.opencontainers.image.source="https://code.thetadev.de/ThetaDev/oidc-forward-auth" \ org.label-schema.vcs-ref=$VCS_REF \
org.opencontainers.image.revision=$VCS_REF org.label-schema.schema-version="1.0"
ENTRYPOINT ["/go/bin/oidc-forward-auth"] ENTRYPOINT ["/go/bin/oidc-forward-auth"]

21
go.mod
View file

@ -1,19 +1,14 @@
module github.com/StiviiK/keycloak-traefik-forward-auth module github.com/StiviiK/keycloak-traefik-forward-auth
go 1.21 go 1.14
toolchain go1.22.2
require ( require (
github.com/caarlos0/env v3.5.0+incompatible github.com/caarlos0/env v3.5.0+incompatible
github.com/coreos/go-oidc/v3 v3.10.0 github.com/coreos/go-oidc v2.2.1+incompatible
github.com/google/uuid v1.6.0 github.com/google/uuid v1.1.1
github.com/sirupsen/logrus v1.9.3 github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 // indirect
golang.org/x/oauth2 v0.19.0 github.com/sirupsen/logrus v1.6.0
) golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 // indirect
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
require ( gopkg.in/square/go-jose.v2 v2.5.1 // indirect
github.com/go-jose/go-jose/v4 v4.0.1 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/sys v0.19.0 // indirect
) )

61
go.sum
View file

@ -1,32 +1,37 @@
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/caarlos0/env v3.5.0+incompatible h1:Yy0UN8o9Wtr/jGHZDpCBLpNrzcFLLM2yixi/rBrKyJs= github.com/caarlos0/env v3.5.0+incompatible h1:Yy0UN8o9Wtr/jGHZDpCBLpNrzcFLLM2yixi/rBrKyJs=
github.com/caarlos0/env v3.5.0+incompatible/go.mod h1:tdCsowwCzMLdkqRYDlHpZCp2UooDD3MspDBjZ2AD02Y= github.com/caarlos0/env v3.5.0+incompatible/go.mod h1:tdCsowwCzMLdkqRYDlHpZCp2UooDD3MspDBjZ2AD02Y=
github.com/coreos/go-oidc/v3 v3.10.0 h1:tDnXHnLyiTVyT/2zLDGj09pFPkhND8Gl8lnTRhoEaJU= github.com/coreos/go-oidc v2.2.1+incompatible h1:mh48q/BqXqgjVHpy2ZY7WnWAbenxRjsz9N1i1YxjHAk=
github.com/coreos/go-oidc/v3 v3.10.0/go.mod h1:5j11xcw0D3+SGxn6Z/WFADsgcWVMyNAlSQupk0KK3ac= github.com/coreos/go-oidc v2.2.1+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-jose/go-jose/v4 v4.0.1 h1:QVEPDE3OluqXBQZDcnNvQrInro2h0e4eqNbnZSWqS6U= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/go-jose/go-jose/v4 v4.0.1/go.mod h1:WVf9LFMHh/QVrmqrOfqun0C45tMe3RoiKJMPvgWwLfY= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 h1:J9b7z+QKAmPf4YLrFg6oQUotqHQeUNWwkvo7jZp1GLU=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/oauth2 v0.19.0 h1:9+E/EZBCbTLNrbN35fHv/a/d/mOBatymz1zbtQrXpIg= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/oauth2 v0.19.0/go.mod h1:vYi7skDa1x015PmRRYZ7+s1cWyPgrPiSYRe4rnsexc8= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
gopkg.in/square/go-jose.v2 v2.5.1 h1:7odma5RETjNHWJnR32wx8t+Io4djHE1PqxCFx3iiZ2w=
gopkg.in/square/go-jose.v2 v2.5.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI=

View file

@ -24,10 +24,10 @@ func getBaseCookie(options *options.Options) *http.Cookie {
} }
} }
func (fw *ForwardAuth) MakeCSRFCookie(w http.ResponseWriter, r *http.Request, options *options.Options, state string) *http.Cookie { func (fw *ForwardAuth) MakeCSRFCookie(w http.ResponseWriter, r *http.Request, options *options.Options, redirect string, state string) *http.Cookie {
cookie := getBaseCookie(options) cookie := getBaseCookie(options)
cookie.Name = "__auth_csrf" cookie.Name = "__auth_csrf"
cookie.Value = fmt.Sprintf("%s|%s", fw.GetReturnUri(r), state) cookie.Value = fmt.Sprintf("%s|%s", redirect, state)
cookie.Expires = time.Now().Local().Add(time.Hour) cookie.Expires = time.Now().Local().Add(time.Hour)
return cookie return cookie

View file

@ -7,11 +7,10 @@ package forwardauth
import ( import (
"context" "context"
"fmt" "fmt"
"strings"
"github.com/StiviiK/keycloak-traefik-forward-auth/pkg/options" "github.com/StiviiK/keycloak-traefik-forward-auth/pkg/options"
"github.com/StiviiK/keycloak-traefik-forward-auth/pkg/utils" "github.com/StiviiK/keycloak-traefik-forward-auth/pkg/utils"
"github.com/coreos/go-oidc/v3/oidc" "github.com/coreos/go-oidc"
"golang.org/x/oauth2" "golang.org/x/oauth2"
) )
@ -20,6 +19,12 @@ type ForwardAuth struct {
OidcProvider *oidc.Provider OidcProvider *oidc.Provider
OAuth2Config oauth2.Config OAuth2Config oauth2.Config
OidcVefifier *oidc.IDTokenVerifier OidcVefifier *oidc.IDTokenVerifier
OidcProviderClaims *OidcProviderClaims
}
type OidcProviderClaims struct {
EndSessionURL string `json:"end_session_endpoint"`
} }
// Claims represents the claims struct which we get from the identity provider // Claims represents the claims struct which we get from the identity provider
@ -37,7 +42,6 @@ type Claims struct {
Picture string `json:"picture"` Picture string `json:"picture"`
Locale string `json:"locale"` Locale string `json:"locale"`
PreferedUsername string `json:"preferred_username"` PreferedUsername string `json:"preferred_username"`
Groups []string `json:"groups"`
} }
// Create creates a new fw auth client from our options // Create creates a new fw auth client from our options
@ -51,11 +55,16 @@ func Create(ctx context.Context, options *options.Options) (*ForwardAuth, error)
ClientID: options.ClientID, ClientID: options.ClientID,
}) })
scopes := []string{oidc.ScopeOpenID, "profile", "email"} providerClaims := OidcProviderClaims{}
scopes = append(scopes, strings.Split(options.Scopes, " ")...) if err = provider.Claims(&providerClaims); err != nil {
return nil, err
}
return &ForwardAuth{ return &ForwardAuth{
OidcProvider: provider, OidcProvider: provider,
OidcVefifier: verifier,
OidcProviderClaims: &providerClaims,
OAuth2Config: oauth2.Config{ OAuth2Config: oauth2.Config{
ClientID: options.ClientID, ClientID: options.ClientID,
ClientSecret: options.ClientSecret, ClientSecret: options.ClientSecret,
@ -65,8 +74,7 @@ func Create(ctx context.Context, options *options.Options) (*ForwardAuth, error)
Endpoint: provider.Endpoint(), Endpoint: provider.Endpoint(),
// "openid" is a required scope for OpenID Connect flows. // "openid" is a required scope for OpenID Connect flows.
Scopes: scopes, Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
}, },
OidcVefifier: verifier,
}, nil }, nil
} }

View file

@ -7,6 +7,7 @@ package forwardauth
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"net/url"
) )
func (fw *ForwardAuth) GetReturnUri(r *http.Request) string { func (fw *ForwardAuth) GetReturnUri(r *http.Request) string {
@ -16,3 +17,19 @@ func (fw *ForwardAuth) GetReturnUri(r *http.Request) string {
return fmt.Sprintf("%s://%s%s", proto, host, path) return fmt.Sprintf("%s://%s%s", proto, host, path)
} }
func (fw *ForwardAuth) GetLogoutUri(redirectURL string, state string) string {
logoutURL, err := url.Parse(fw.OidcProviderClaims.EndSessionURL)
if err != nil {
return ""
}
query := logoutURL.Query()
if redirectURL != "" {
query.Set("post_logout_redirect_uri", redirectURL)
}
if state != "" {
query.Set("state", state)
}
logoutURL.RawQuery = query.Encode()
return logoutURL.String()
}

View file

@ -12,10 +12,10 @@ import (
) )
// CallbackHandler returns a handler function which handles the callback from oidc provider // CallbackHandler returns a handler function which handles the callback from oidc provider
func (root *HttpHandler) callbackHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL) { func (root *HttpHandler) authCallbackHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL) {
logger := logrus.WithFields(logrus.Fields{ logger := logrus.WithFields(logrus.Fields{
"SourceIP": r.Header.Get("X-Forwarded-For"), "SourceIP": r.Header.Get("X-Forwarded-For"),
"Path": forwardedURI.Path, "Path": "/auth/resp",
}) })
// check for the csrf cookie // check for the csrf cookie

View file

@ -14,11 +14,12 @@ import (
) )
// RootHandler returns a handler function which handles all requests to the root // RootHandler returns a handler function which handles all requests to the root
func (root *HttpHandler) rootHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL, queryURI *url.URL) { func (root *HttpHandler) authRootHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL) {
redirect := fmt.Sprintf("%s://%s%s", r.Header.Get("X-Forwarded-Proto"), r.Header.Get("X-Forwarded-Host"), r.Header.Get("X-Forwarded-Uri"))
logger := logrus.WithFields(logrus.Fields{ logger := logrus.WithFields(logrus.Fields{
"SourceIP": r.Header.Get("X-Forwarded-For"), "SourceIP": r.Header.Get("X-Forwarded-For"),
"RequestTarget": root.forwardAuth.GetReturnUri(r), "RequestTarget": redirect,
"Path": forwardedURI.Path, "Path": "/",
}) })
claims, err := root.forwardAuth.IsAuthenticated(r.Context(), logger, w, r, root.options) claims, err := root.forwardAuth.IsAuthenticated(r.Context(), logger, w, r, root.options)
@ -30,29 +31,11 @@ func (root *HttpHandler) rootHandler(w http.ResponseWriter, r *http.Request, for
//http.SetCookie(w, root.forwardAuth.ClearRefreshAuthCookie(root.options)) //http.SetCookie(w, root.forwardAuth.ClearRefreshAuthCookie(root.options))
state := uuid.New().String() state := uuid.New().String()
http.SetCookie(w, root.forwardAuth.MakeCSRFCookie(w, r, root.options, state)) http.SetCookie(w, root.forwardAuth.MakeCSRFCookie(w, r, root.options, redirect, state))
http.Redirect(w, r, root.forwardAuth.OAuth2Config.AuthCodeURL(state), http.StatusTemporaryRedirect) http.Redirect(w, r, root.forwardAuth.OAuth2Config.AuthCodeURL(state), http.StatusTemporaryRedirect)
return return
} }
// Check group
group := queryURI.Query().Get("group")
if len(group) > 0 {
if !contains(claims.Groups, group) {
logger.Warnf("User %s not member of group %s", claims.PreferedUsername, group)
http.Error(w, fmt.Sprintf("You need to be a member of the group '%s' to access this site", group), http.StatusForbidden)
}
}
w.Header().Set("X-Forwarded-User", claims.Email) w.Header().Set("X-Forwarded-User", claims.Email)
w.WriteHeader(200) w.WriteHeader(http.StatusOK)
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
} }

View file

@ -5,6 +5,7 @@ This code is licensed under MIT license (see LICENSE for details)
package httphandler package httphandler
import ( import (
"fmt"
"net/http" "net/http"
"net/url" "net/url"
@ -24,25 +25,28 @@ func Create(fw *forwardauth.ForwardAuth, options *options.Options) *HttpHandler
} }
} }
func (h *HttpHandler) Entrypoint() func(http.ResponseWriter, *http.Request) { func (root *HttpHandler) Entrypoint() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
uri, err := url.Parse(r.Header.Get("X-Forwarded-Uri")) uri, err := url.Parse(r.Header.Get("X-Forwarded-Uri"))
host := r.Header.Get("X-Forwarded-Host") switch {
case err != nil:
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
}
if host == h.options.AuthDomain { case uri.Path == root.options.RedirectURL:
// Handles OIDC callback root.authCallbackHandler(w, r, uri)
if uri.Path == h.options.RedirectURL { return
h.callbackHandler(w, r, uri)
case uri.Path == root.options.LogoutUrl:
root.logoutHandler(w, r, uri)
return
case uri.Path == fmt.Sprintf("%s/resp", root.options.LogoutUrl):
return
default:
root.authRootHandler(w, r, uri)
return return
} }
} }
// Handles forward auth
h.rootHandler(w, r, uri, r.URL)
}
} }

View file

@ -0,0 +1,49 @@
/*
Copyright (c) 2020 Stefan Kürzeder <info@stivik.de>
This code is licensed under MIT license (see LICENSE for details)
*/
package httphandler
import (
"fmt"
"net/http"
"net/url"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
// RootHandler returns a handler function which handles all requests to the root
func (root *HttpHandler) logoutHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL) {
logger := logrus.WithFields(logrus.Fields{
"SourceIP": r.Header.Get("X-Forwarded-For"),
"RequestTarget": root.forwardAuth.GetReturnUri(r),
"Path": root.options.LogoutUrl,
})
// check for the csrf cookie
state, redirect, err := root.forwardAuth.ValidateCSRFCookie(r)
if err != nil {
state := uuid.New().String()
redirect := fmt.Sprintf("%s://%s", r.Header.Get("X-Forwarded-Proto"), r.Header.Get("X-Forwarded-Host"))
http.SetCookie(w, root.forwardAuth.MakeCSRFCookie(w, r, root.options, redirect, state))
responseURL := fmt.Sprintf("https://%s%s/resp", root.options.AuthDomain, root.options.LogoutUrl)
http.Redirect(w, r, root.forwardAuth.GetLogoutUri(responseURL, state), http.StatusTemporaryRedirect)
return
}
// verify the state
if forwardedURI.Query().Get("state") != state {
http.Error(w, "state did not match", http.StatusBadRequest)
return
}
// Clear the auth information
logger.Info("Destroying auth cookie.")
http.SetCookie(w, root.forwardAuth.ClearAuthCookie(root.options))
// Redirect to the base
http.Redirect(w, r, redirect, http.StatusFound)
}

View file

@ -18,7 +18,7 @@ type Options struct {
CookieDomain string `env:"COOKIE_DOMAIN"` CookieDomain string `env:"COOKIE_DOMAIN"`
Port int `env:"PORT" envDefault:"4181"` Port int `env:"PORT" envDefault:"4181"`
RedirectURL string `env:"REDIRECT_URL" envDefault:"/auth/resp"` RedirectURL string `env:"REDIRECT_URL" envDefault:"/auth/resp"`
Scopes string `env:"SCOPES"` LogoutUrl string `env:"LOGOUT_URL" envDefault:"/auth/logout"`
} }
// LoadOptions parses the environment vars and the options // LoadOptions parses the environment vars and the options