Compare commits
	
		
			2 commits
		
	
	
		
			
				master
			
			...
			
				feature/lo
			
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 
							 | 
						9b3558f598 | ||
| 
							 | 
						8807ea42bb | 
					 15 changed files with 269 additions and 293 deletions
				
			
		
							
								
								
									
										2
									
								
								.github/PULL_REQUEST_TEMPLATE.md
									
										
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.github/PULL_REQUEST_TEMPLATE.md
									
										
									
									
										vendored
									
									
								
							| 
						 | 
					@ -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 
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
							
								
								
									
										14
									
								
								Dockerfile
									
										
									
									
									
								
							
							
						
						
									
										14
									
								
								Dockerfile
									
										
									
									
									
								
							| 
						 | 
					@ -1,5 +1,5 @@
 | 
				
			||||||
# Builder
 | 
					# Builder
 | 
				
			||||||
FROM golang:alpine AS builder
 | 
					FROM golang:alpine as builder
 | 
				
			||||||
WORKDIR /app
 | 
					WORKDIR /app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# Install git + SSL ca certificates.
 | 
					# Install git + SSL ca certificates.
 | 
				
			||||||
| 
						 | 
					@ -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"]
 | 
				
			||||||
							
								
								
									
										27
									
								
								go.mod
									
										
									
									
									
								
							
							
						
						
									
										27
									
								
								go.mod
									
										
									
									
									
								
							| 
						 | 
					@ -1,25 +1,14 @@
 | 
				
			||||||
module github.com/StiviiK/keycloak-traefik-forward-auth
 | 
					module github.com/StiviiK/keycloak-traefik-forward-auth
 | 
				
			||||||
 | 
					
 | 
				
			||||||
go 1.24
 | 
					go 1.14
 | 
				
			||||||
 | 
					 | 
				
			||||||
