Skip to content

an SSO and OAuth / OIDC login solution for Nginx using the auth_request module

License

Notifications You must be signed in to change notification settings

vouch/vouch-proxy

Repository files navigation

Vouch Proxy

GitHub stars Build Status Go Report Card MIT license GitHub version

An SSO solution for Nginx using theauth_requestmodule. Vouch Proxy can protect all of your websites at once.

Vouch Proxy supports many OAuth and OIDC login providers and can enforce authentication to...

Please do let us know when you have deployed Vouch Proxy with your preffered IdP or library so we can update the list.

If Vouch is running on the same host as the Nginx reverse proxy the response time from the/validateendpoint to Nginx should beless than 1ms.


Table of Contents

What Vouch Proxy Does

Vouch Proxy (VP) forces visitors to login and authenticate with anIdP(such as one of the services listed above) before allowing them access to a website.

Vouch Proxy protects websites

VP can also be used as a Single Sign On (SSO) solution to protect all web applications in the same domain.

Vouch Proxy is a Single Sign On solution

After a visitor logs in Vouch Proxy allows access to the protected websites for several hours. Every request is checked by VP to ensure that it is valid.

VP can send the visitor's email, name and other information which the IdP provides (including access tokens) to the web application as HTTP headers. VP can be used to replace application user management entirely.

Installation and Configuration

Vouch Proxy relies on the ability to share a cookie between the Vouch Proxy server and the application it's protecting. Typically this will be done by running Vouch on a subdomain such asvouch.yourdomainwith apps running atapp1.yourdomainandapp2.yourdomain.The protected domain is.yourdomainand the Vouch Proxy cookie must be set in this domain by settingvouch.domainsto includeyourdomainor sometimes by settingvouch.cookie.domaintoyourdomain.

  • cp./config/config.yml_example_$OAUTH_PROVIDER./config/config.yml
  • create OAuth credentials for Vouch Proxy atgoogleorgithub,etc
    • be sure to direct the callback URL to the Vouch Proxy/authendpoint
  • configure Nginx...

The following Nginx config assumes..

  • Nginx,vouch.yourdomainandprotectedapp.yourdomainare running on the same server
  • both domains are served ashttpsand have valid certs (if not, change tolisten 80and setvouch.cookie.securetofalse)
server{
listen443ssl http2;
server_nameprotectedapp.yourdomain;
root/var/www/html/;

ssl_certificate/etc/letsencrypt/live/protectedapp.yourdomain /fullchain.pem;
ssl_certificate_key/etc/letsencrypt/live/protectedapp.yourdomain /privkey.pem;

# send all requests to the `/validate` endpoint for authorization
auth_request/validate;

location= /validate{
# forward the /validate request to Vouch Proxy
proxy_passhttp://127.0.0.1:9090/validate;
# be sure to pass the original host header
proxy_set_headerHost$http_host;

# Vouch Proxy only acts on the request headers
proxy_pass_request_bodyoff;
proxy_set_headerContent-Length"";

# optionally add X-Vouch-User as returned by Vouch Proxy along with the request
auth_request_set$auth_resp_x_vouch_user$upstream_http_x_vouch_user;

# optionally add X-Vouch-IdP-Claims-* custom claims you are tracking
# auth_request_set $auth_resp_x_vouch_idp_claims_groups $upstream_http_x_vouch_idp_claims_groups;
# auth_request_set $auth_resp_x_vouch_idp_claims_given_name $upstream_http_x_vouch_idp_claims_given_name;
# optinally add X-Vouch-IdP-AccessToken or X-Vouch-IdP-IdToken
# auth_request_set $auth_resp_x_vouch_idp_accesstoken $upstream_http_x_vouch_idp_accesstoken;
# auth_request_set $auth_resp_x_vouch_idp_idtoken $upstream_http_x_vouch_idp_idtoken;

# these return values are used by the @error401 call
auth_request_set$auth_resp_jwt$upstream_http_x_vouch_jwt;
auth_request_set$auth_resp_err$upstream_http_x_vouch_err;
auth_request_set$auth_resp_failcount$upstream_http_x_vouch_failcount;

# Vouch Proxy can run behind the same Nginx reverse proxy
# may need to comply to "upstream" server naming
# proxy_pass http://vouch.yourdomain /validate;
# proxy_set_header Host $http_host;
}

# if validate returns `401 not authorized` then forward the request to the error401block
error_page401= @error401;

location@error401{
# redirect to Vouch Proxy for login
return302https://vouch.yourdomain /login?url=$scheme://$http_host$request_uri&vouch-failcount=$auth_resp_failcount&X-Vouch-Token=$auth_resp_jwt&error=$auth_resp_err;
# you usually *want* to redirect to Vouch running behind the same Nginx config proteced by https
# but to get started you can just forward the end user to the port that vouch is running on
# return 302 http://vouch.yourdomain:9090/login?url=$scheme://$http_host$request_uri&vouch-failcount=$auth_resp_failcount&X-Vouch-Token=$auth_resp_jwt&error=$auth_resp_err;
}

location/{
# forward authorized requests to your service protectedapp.yourdomain
proxy_passhttp://127.0.0.1:8080;
# you may need to set these variables in this block as per https://github /vouch/vouch-proxy/issues/26#issuecomment-425215810
# auth_request_set $auth_resp_x_vouch_user $upstream_http_x_vouch_user
# auth_request_set $auth_resp_x_vouch_idp_claims_groups $upstream_http_x_vouch_idp_claims_groups;
# auth_request_set $auth_resp_x_vouch_idp_claims_given_name $upstream_http_x_vouch_idp_claims_given_name;

# set user header (usually an email)
proxy_set_headerX-Vouch-User$auth_resp_x_vouch_user;
# optionally pass any custom claims you are tracking
# proxy_set_header X-Vouch-IdP-Claims-Groups $auth_resp_x_vouch_idp_claims_groups;
# proxy_set_header X-Vouch-IdP-Claims-Given_Name $auth_resp_x_vouch_idp_claims_given_name;
# optionally pass the accesstoken or idtoken
# proxy_set_header X-Vouch-IdP-AccessToken $auth_resp_x_vouch_idp_accesstoken;
# proxy_set_header X-Vouch-IdP-IdToken $auth_resp_x_vouch_idp_idtoken;
}
}

If Vouch is configured behind thesamenginx reverseproxy (perhaps so you can configure ssl) be sure to pass theHostheader properly, otherwise the JWT cookie cannot be set into the domain

server{
listen443ssl http2;
server_namevouch.yourdomain;
ssl_certificate/etc/letsencrypt/live/vouch.yourdomain /fullchain.pem;
ssl_certificate_key/etc/letsencrypt/live/vouch.yourdomain /privkey.pem;

location/{
proxy_passhttp://127.0.0.1:9090;
# be sure to pass the original host header
proxy_set_headerHost$http_host;
}
}

Vouch Proxy "in a path"

As ofv0.33.0Vouch Proxy can be served within an Nginx location (path) by configuringvouch.document_root: /vp_in_a_path

This avoids the need to setup a separate domain for Vouch Proxy such asvouch.yourdomain.For example VP login will be served fromhttps://protectedapp.yourdomain /vp_in_a_path/login

server{
listen443ssl http2;
server_nameprotectedapp.yourdomain;

ssl_certificate/etc/letsencrypt/live/protectedapp.yourdomain /fullchain.pem;
ssl_certificate_key/etc/letsencrypt/live/protectedapp.yourdomain /privkey.pem;

# This location serves all Vouch Proxy endpoints as /vp_in_a_path/$uri
# including /vp_in_a_path/validate, /vp_in_a_path/login, /vp_in_a_path/logout, /vp_in_a_path/auth, /vp_in_a_path/auth/$STATE, etc
location/vp_in_a_path{
proxy_passhttp://127.0.0.1:9090;# must not! have a slash at the end
proxy_set_headerHost$http_host;
proxy_pass_request_bodyoff;
proxy_set_headerContent-Length"";

# these return values are used by the @error401 call
auth_request_set$auth_resp_jwt$upstream_http_x_vouch_jwt;
auth_request_set$auth_resp_err$upstream_http_x_vouch_err;
auth_request_set$auth_resp_failcount$upstream_http_x_vouch_failcount;
}

# if /vp_in_a_path/validate returns `401 not authorized` then forward the request to the error401block
error_page401= @error401;

location@error401{
# redirect to Vouch Proxy for login
return302https://protectedapp.yourdomain /vp_in_a_path/login?url=$scheme://$http_host$request_uri&vouch-failcount=$auth_resp_failcount&X-Vouch-Token=$auth_resp_jwt&error=$auth_resp_err;
}

location/{
auth_request/vp_in_a_path/validate;
proxy_passhttp://127.0.0.1:8080;
# see the Nginx config above for additional headers which can be set from Vouch Proxy
}
}

Additional Nginx Configurations

Additional Nginx configurations can be found in theexamplesdirectory.

Configuring via Environmental Variables

Here's a minimal setup using Google's OAuth...

VOUCH_DOMAINS=yourdomain \
OAUTH_PROVIDER=google \
OAUTH_CLIENT_ID=1234 \
OAUTH_CLIENT_SECRET=secretsecret \
OAUTH_CALLBACK_URL=https://vouch.yourdomain /auth \
./vouch-proxy

Environmental variable names are documented inconfig/config.yml_example

All lists with multiple values must be comma separated:VOUCH_DOMAINS= "yourdomain,yourotherdomain"

The variableVOUCH_CONFIGcan be used to set an alternate location for the configuration file.VOUCH_ROOTcan be used to set an alternate root directory for Vouch Proxy to look for support files.

Tips, Tricks and Advanced Configurations

All Vouch Proxy configuration items are documented inconfig/config.yml_example

Please do help us to expand this list.

Scopes and Claims

With Vouch Proxy you can request variousscopes(standard and custom) to obtain more information about the user or gain access to the provider's APIs. Internally, Vouch Proxy launches a requests touser_info_urlafter successful authentication. The requiredclaimsare extracted from the provider's response and stored in the VP cookie.

⚠️Additional claims and tokens will be added to the VP cookie and can make it large

The VP cookie may be split into several cookies to accomdate browser cookie size limits. But if you need it, you need it. Large cookies and headers require Nginx to be configured with larger buffers. Seelarge_client_header_buffersandproxy_buffer_sizefor more information.

Setupscopesandclaimsin Vouch Proxy with Nginx

  1. Configure Vouch Proxy for Nginx and your IdP as normal (See:Installation and Configuration)

  2. Set the necessaryscopes in theoauthsection of the vouch-proxyconfig.yml(example config)

    1. setidtoken: X-Vouch-IdP-IdTokenin theheaderssection of vouch-proxy'sconfig.yml
    2. log in and call the/validateendpoint in a modern browser
    3. check the response header for aX-Vouch-IdP-IdTokenheader
    4. copy the value of the header into the debugger athttps://jwt.io/and ensure that the necessary claims are part of the jwt
    5. if they are not, you need to adjust thescopesin theoauthsection of yourconfig.ymlor reconfigure your oauth provider
  3. Set the necessaryclaimsin theheadersection of the vouch-proxyconfig.yml

    1. log in and call the/validateendpoint in a modern browser
    2. check the response headers for headers of the formX-Vouch-IdP-Claims-<ClaimName>
    3. If they are not there clear your cookies and cached browser data
    4. 🐞 If they are still not there but exist in the jwt (esp. custom claims) there might be a bug
    5. remove theidtoken: X-Vouch-IdP-IdTokenfrom theheaderssection of vouch-proxy'sconfig.ymlif you don't need it
  4. Useauth_request_setafterauth_requestinside the protected location in the nginxserver.conf

  5. Consume the claim (example nginx config)

Running from Docker

docker run -d \
-p 9090:9090 \
--name vouch-proxy \
-v${PWD}/config:/config \
quay.io/vouch/vouch-proxy

or

docker run -d \
-p 9090:9090 \
--name vouch-proxy \
-e VOUCH_DOMAINS=yourdomain \
-e OAUTH_PROVIDER=google \
-e OAUTH_CLIENT_ID=1234 \
-e OAUTH_CLIENT_SECRET=secretsecret \
-e OAUTH_CALLBACK_URL=https://vouch.yourdomain /auth \
quay.io/vouch/vouch-proxy

As ofv0.36.0the docker process in the container runs as uservouchwith UID 999 and GID 999. You may need to set the permissions of/config/config.ymland/config/secretto correspond to be readable by this user, or otherwise usedocker run --user $UID:$GID...or perhaps build the docker container from source and use the available ARGs for UID and GID.

Automated container builds for each Vouch Proxy release are available fromquay.io.Each release produces..

a minimal go binary container built fromDockerfile

  • quay.io/vouch/vouch-proxy:latest
  • quay.io/vouch/vouch-proxy:x.y.zsuch asquay.io/vouch/vouch-proxy:0.28.0

analpinebased container built fromDockerfile.alpine

  • quay.io/vouch/vouch-proxy:alpine-latest
  • quay.io/vouch/vouch-proxy:alpine-x.y.z

Vouch Proxyarmimages are available onDocker Hub

  • voucher/vouch-proxy:latest-arm

Kubernetes Nginx Ingress

If you are using kubernetes withnginx-ingress,you can configure your ingress with the following annotations (note quoting theauth-signinannotation):

nginx.ingress.kubernetes.io/auth-signin:"https://vouch.yourdomain /login?url=$scheme://$http_host$request_uri&vouch-failcount=$auth_resp_failcount&X-Vouch-Token=$auth_resp_jwt&error=$auth_resp_err"
nginx.ingress.kubernetes.io/auth-url: https://vouch.yourdomain /validate
nginx.ingress.kubernetes.io/auth-response-headers: X-Vouch-User
nginx.ingress.kubernetes.io/auth-snippet:|
#these return values are used by the @error401 call
auth_request_set$auth_resp_jwt$upstream_http_x_vouch_jwt;
auth_request_set$auth_resp_err$upstream_http_x_vouch_err;
auth_request_set$auth_resp_failcount$upstream_http_x_vouch_failcount;
#when VP is hosted externally to k8s ensure the SSL cert is valid to avoid MITM risk
#proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
#proxy_ssl_session_reuse on;
#proxy_ssl_verify_depth 2;
#proxy_ssl_verify on;

Helm Charts are maintained bypunkle,martina-ifandhalkeyeand are available athttps://github /vouch/helm-charts

Compiling from source and running the binary

./do.sh goget
./do.sh build
./vouch-proxy

As ofv0.29.0all templates, static assets and configuration defaults in.defaults.ymlare built into the static binary usinggo:embeddirectives.

/login and /logout endpoint redirection

As ofv0.11.0additional checks are in place to reducethe attack surface of url redirection.

/login?url=POST_LOGIN_URL

The passed URL...

  • must start with eitherhttporhttps
  • must have a domain overlap with either a domain in thevouch.domainslist or thevouch.cookie.domain(if either of those are configured)
  • cannot have a parameter which includes a URL toprevent URL chaining attacks

/logout?url=NEXT_URL

The Vouch Proxy/logoutendpoint accepts aurlparameter in the query string which can be used to302redirect a user to your orignal OAuth provider/IDP/OIDC provider'srevocation_endpoint

https://vouch.oursites /logout?url=https://oauth2.googleapis /revoke

this url must be present in the configuration file on the listvouch.post_logout_redirect_uris

#in order to prevent redirection attacks all redirected URLs to /logout must be specified
#the URL must still be passed to Vouch Proxy as https://vouch.yourdomain /logout?url=${ONE OF THE URLS BELOW}
post_logout_redirect_uris:
#your apps login page
-https://yourdomain /login
#your IdPs logout enpoint
#from https://accounts.google /.well-known/openid-configuration
-https://oauth2.googleapis /revoke
#you may be daisy chaining to your IdP
-https://myorg.okta /oauth2/123serverid/v1/logout?post_logout_redirect_uri=http://myapp.yourdomain /login

Note that your IdP will likely carry their own, separatepost_logout_redirect_urilist.

logout resources..

Troubleshooting, Support and Feature Requests (Read this before submitting an issue at GitHub)

Getting the stars to align between Nginx, Vouch Proxy and your IdP can be tricky. We want to help you get up and running as quickly as possible. The most common problem is..

I'm getting an infinite redirect loop which returns me to my IdP (Google/Okta/GitHub/...)

Double check that you are running Vouch Proxy and your apps on a common domain that can share cookies. For example,vouch.yourdomainandapp.yourdomaincan share cookies on the.yourdomaindomain. (It will not work if you are trying to usevouch.yourdomain.organdapp.yourdomain.net.)

You may need to explicitly define the domain that the cookie should be set on. You can do this in the config file by setting the option:

vouch:
cookie:
#force the domain of the cookie to set
domain:yourdomain

If you continue to have trouble, try the following:

  • turn onvouch.testing: true.This will slow down the loop.

  • setvouch.logLevel: debug.

  • theHost:header in the http request, theoauth.callback_urland the configuredvouch.domainsmust all align so that the cookie that carries the JWT can be placed properly into the browser and then returned on each request

  • it helps tothink like a cookie.

    • a cookie is set into a domain. If you havesiteA.yourdomainandsiteB.yourdomainprotected by Vouch Proxy, you want the Vouch Proxy cookie to be set into.yourdomain
    • if you authenticate tovouch.yourdomainthe cookie will not be able to be seen bydev.anythingelse
    • unless you are using https, you should setvouch.cookie.secure: false
    • cookiesareavailable to all ports of a domain
  • please see theissues which have been closed that mention redirect

Okay, I looked at the issues and have tried some things with my configs but it's still not working

Pleasesubmit a new issuein the following fashion..

TLDR:

  • setvouch.testing: true
  • setvouch.logLevel: debug
  • conduct two full round trips of./vouch-proxycapturing the output..
    • VP startup
    • /validate
    • /login- even if the error is here
    • /auth
    • /validate- capture everything
  • put all your logs and config in agist.
  • ./do.sh bug_reportis your friend

But read this anyways because we'll ask you to read it if you don't follow these instruction.:)

  • turn onvouch.testing: trueand setvouch.logLevel: debug.
  • use agistor anotherpaste servicesuch ashasteb.in.DO NOT PUT YOUR LOGS AND CONFIG INTO THE GITHUB ISSUE.Using a paste service is important as it will maintain spacing and will provide line numbers and formatting. We are hunting for needles in haystacks with setups with several moving parts, these features help considerably. Paste services save your time and our time and help us to help you quickly. You're more likely to get good support from us in a timely manner by following this advice.
  • run./do.sh bug_report secretdomain secretpass [anothersecret..]which will create a redacted version of your config and logs removing each of those strings
    • and follow the instructions at the end to redact your Nginx config
  • all of those go into agist
  • thenopen a new issuein this repository

A bug report can be generated from a docker environment using thequay.io/vouch/vouch-proxy:alpineimage...

docker run --name vouch_proxy -v $PWD/config:/config -v $PWD/certs:/certs -it --rm --entrypoint /do.sh quay.io/vouch/vouch-proxy:alpine bug_report yourdomain anotherdomain someothersecret

Contributing

We'd love to have you contribute! Please refer to ourcontribution guidelinesfor details.

Advanced Authorization Using OpenResty

OpenResty® is a full-fledged web platform that integrates the standard Nginx core, LuaJIT, many carefully written Lua libraries, lots of high quality 3rd-party Nginx modules, and most of their external dependencies.

You can replace nginx withOpenRestyfairly easily.

With OpenResty and Lua it is possible to provide customized and advanced authorization on any header or claims vouch passes down.

OpenResty and configs for a variety of scenarios are available in theexamplesdirectory.

The flow of login and authentication using Google Oauth

  • Bob visitshttps://private.oursites

  • the Nginx reverse proxy...

    • recieves the request for private.oursites from Bob
    • uses theauth_requestmodule configured for the/validatepath
    • /validateis configured toproxy_passrequests to the authentication service athttps://vouch.oursites /validate
      • if/validatereturns...
        • 200 OK then SUCCESS allow Bob through
        • 401 NotAuthorized then
          • respond to Bob with a 302 redirect tohttps://vouch.oursites /login?url=https://private.oursites
  • Vouch Proxyhttps://vouch.oursites /validate

    • recieves the request for private.oursites from Bob via Nginxproxy_pass
    • looks for a cookie named "oursitesSSO" that contains a JWT
    • if the cookie is found, and the JWT is valid
      • returns200 OKto Nginx, which will allow access (bob notices nothing)
    • if the cookie is NOT found, or the JWT is NOT valid
      • return401 NotAuthorizedto Nginx (which forwards the request on to login)
  • Bob is first forwarded briefly tohttps://vouch.oursites /login?url=https://private.oursites

    • clears out the cookie named "oursitesSSO" if it exists
    • generates a nonce and stores it in session variable $STATE
    • stores the urlhttps://private.oursitesfrom the query string in session variable$requestedURL
    • respond to Bob with a 302 redirect to Google's OAuth Login form, including the$STATEnonce
  • Bob logs into his Google account using Oauth

    • after successful login
    • Google responds to Bob with a 302 redirect tohttps://vouch.oursites /auth?state=$STATE
  • Bob is forwarded tohttps://vouch.oursites /auth?state=$STATE

    • if the $STATE nonce from the url matches the session variable "state"
    • make a "third leg" request of Google (server to server) to exchange the OAuth code for Bob's user info including email addressbob@oursites
    • if the email address matches the domain oursites (it does)
      • issue bob a JWT in the form of a cookie named "oursitesSSO"
      • retrieve the session variable$requestedURLand 302 redirect bob back tohttps://private.oursites

Note that outside of some innocuos redirection, Bob only ever seeshttps://private.oursitesand the Google Login screen in his browser. While Vouch does interact with Bob's browser several times, it is just to set cookies, and if the 302 redirects work properly Bob will log in quickly.

Once the JWT is set, Bob will be authorized for all other sites which are configured to usehttps://vouch.oursites /validatefrom theauth_requestNginx module.

The next time Bob is forwarded to google for login, since he has already authorized the Vouch Proxy OAuth app, Google immediately forwards him back and sets the cookie and sends him on his merry way. In some browsers such as Chrome, Bob may not even notice that he logged in using Vouch Proxy.