toolchain go1.24.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.14.1
 | 
						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.30.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/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5 // indirect
 | 
					 | 
				
			||||||
	github.com/pzentenoe/go-cache v1.0.0 // indirect
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
require (
 | 
					 | 
				
			||||||
	github.com/go-jose/go-jose/v4 v4.1.0 // indirect
 | 
					 | 
				
			||||||
	github.com/tg123/go-htpasswd v1.2.4
 | 
					 | 
				
			||||||
	golang.org/x/crypto v0.38.0 // indirect
 | 
					 | 
				
			||||||
	golang.org/x/sys v0.33.0 // indirect
 | 
					 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
							
								
								
									
										67
									
								
								go.sum
									
										
									
									
									
								
							
							
						
						
									
										67
									
								
								go.sum
									
										
									
									
									
								
							| 
						 | 
					@ -1,38 +1,37 @@
 | 
				
			||||||
github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5 h1:IEjq88XO4PuBDcvmjQJcQGg+w+UaafSy8G5Kcb5tBhI=
 | 
					cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
 | 
				
			||||||
github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5/go.mod h1:exZ0C/1emQJAw5tHOaUDyY1ycttqBAPcxuzf7QbY6ec=
 | 
					 | 
				
			||||||
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.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk=
 | 
					github.com/coreos/go-oidc v2.2.1+incompatible h1:mh48q/BqXqgjVHpy2ZY7WnWAbenxRjsz9N1i1YxjHAk=
 | 
				
			||||||
github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU=
 | 
					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.1.0 h1:cYSYxd3pw5zd2FSXk2vGdn9igQU2PS8MuxrCOCl0FdY=
 | 
					github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
 | 
				
			||||||
github.com/go-jose/go-jose/v4 v4.1.0/go.mod h1:GG/vqmYm3Von2nYiB2vGTXzdoNKE5tix5tuc6iAd+sw=
 | 
					github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
 | 
				
			||||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
 | 
					github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
 | 
				
			||||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
 | 
					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/pzentenoe/go-cache v1.0.0 h1:6jHsrh4CGKSBBmvNrEDn+EN9cJd4qOqLsHb7xWWEPBM=
 | 
					github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 h1:J9b7z+QKAmPf4YLrFg6oQUotqHQeUNWwkvo7jZp1GLU=
 | 
				
			||||||
github.com/pzentenoe/go-cache v1.0.0/go.mod h1:1JaNc73+p1tmcbNJwK55vtPR40h0hIoqqjlnhBZevBw=
 | 
					github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA=
 | 
				
			||||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
 | 
					github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
 | 
				
			||||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
 | 
					github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
 | 
				
			||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
 | 
					github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
 | 
				
			||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
 | 
					golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
 | 
				
			||||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
 | 
					golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=
 | 
				
			||||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
 | 
					golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
 | 
				
			||||||
github.com/tg123/go-htpasswd v1.2.4 h1:HgH8KKCjdmo7jjXWN9k1nefPBd7Be3tFCTjc2jPraPU=
 | 
					golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
 | 
				
			||||||
github.com/tg123/go-htpasswd v1.2.4/go.mod h1:EKThQok9xHkun6NBMynNv6Jmu24A33XdZzzl4Q7H1+0=
 | 
					golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg=
 | 
				
			||||||
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
 | 
					golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
 | 
				
			||||||
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
 | 
					golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
 | 
				
			||||||
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
 | 
					golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
 | 
				
			||||||
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
 | 
					golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw=
 | 
				
			||||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 | 
					golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
 | 
				
			||||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
 | 
					golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 | 
				
			||||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
 | 
					golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
 | 
				
			||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 | 
					golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 | 
				
			||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 | 
					golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
 | 
				
			||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
 | 
					golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 | 
				
			||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 | 
					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=
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
| 
						 | 
					@ -44,22 +44,15 @@ func (fw *ForwardAuth) IsAuthenticated(context context.Context, logger *logrus.E
 | 
				
			||||||
	var claims Claims
 | 
						var claims Claims
 | 
				
			||||||
	logger = logger.WithField("FunctionSource", "IsAuthenticated")
 | 
						logger = logger.WithField("FunctionSource", "IsAuthenticated")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Check if we have a session cookie
 | 
						// Check if we have an Auth cookie
 | 
				
			||||||
	cookie, err := fw.GetSessionCookie(r, options)
 | 
						cookie, err := fw.GetAuthCookie(r)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		logger.Error(err.Error())
 | 
							logger.Error(err.Error())
 | 
				
			||||||
		return &claims, err
 | 
							return &claims, err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	sessionId := cookie.Value
 | 
					 | 
				
			||||||
	session := fw.SessionCache.Get(sessionId)
 | 
					 | 
				
			||||||
	if session == nil {
 | 
					 | 
				
			||||||
		err = errors.New("session not found")
 | 
					 | 
				
			||||||
		return &claims, err
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// check if the token is valid
 | 
						// check if the token is valid
 | 
				
			||||||
	idToken, err := fw.OidcVefifier.Verify(context, session.IDToken)
 | 
						idToken, err := fw.OidcVefifier.Verify(context, cookie.Value)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	switch {
 | 
						switch {
 | 
				
			||||||
	case err == nil: // Token is valid
 | 
						case err == nil: // Token is valid
 | 
				
			||||||
| 
						 | 
					@ -72,24 +65,36 @@ func (fw *ForwardAuth) IsAuthenticated(context context.Context, logger *logrus.E
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		return &claims, nil
 | 
							return &claims, nil
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							// Todo: Updating the cookies does sadly not work here
 | 
				
			||||||
	case strings.Contains(err.Error(), "expired"): // Token is expired
 | 
						case strings.Contains(err.Error(), "expired"): // Token is expired
 | 
				
			||||||
		logger.Info("Received expired token, trying to refesh it.")
 | 
							logger.Info("Received expired token, trying to refesh it.")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		result, err := fw.RefreshToken(context, session.RefreshToken)
 | 
							refreshCookie, err := fw.GetRefreshAuthCookie(r)
 | 
				
			||||||
		if err != nil {
 | 
							if err != nil {
 | 
				
			||||||
			fw.SessionCache.Delete(sessionId)
 | 
					 | 
				
			||||||
			logger.Error(err.Error())
 | 
								logger.Error(err.Error())
 | 
				
			||||||
			return &claims, err
 | 
								return &claims, err
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		newSession := SessionCacheItem{IDToken: result.IDToken, RefreshToken: result.RefreshToken}
 | 
							result, err := fw.RefreshToken(context, refreshCookie.Value)
 | 
				
			||||||
		fw.SessionCache.Update(sessionId, &newSession)
 | 
							if err != nil {
 | 
				
			||||||
 | 
								logger.Error(err.Error())
 | 
				
			||||||
 | 
								return &claims, err
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							http.SetCookie(w, fw.MakeAuthCookie(options, result))
 | 
				
			||||||
 | 
							if len(result.RefreshToken) > 0 { // Do we have an refresh token?
 | 
				
			||||||
 | 
								http.SetCookie(w, fw.MakeRefreshAuthCookie(options, result))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		return result.IDTokenClaims, nil
 | 
							return result.IDTokenClaims, nil
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	default: // Other error
 | 
						case err != nil: // Other error
 | 
				
			||||||
		fw.SessionCache.Delete(sessionId)
 | 
					 | 
				
			||||||
		logger.Error(err.Error())
 | 
							logger.Error(err.Error())
 | 
				
			||||||
		return &claims, err
 | 
							return &claims, err
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						default:
 | 
				
			||||||
 | 
							logger.Error("default case, should not happen")
 | 
				
			||||||
 | 
							return &claims, errors.New("default case")
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
| 
						 | 
					@ -24,17 +24,17 @@ 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 = options.CookiePrefix + "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
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (fw *ForwardAuth) ValidateCSRFCookie(r *http.Request, options *options.Options) (state string, redirect string, error error) {
 | 
					func (fw *ForwardAuth) ValidateCSRFCookie(r *http.Request) (state string, redirect string, error error) {
 | 
				
			||||||
	csrfCookie, err := r.Cookie(options.CookiePrefix + "csrf")
 | 
						csrfCookie, err := r.Cookie("__auth_csrf")
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		return "", "", errors.New("Missing csrf cookie")
 | 
							return "", "", errors.New("Missing csrf cookie")
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
| 
						 | 
					@ -58,30 +58,49 @@ func (fw *ForwardAuth) ValidateCSRFCookie(r *http.Request, options *options.Opti
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (fw *ForwardAuth) ClearCSRFCookie(options *options.Options) *http.Cookie {
 | 
					func (fw *ForwardAuth) ClearCSRFCookie(options *options.Options) *http.Cookie {
 | 
				
			||||||
	cookie := getBaseCookie(options)
 | 
						cookie := getBaseCookie(options)
 | 
				
			||||||
	cookie.Name = options.CookiePrefix + "csrf"
 | 
						cookie.Name = "__auth_csrf"
 | 
				
			||||||
	cookie.Expires = time.Now().Local().Add(time.Hour * -1)
 | 
						cookie.Expires = time.Now().Local().Add(time.Hour * -1)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return cookie
 | 
						return cookie
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (fw *ForwardAuth) MakeSessionCookie(options *options.Options, sessionId string) *http.Cookie {
 | 
					func (fw *ForwardAuth) MakeAuthCookie(options *options.Options, authResult *AuthenticatationResult) *http.Cookie {
 | 
				
			||||||
	cookie := getBaseCookie(options)
 | 
						cookie := getBaseCookie(options)
 | 
				
			||||||
	cookie.Name = options.CookiePrefix + "session"
 | 
						cookie.Name = "__auth"
 | 
				
			||||||
	cookie.Value = sessionId
 | 
						cookie.Value = authResult.IDToken
 | 
				
			||||||
	if options.SessionLifetime > 0 {
 | 
						cookie.Expires = time.Now().Local().Add(time.Hour * 24)
 | 
				
			||||||
		cookie.Expires = time.Now().Local().Add(time.Hour * time.Duration(options.SessionLifetime))
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return cookie
 | 
						return cookie
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (fw *ForwardAuth) GetSessionCookie(r *http.Request, options *options.Options) (*http.Cookie, error) {
 | 
					func (fw *ForwardAuth) GetAuthCookie(r *http.Request) (*http.Cookie, error) {
 | 
				
			||||||
	return r.Cookie(options.CookiePrefix + "session")
 | 
						return r.Cookie("__auth")
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (fw *ForwardAuth) ClearSessionCookie(options *options.Options) *http.Cookie {
 | 
					func (fw *ForwardAuth) ClearAuthCookie(options *options.Options) *http.Cookie {
 | 
				
			||||||
	cookie := getBaseCookie(options)
 | 
						cookie := getBaseCookie(options)
 | 
				
			||||||
	cookie.Name = options.CookiePrefix + "session"
 | 
						cookie.Name = "__auth"
 | 
				
			||||||
 | 
						cookie.Expires = time.Now().Local().Add(time.Hour * -1)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return cookie
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (fw *ForwardAuth) MakeRefreshAuthCookie(options *options.Options, authResult *AuthenticatationResult) *http.Cookie {
 | 
				
			||||||
 | 
						cookie := getBaseCookie(options)
 | 
				
			||||||
 | 
						cookie.Name = "__auth_refresh"
 | 
				
			||||||
 | 
						cookie.Value = authResult.RefreshToken
 | 
				
			||||||
 | 
						cookie.Expires = time.Now().Local().Add(time.Hour * 24)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return cookie
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (fw *ForwardAuth) GetRefreshAuthCookie(r *http.Request) (*http.Cookie, error) {
 | 
				
			||||||
 | 
						return r.Cookie("__auth_refresh")
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (fw *ForwardAuth) ClearRefreshAuthCookie(options *options.Options) *http.Cookie {
 | 
				
			||||||
 | 
						cookie := getBaseCookie(options)
 | 
				
			||||||
 | 
						cookie.Name = "__auth_refresh"
 | 
				
			||||||
	cookie.Expires = time.Now().Local().Add(time.Hour * -1)
 | 
						cookie.Expires = time.Now().Local().Add(time.Hour * -1)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return cookie
 | 
						return cookie
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
| 
						 | 
					@ -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,7 +19,12 @@ type ForwardAuth struct {
 | 
				
			||||||
	OidcProvider *oidc.Provider
 | 
						OidcProvider *oidc.Provider
 | 
				
			||||||
	OAuth2Config oauth2.Config
 | 
						OAuth2Config oauth2.Config
 | 
				
			||||||
	OidcVefifier *oidc.IDTokenVerifier
 | 
						OidcVefifier *oidc.IDTokenVerifier
 | 
				
			||||||
	SessionCache SessionCache
 | 
					
 | 
				
			||||||
 | 
						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
 | 
				
			||||||
| 
						 | 
					@ -30,15 +34,14 @@ type Claims struct {
 | 
				
			||||||
	IssuedAt   utils.Time `json:"iat"`
 | 
						IssuedAt   utils.Time `json:"iat"`
 | 
				
			||||||
	Expiration utils.Time `json:"exp"`
 | 
						Expiration utils.Time `json:"exp"`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	Name             string   `json:"name"`
 | 
						Name             string `json:"name"`
 | 
				
			||||||
	GivenName        string   `json:"given_name"`
 | 
						GivenName        string `json:"given_name"`
 | 
				
			||||||
	FamilyName       string   `json:"family_name"`
 | 
						FamilyName       string `json:"family_name"`
 | 
				
			||||||
	Email            string   `json:"email"`
 | 
						Email            string `json:"email"`
 | 
				
			||||||
	VerifiedMail     bool     `json:"email_verified"`
 | 
						VerifiedMail     bool   `json:"email_verified"`
 | 
				
			||||||
	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
 | 
				
			||||||
| 
						 | 
					@ -52,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,
 | 
				
			||||||
| 
						 | 
					@ -66,9 +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,
 | 
					 | 
				
			||||||
		SessionCache: newSessionCache(options),
 | 
					 | 
				
			||||||
	}, nil
 | 
						}, nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
| 
						 | 
					@ -1,61 +0,0 @@
 | 
				
			||||||
package forwardauth
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
import (
 | 
					 | 
				
			||||||
	"time"
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	"github.com/StiviiK/keycloak-traefik-forward-auth/pkg/options"
 | 
					 | 
				
			||||||
	"github.com/google/uuid"
 | 
					 | 
				
			||||||
	"github.com/pzentenoe/go-cache"
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
type SessionCache struct {
 | 
					 | 
				
			||||||
	internal  *cache.Cache
 | 
					 | 
				
			||||||
	longLived bool
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
type SessionCacheItem struct {
 | 
					 | 
				
			||||||
	IDToken      string
 | 
					 | 
				
			||||||
	RefreshToken string
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func newSessionCache(options *options.Options) SessionCache {
 | 
					 | 
				
			||||||
	longLived := options.SessionLifetime > 0
 | 
					 | 
				
			||||||
	var nd int
 | 
					 | 
				
			||||||
	if longLived {
 | 
					 | 
				
			||||||
		nd = options.SessionLifetime
 | 
					 | 
				
			||||||
	} else {
 | 
					 | 
				
			||||||
		nd = 12
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	return SessionCache{
 | 
					 | 
				
			||||||
		internal: cache.New(time.Hour*time.Duration(nd), time.Hour),
 | 
					 | 
				
			||||||
		longLived: longLived,
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (c *SessionCache) Get(sessionId string) *SessionCacheItem {
 | 
					 | 
				
			||||||
	itm, _ := c.internal.Get(sessionId)
 | 
					 | 
				
			||||||
	if itm == nil {
 | 
					 | 
				
			||||||
		return nil
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
	return itm.(*SessionCacheItem)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (c *SessionCache) Create(session *SessionCacheItem) string {
 | 
					 | 
				
			||||||
	sessionId := uuid.New().String()
 | 
					 | 
				
			||||||
	c.internal.SetDefault(sessionId, session)
 | 
					 | 
				
			||||||
	return sessionId
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (c *SessionCache) Update(sessionId string, session *SessionCacheItem) {
 | 
					 | 
				
			||||||
	_, exp, found := c.internal.GetWithExpiration(sessionId)
 | 
					 | 
				
			||||||
	if found && c.longLived {
 | 
					 | 
				
			||||||
		c.internal.Set(sessionId, session, exp.Sub(time.Now()))
 | 
					 | 
				
			||||||
	} else {
 | 
					 | 
				
			||||||
		c.internal.SetDefault(sessionId, session)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (c *SessionCache) Delete(sessionId string) {
 | 
					 | 
				
			||||||
	c.internal.Delete(sessionId)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
| 
						 | 
					@ -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()
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
| 
						 | 
					@ -8,19 +8,18 @@ import (
 | 
				
			||||||
	"net/http"
 | 
						"net/http"
 | 
				
			||||||
	"net/url"
 | 
						"net/url"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"github.com/StiviiK/keycloak-traefik-forward-auth/pkg/forwardauth"
 | 
					 | 
				
			||||||
	"github.com/sirupsen/logrus"
 | 
						"github.com/sirupsen/logrus"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// 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
 | 
				
			||||||
	state, redirect, err := root.forwardAuth.ValidateCSRFCookie(r, root.options)
 | 
						state, redirect, err := root.forwardAuth.ValidateCSRFCookie(r)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		http.Error(w, err.Error(), http.StatusUnauthorized)
 | 
							http.Error(w, err.Error(), http.StatusUnauthorized)
 | 
				
			||||||
		return
 | 
							return
 | 
				
			||||||
| 
						 | 
					@ -42,9 +41,9 @@ func (root *HttpHandler) callbackHandler(w http.ResponseWriter, r *http.Request,
 | 
				
			||||||
	// clear the csrf cookie
 | 
						// clear the csrf cookie
 | 
				
			||||||
	http.SetCookie(w, root.forwardAuth.ClearCSRFCookie(root.options))
 | 
						http.SetCookie(w, root.forwardAuth.ClearCSRFCookie(root.options))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	newSession := forwardauth.SessionCacheItem{IDToken: authResult.IDToken, RefreshToken: authResult.RefreshToken}
 | 
						http.SetCookie(w, root.forwardAuth.MakeAuthCookie(root.options, authResult))
 | 
				
			||||||
	sessionId := root.forwardAuth.SessionCache.Create(&newSession)
 | 
						//if len(authResult.RefreshToken) > 0 { // Do we have an refresh token?
 | 
				
			||||||
 | 
						//	http.SetCookie(w, root.forwardAuth.MakeRefreshAuthCookie(root.options, authResult))
 | 
				
			||||||
	http.SetCookie(w, root.forwardAuth.MakeSessionCookie(root.options, sessionId))
 | 
						//}
 | 
				
			||||||
	http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
 | 
						http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
							
								
								
									
										41
									
								
								pkg/httphandler/auth_root.go
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										41
									
								
								pkg/httphandler/auth_root.go
									
										
									
									
									
										Normal file
									
								
							| 
						 | 
					@ -0,0 +1,41 @@
 | 
				
			||||||
 | 
					/*
 | 
				
			||||||
 | 
					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) 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{
 | 
				
			||||||
 | 
							"SourceIP":      r.Header.Get("X-Forwarded-For"),
 | 
				
			||||||
 | 
							"RequestTarget": redirect,
 | 
				
			||||||
 | 
							"Path":          "/",
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						claims, err := root.forwardAuth.IsAuthenticated(r.Context(), logger, w, r, root.options)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							logger = logger.WithField("FunctionSource", "RootHandler")
 | 
				
			||||||
 | 
							logger.Warn("IsAuthenticated failed, initating login flow.")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							http.SetCookie(w, root.forwardAuth.ClearAuthCookie(root.options))
 | 
				
			||||||
 | 
							//http.SetCookie(w, root.forwardAuth.ClearRefreshAuthCookie(root.options))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							state := uuid.New().String()
 | 
				
			||||||
 | 
							http.SetCookie(w, root.forwardAuth.MakeCSRFCookie(w, r, root.options, redirect, state))
 | 
				
			||||||
 | 
							http.Redirect(w, r, root.forwardAuth.OAuth2Config.AuthCodeURL(state), http.StatusTemporaryRedirect)
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						w.Header().Set("X-Forwarded-User", claims.Email)
 | 
				
			||||||
 | 
						w.WriteHeader(http.StatusOK)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
| 
						 | 
					@ -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)
 | 
					 | 
				
			||||||
				return
 | 
					 | 
				
			||||||
			}
 | 
					 | 
				
			||||||
		}
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// Handles forward auth
 | 
							case uri.Path == root.options.LogoutUrl:
 | 
				
			||||||
		h.rootHandler(w, r, uri, r.URL)
 | 
								root.logoutHandler(w, r, uri)
 | 
				
			||||||
 | 
								return
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							case uri.Path == fmt.Sprintf("%s/resp", root.options.LogoutUrl):
 | 
				
			||||||
 | 
								return
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							default:
 | 
				
			||||||
 | 
								root.authRootHandler(w, r, uri)
 | 
				
			||||||
 | 
								return
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
							
								
								
									
										49
									
								
								pkg/httphandler/logout_root.go
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										49
									
								
								pkg/httphandler/logout_root.go
									
										
									
									
									
										Normal 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)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
| 
						 | 
					@ -1,69 +0,0 @@
 | 
				
			||||||
/*
 | 
					 | 
				
			||||||
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) rootHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL, queryURI *url.URL) {
 | 
					 | 
				
			||||||
	logger := logrus.WithFields(logrus.Fields{
 | 
					 | 
				
			||||||
		"SourceIP":      r.Header.Get("X-Forwarded-For"),
 | 
					 | 
				
			||||||
		"RequestTarget": root.forwardAuth.GetReturnUri(r),
 | 
					 | 
				
			||||||
		"Path":          forwardedURI.Path,
 | 
					 | 
				
			||||||
	})
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	user, pass, usesBasicAuth := r.BasicAuth()
 | 
					 | 
				
			||||||
	if usesBasicAuth && root.options.BypassPwd != nil {
 | 
					 | 
				
			||||||
		if root.options.BypassPwd.Match(user, pass) {
 | 
					 | 
				
			||||||
			logger.Infof("Basic auth successful: %s", user)
 | 
					 | 
				
			||||||
			w.Header().Set("X-Forwarded-User", "bypass@example.com")
 | 
					 | 
				
			||||||
			w.WriteHeader(200)
 | 
					 | 
				
			||||||
			return
 | 
					 | 
				
			||||||
		} else {
 | 
					 | 
				
			||||||
			logger.Errorf("Basic auth failed: %s", user)
 | 
					 | 
				
			||||||
		}
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	claims, err := root.forwardAuth.IsAuthenticated(r.Context(), logger, w, r, root.options)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		logger = logger.WithField("FunctionSource", "RootHandler")
 | 
					 | 
				
			||||||
		logger.Warn("IsAuthenticated failed, initating login flow.")
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
		http.SetCookie(w, root.forwardAuth.ClearSessionCookie(root.options))
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
		state := uuid.New().String()
 | 
					 | 
				
			||||||
		http.SetCookie(w, root.forwardAuth.MakeCSRFCookie(w, r, root.options, state))
 | 
					 | 
				
			||||||
		http.Redirect(w, r, root.forwardAuth.OAuth2Config.AuthCodeURL(state), http.StatusTemporaryRedirect)
 | 
					 | 
				
			||||||
		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.WriteHeader(200)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func contains(s []string, e string) bool {
 | 
					 | 
				
			||||||
	for _, a := range s {
 | 
					 | 
				
			||||||
		if a == e {
 | 
					 | 
				
			||||||
			return true
 | 
					 | 
				
			||||||
		}
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
	return false
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
| 
						 | 
					@ -6,26 +6,19 @@ package options
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	"strings"
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"github.com/caarlos0/env"
 | 
						"github.com/caarlos0/env"
 | 
				
			||||||
	"github.com/tg123/go-htpasswd"
 | 
					 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type Options struct {
 | 
					type Options struct {
 | 
				
			||||||
	Issuer          string `env:"ISSUER"`
 | 
						Issuer       string `env:"ISSUER"`
 | 
				
			||||||
	ClientID        string `env:"CLIENT_ID"`
 | 
						ClientID     string `env:"CLIENT_ID"`
 | 
				
			||||||
	ClientSecret    string `env:"CLIENT_SECRET"`
 | 
						ClientSecret string `env:"CLIENT_SECRET"`
 | 
				
			||||||
	AuthDomain      string `env:"AUTH_DOMAIN"`
 | 
						AuthDomain   string `env:"AUTH_DOMAIN"`
 | 
				
			||||||
	CookieDomain    string `env:"COOKIE_DOMAIN"`
 | 
						CookieDomain string `env:"COOKIE_DOMAIN"`
 | 
				
			||||||
	CookiePrefix    string `env:"COOKIE_PREFIX" envDefault:"oidca_"`
 | 
						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"`
 | 
						LogoutUrl    string `env:"LOGOUT_URL" envDefault:"/auth/logout"`
 | 
				
			||||||
	Scopes          string `env:"SCOPES"`
 | 
					 | 
				
			||||||
	BypassUser      string `env:"BYPASS_USER"`
 | 
					 | 
				
			||||||
	BypassFile      string `env:"BYPASS_FILE"`
 | 
					 | 
				
			||||||
	BypassPwd       *htpasswd.File
 | 
					 | 
				
			||||||
	SessionLifetime int `env:"SESSION_LIFETIME" envDefault:"0"`
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// LoadOptions parses the environment vars and the options
 | 
					// LoadOptions parses the environment vars and the options
 | 
				
			||||||
| 
						 | 
					@ -35,20 +28,5 @@ func LoadOptions() (*Options, error) {
 | 
				
			||||||
		return nil, fmt.Errorf("failed to parse options: %s", err)
 | 
							return nil, fmt.Errorf("failed to parse options: %s", err)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	if options.BypassFile != "" {
 | 
					 | 
				
			||||||
		parsed, err := htpasswd.New(options.BypassFile, htpasswd.DefaultSystems, func(err error) {})
 | 
					 | 
				
			||||||
		if err != nil {
 | 
					 | 
				
			||||||
			return nil, err
 | 
					 | 
				
			||||||
		}
 | 
					 | 
				
			||||||
		options.BypassPwd = parsed
 | 
					 | 
				
			||||||
	} else if options.BypassUser != "" {
 | 
					 | 
				
			||||||
		prep := strings.ReplaceAll(options.BypassUser, ";", "\n")
 | 
					 | 
				
			||||||
		parsed, err := htpasswd.NewFromReader(strings.NewReader(prep), htpasswd.DefaultSystems, func(err error) {})
 | 
					 | 
				
			||||||
		if err != nil {
 | 
					 | 
				
			||||||
			return nil, err
 | 
					 | 
				
			||||||
		}
 | 
					 | 
				
			||||||
		options.BypassPwd = parsed
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	return &options, nil
 | 
						return &options, nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue