1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2024-11-24 08:52:25 +02:00

Merge pull request #1119 from oauth2-proxy/release-7.1.0

Prepare for release v7.1.0
This commit is contained in:
Joel Speed 2021-03-25 17:24:36 +00:00 committed by GitHub
commit 333418983c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 1734 additions and 9 deletions

View File

@ -4,6 +4,26 @@
## Important Notes
## Breaking Changes
## Changes since v7.1.0
# V7.1.0
## Release Highlights
- New improved design for sign in and error pages based on bulma framework
- Refactored templates loading
- `robots.txt`, `sign_in.html` and `error.html` can now be provided individually in `--custom-templates-dir`
- If any of the above are not provided, defaults are used
- Defaults templates be found in [pkg/app/pagewriter](https://github.com/oauth2-proxy/oauth2-proxy/tree/v7.1.0/pkg/app/pagewriter)
- Introduction of basic prometheus metrics
- Introduction of Traefik based local testing/example environment
- Support for request IDs to allow request co-ordination of log lines
## Important Notes
- [GHSA-652x-m2gr-hppm](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-652x-m2gr-hppm) GitLab group authorization stopped working in v7.0.0, the functionality has now been restored, please see the linked advisory for details
- [#1103](https://github.com/oauth2-proxy/oauth2-proxy/pull/1103) Upstream request signatures via `--signature-key` is
deprecated. Support will be removed completely in v8.0.0.
- [1087](https://github.com/oauth2-proxy/oauth2-proxy/pull/1087) The default logging templates have been updated to include {{.RequestID}}
@ -14,15 +34,19 @@
## Breaking Changes
N/A
## Changes since v7.0.1
- [GHSA-652x-m2gr-hppm](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-652x-m2gr-hppm) `--gitlab-group` GitLab Group Authorization config flag stopped working in v7.0.0 (@NickMeves, @papey)
- [#1113](https://github.com/oauth2-proxy/oauth2-proxy/pull/1113) Panic with GitLab project repository auth (@piersharding)
- [#1116](https://github.com/oauth2-proxy/oauth2-proxy/pull/1116) Reinstate preferEmailToUser behaviour for basic auth sessions (@JoelSpeed)
- [#1115](https://github.com/oauth2-proxy/oauth2-proxy/pull/1115) Fix upstream proxy appending ? to requests (@JoelSpeed)
- [#1117](https://github.com/oauth2-proxy/oauth2-proxy/pull/1117) Deprecate GCP HealthCheck option (@JoelSpeed)
- [#1117](https://github.com/oauth2-proxy/oauth2-proxy/pull/1117) Deprecate GCP HealthCheck option (@JoelSpeed)
- [#1104](https://github.com/oauth2-proxy/oauth2-proxy/pull/1104) Allow custom robots text pages (@JoelSpeed)
- [#1045](https://github.com/oauth2-proxy/oauth2-proxy/pull/1045) Ensure redirect URI always has a scheme (@JoelSpeed)
- [#1103](https://github.com/oauth2-proxy/oauth2-proxy/pull/1103) Deprecate upstream request signatures (@NickMeves)
- [1087](https://github.com/oauth2-proxy/oauth2-proxy/pull/1087) Support Request ID in logging (@NickMeves)
- [#1087](https://github.com/oauth2-proxy/oauth2-proxy/pull/1087) Support Request ID in logging (@NickMeves)
- [#914](https://github.com/oauth2-proxy/oauth2-proxy/pull/914) Extract email from id_token for azure provider when oidc is configured (@weinong)
- [#1047](https://github.com/oauth2-proxy/oauth2-proxy/pull/1047) Refactor HTTP Server and add ServerGroup to handle graceful shutdown of multiple servers (@JoelSpeed)
- [#1070](https://github.com/oauth2-proxy/oauth2-proxy/pull/1070) Refactor logging middleware to middleware package (@NickMeves)
@ -34,9 +58,9 @@
- [#1029](https://github.com/oauth2-proxy/oauth2-proxy/pull/1029) Refactor error page rendering and allow debug messages on error (@JoelSpeed)
- [#1028](https://github.com/oauth2-proxy/oauth2-proxy/pull/1028) Refactor templates, update theme and provide styled error pages (@JoelSpeed)
- [#1039](https://github.com/oauth2-proxy/oauth2-proxy/pull/1039) Ensure errors in tests are logged to the GinkgoWriter (@JoelSpeed)
- [#980](https://github.com/oauth2-proxy/oauth2-proxy/pull/980) Add Prometheus metrics endpoint
- [#1023](https://github.com/oauth2-proxy/oauth2-proxy/pull/1023) Update docs on Traefik ForwardAuth support without the use of Traefik 'errors' middleware
- [#1091](https://github.com/oauth2-proxy/oauth2-proxy/pull/1091) Add an example with Traefik (configuration without Traefik 'errors' middleware)
- [#980](https://github.com/oauth2-proxy/oauth2-proxy/pull/980) Add Prometheus metrics endpoint (@neuralsandwich)
- [#1023](https://github.com/oauth2-proxy/oauth2-proxy/pull/1023) Update docs on Traefik ForwardAuth support without the use of Traefik 'errors' middleware (@pcneo83)
- [#1091](https://github.com/oauth2-proxy/oauth2-proxy/pull/1091) Add an example with Traefik (configuration without Traefik 'errors' middleware) (@fcollonval)
# V7.0.1

View File

@ -23,7 +23,7 @@ Going forward, all images shall be available at `quay.io/oauth2-proxy/oauth2-pro
1. Choose how to deploy:
a. Download [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.0.1`)
a. Download [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.1.0`)
b. Build with `$ go get github.com/oauth2-proxy/oauth2-proxy` which will put the binary in `$GOROOT/bin`

View File

@ -15,7 +15,7 @@ services:
oauth2-proxy:
container_name: oauth2-proxy
image: quay.io/oauth2-proxy/oauth2-proxy:v7.0.1
image: quay.io/oauth2-proxy/oauth2-proxy:v7.1.0
command: --config /oauth2-proxy.cfg
hostname: oauth2-proxy
volumes:

View File

@ -13,7 +13,7 @@ version: '3.0'
services:
oauth2-proxy:
container_name: oauth2-proxy
image: quay.io/oauth2-proxy/oauth2-proxy:v7.0.1
image: quay.io/oauth2-proxy/oauth2-proxy:v7.1.0
command: --config /oauth2-proxy.cfg
ports:
- 4180:4180/tcp

View File

@ -6,7 +6,7 @@ slug: /
1. Choose how to deploy:
a. Download [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.0.1`)
a. Download [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.1.0`)
b. Build with `$ go get github.com/oauth2-proxy/oauth2-proxy/v7` which will put the binary in `$GOPATH/bin`

View File

@ -0,0 +1,11 @@
---
id: behaviour
title: Behaviour
---
1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`).
2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned)
3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set
4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration)
Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md).

View File

@ -0,0 +1,49 @@
---
id: security
title: Security
---
:::note
OAuth2 Proxy is a community project.
Maintainers do not work on this project full time, and as such,
while we endeavour to respond to disclosures as quickly as possible,
this may take longer than in projects with corporate sponsorship.
:::
## Security Disclosures
:::important
If you believe you have found a vulnerability within OAuth2 Proxy or any of its
dependencies, please do NOT open an issue or PR on GitHub, please do NOT post
any details publicly.
:::
Security disclosures MUST be done in private.
If you have found an issue that you would like to bring to the attention of the
maintenance team for OAuth2 Proxy, please compose an email and send it to the
list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file.
Please include as much detail as possible.
Ideally, your disclosure should include:
- A reproducible case that can be used to demonstrate the exploit
- How you discovered this vulnerability
- A potential fix for the issue (if you have thought of one)
- Versions affected (if not present in master)
- Your GitHub ID
### How will we respond to disclosures?
We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories)
to privately discuss fixes for disclosed vulnerabilities.
If you include a GitHub ID with your disclosure we will add you as a collaborator
for the advisory so that you can join the discussion and validate any fixes
we may propose.
For minor issues and previously disclosed vulnerabilities (typically for
dependencies), we may use regular PRs for fixes and forego the security advisory.
Once a fix has been agreed upon, we will merge the fix and create a new release.
If we have multiple security issues in flight simultaneously, we may delay
merging fixes until all patches are ready.
We may also backport the fix to previous releases,
but this will be at the discretion of the maintainers.

View File

@ -0,0 +1,237 @@
---
id: alpha-config
title: Alpha Configuration
---
:::warning
This page contains documentation for alpha features.
We reserve the right to make breaking changes to the features detailed within this page with no notice.
Options described in this page may be changed, removed, renamed or moved without prior warning.
Please beware of this before you use alpha configuration options.
:::
This page details a set of **alpha** configuration options in a new format.
Going forward we are intending to add structured configuration in YAML format to
replace the existing TOML based configuration file and flags.
Below is a reference for the structure of the configuration, with
[AlphaOptions](#alphaoptions) as the root of the configuration.
When using alpha configuration, your config file will look something like below:
```yaml
upstreams:
- id: ...
...
injectRequestHeaders:
- name: ...
...
injectResponseHeaders:
- name: ...
...
```
Please browse the [reference](#configuration-reference) below for the structure
of the new configuration format.
## Using Alpha Configuration
To use the new **alpha** configuration, generate a YAML file based on the format
described in the [reference](#configuration-reference) below.
Provide the path to this file using the `--alpha-config` flag.
:::note
When using the `--alpha-config` flag, some options are no longer available.
See [removed options](#removed-options) below for more information.
:::
### Converting configuration to the new structure
Before adding the new `--alpha-config` option, start OAuth2 Proxy using the
`convert-config-to-alpha` flag to convert existing configuration to the new format.
```bash
oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg
```
This will convert any options supported by the new format to YAML and print the
new configuration to `STDOUT`.
Copy this to a new file, remove any options from your existing configuration
noted in [removed options](#removed-options) and then start OAuth2 Proxy using
the new config.
```bash
oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
```
## Removed options
The following flags/options and their respective environment variables are no
longer available when using alpha configuration:
<!-- Legacy Upstream FlagSet -->
- `flush-interval`/`flush_interval`
- `pass-host-header`/`pass_host_header`
- `proxy-websockets`/`proxy_websockets`
- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify`
- `upstream`/`upstreams`
<!-- Legacy Headers FlagSet -->
- `pass-basic-auth`/`pass_basic_auth`
- `pass-access-token`/`pass_access_token`
- `pass-user-headers`/`pass_user_headers`
- `pass-authorization-header`/`pass_authorization_header`
- `set-basic-auth`/`set_basic_auth`
- `set-xauthrequest`/`set_xauthrequest`
- `set-authorization-header`/`set_authorization_header`
- `prefer-email-to-user`/`prefer_email_to_user`
- `basic-auth-password`/`basic_auth_password`
- `skip-auth-strip-headers`/`skip_auth_strip_headers`
Attempting to use these options via flags or via config when `--alpha-config`
set will result in an error.
:::important
You must remove these options before starting OAuth2 Proxy with `--alpha-config`
:::
## Configuration Reference
<!--- THIS FILE IS AUTOGENERATED!!! DO NOT EDIT!!! -->
### AlphaOptions
AlphaOptions contains alpha structured configuration options.
Usage of these options allows users to access alpha features that are not
available as part of the primary configuration structure for OAuth2 Proxy.
:::warning
The options within this structure are considered alpha.
They may change between releases without notice.
:::
| Field | Type | Description |
| ----- | ---- | ----------- |
| `upstreams` | _[Upstreams](#upstreams)_ | Upstreams is used to configure upstream servers.<br/>Once a user is authenticated, requests to the server will be proxied to<br/>these upstream servers based on the path mappings defined in this list. |
| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added<br/>to requests to upstream servers.<br/>Headers may source values from either the authenticated user's session<br/>or from a static secret value. |
| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added<br/>to responses from the proxy.<br/>This is typically used when using the proxy as an external authentication<br/>provider in conjunction with another proxy such as NGINX and its<br/>auth_request module.<br/>Headers may source values from either the authenticated user's session<br/>or from a static secret value. |
| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.<br/>You may choose to run both HTTP and HTTPS servers simultaneously.<br/>This can be done by setting the BindAddress and the SecureBindAddress simultaneously.<br/>To use the secure server you must configure a TLS certificate and key. |
| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.<br/>You may choose to run both HTTP and HTTPS servers simultaneously.<br/>This can be done by setting the BindAddress and the SecureBindAddress simultaneously.<br/>To use the secure server you must configure a TLS certificate and key. |
### ClaimSource
(**Appears on:** [HeaderValue](#headervalue))
ClaimSource allows loading a header value from a claim within the session
| Field | Type | Description |
| ----- | ---- | ----------- |
| `claim` | _string_ | Claim is the name of the claim in the session that the value should be<br/>loaded from. |
| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the<br/>claim if it is non-empty. |
| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.<br/>Note the value of claim will become the basic auth username and the<br/>basicAuthPassword will be used as the password value. |
### Duration
#### (`string` alias)
(**Appears on:** [Upstream](#upstream))
Duration is as string representation of a period of time.
A duration string is a is a possibly signed sequence of decimal numbers,
each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
### Header
(**Appears on:** [AlphaOptions](#alphaoptions))
Header represents an individual header that will be added to a request or
response header.
| Field | Type | Description |
| ----- | ---- | ----------- |
| `name` | _string_ | Name is the header name to be used for this set of values.<br/>Names should be unique within a list of Headers. |
| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header<br/>should be preserved for the request to the upstream server.<br/>This option only takes effet on injected request headers.<br/>Defaults to false (headers that match this header will be stripped). |
| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header |
### HeaderValue
(**Appears on:** [Header](#header))
HeaderValue represents a single header value and the sources that can
make up the header value
| Field | Type | Description |
| ----- | ---- | ----------- |
| `value` | _[]byte_ | Value expects a base64 encoded string value. |
| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. |
| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. |
| `claim` | _string_ | Claim is the name of the claim in the session that the value should be<br/>loaded from. |
| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the<br/>claim if it is non-empty. |
| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.<br/>Note the value of claim will become the basic auth username and the<br/>basicAuthPassword will be used as the password value. |
### SecretSource
(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls))
SecretSource references an individual secret value.
Only one source within the struct should be defined at any time.
| Field | Type | Description |
| ----- | ---- | ----------- |
| `value` | _[]byte_ | Value expects a base64 encoded string value. |
| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. |
| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. |
### Server
(**Appears on:** [AlphaOptions](#alphaoptions))
Server represents the configuration for an HTTP(S) server
| Field | Type | Description |
| ----- | ---- | ----------- |
| `BindAddress` | _string_ | BindAddress is the the address on which to serve traffic.<br/>Leave blank or set to "-" to disable. |
| `SecureBindAddress` | _string_ | SecureBindAddress is the the address on which to serve secure traffic.<br/>Leave blank or set to "-" to disable. |
| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the<br/>secure traffic. |
### TLS
(**Appears on:** [Server](#server))
TLS contains the information for loading a TLS certifcate and key.
| Field | Type | Description |
| ----- | ---- | ----------- |
| `Key` | _[SecretSource](#secretsource)_ | Key is the the TLS key data to use.<br/>Typically this will come from a file. |
| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.<br/>Typically this will come from a file. |
### Upstream
(**Appears on:** [Upstreams](#upstreams))
Upstream represents the configuration for an upstream server.
Requests will be proxied to this upstream if the path matches the request path.
| Field | Type | Description |
| ----- | ---- | ----------- |
| `id` | _string_ | ID should be a unique identifier for the upstream.<br/>This value is required for all upstreams. |
| `path` | _string_ | Path is used to map requests to the upstream server.<br/>The closest match will take precedence and all Paths must be unique. |
| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File<br/>based URL. It may include a path, in which case all requests will be served<br/>under that path.<br/>Eg:<br/>- http://localhost:8080<br/>- https://service.localhost<br/>- https://service.localhost/path<br/>- file://host/path<br/>If the URI's path is "/base" and the incoming request was for "/dir",<br/>the upstream request will be for "/base/dir". |
| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.<br/>This option is insecure and will allow potential Man-In-The-Middle attacks<br/>betweem OAuth2 Proxy and the usptream server.<br/>Defaults to false. |
| `static` | _bool_ | Static will make all requests to this upstream have a static response.<br/>The response will have a body of "Authenticated" and a response code<br/>matching StaticCode.<br/>If StaticCode is not set, the response will return a 200 response. |
| `staticCode` | _int_ | StaticCode determines the response code for the Static response.<br/>This option can only be used with Static enabled. |
| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when<br/>streaming response from the upstream.<br/>Defaults to 1 second. |
| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied<br/>to the upstream server.<br/>Defaults to true. |
| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers<br/>Defaults to true. |
### Upstreams
#### ([[]Upstream](#upstream) alias)
(**Appears on:** [AlphaOptions](#alphaoptions))
Upstreams is a collection of definitions for upstream servers.

View File

@ -0,0 +1,101 @@
---
id: alpha-config
title: Alpha Configuration
---
:::warning
This page contains documentation for alpha features.
We reserve the right to make breaking changes to the features detailed within this page with no notice.
Options described in this page may be changed, removed, renamed or moved without prior warning.
Please beware of this before you use alpha configuration options.
:::
This page details a set of **alpha** configuration options in a new format.
Going forward we are intending to add structured configuration in YAML format to
replace the existing TOML based configuration file and flags.
Below is a reference for the structure of the configuration, with
[AlphaOptions](#alphaoptions) as the root of the configuration.
When using alpha configuration, your config file will look something like below:
```yaml
upstreams:
- id: ...
...
injectRequestHeaders:
- name: ...
...
injectResponseHeaders:
- name: ...
...
```
Please browse the [reference](#configuration-reference) below for the structure
of the new configuration format.
## Using Alpha Configuration
To use the new **alpha** configuration, generate a YAML file based on the format
described in the [reference](#configuration-reference) below.
Provide the path to this file using the `--alpha-config` flag.
:::note
When using the `--alpha-config` flag, some options are no longer available.
See [removed options](#removed-options) below for more information.
:::
### Converting configuration to the new structure
Before adding the new `--alpha-config` option, start OAuth2 Proxy using the
`convert-config-to-alpha` flag to convert existing configuration to the new format.
```bash
oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg
```
This will convert any options supported by the new format to YAML and print the
new configuration to `STDOUT`.
Copy this to a new file, remove any options from your existing configuration
noted in [removed options](#removed-options) and then start OAuth2 Proxy using
the new config.
```bash
oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
```
## Removed options
The following flags/options and their respective environment variables are no
longer available when using alpha configuration:
<!-- Legacy Upstream FlagSet -->
- `flush-interval`/`flush_interval`
- `pass-host-header`/`pass_host_header`
- `proxy-websockets`/`proxy_websockets`
- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify`
- `upstream`/`upstreams`
<!-- Legacy Headers FlagSet -->
- `pass-basic-auth`/`pass_basic_auth`
- `pass-access-token`/`pass_access_token`
- `pass-user-headers`/`pass_user_headers`
- `pass-authorization-header`/`pass_authorization_header`
- `set-basic-auth`/`set_basic_auth`
- `set-xauthrequest`/`set_xauthrequest`
- `set-authorization-header`/`set_authorization_header`
- `prefer-email-to-user`/`prefer_email_to_user`
- `basic-auth-password`/`basic_auth_password`
- `skip-auth-strip-headers`/`skip_auth_strip_headers`
Attempting to use these options via flags or via config when `--alpha-config`
set will result in an error.
:::important
You must remove these options before starting OAuth2 Proxy with `--alpha-config`
:::
## Configuration Reference

View File

@ -0,0 +1,510 @@
---
id: oauth_provider
title: OAuth Provider Configuration
---
You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on.
Valid providers are :
- [Google](#google-auth-provider) _default_
- [Azure](#azure-auth-provider)
- [Facebook](#facebook-auth-provider)
- [GitHub](#github-auth-provider)
- [Keycloak](#keycloak-auth-provider)
- [GitLab](#gitlab-auth-provider)
- [LinkedIn](#linkedin-auth-provider)
- [Microsoft Azure AD](#microsoft-azure-ad-provider)
- [OpenID Connect](#openid-connect-provider)
- [login.gov](#logingov-provider)
- [Nextcloud](#nextcloud-provider)
- [DigitalOcean](#digitalocean-auth-provider)
- [Bitbucket](#bitbucket-auth-provider)
- [Gitea](#gitea-auth-provider)
The provider can be selected using the `provider` configuration value.
Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the OpenID Connect provider.
### Google Auth Provider
For Google, the registration steps are:
1. Create a new project: https://console.developers.google.com/project
2. Choose the new project from the top right project dropdown (only if another project is selected)
3. In the project Dashboard center pane, choose **"API Manager"**
4. In the left Nav pane, choose **"Credentials"**
5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save.
6. In the center pane, choose **"Credentials"** tab.
- Open the **"New credentials"** drop down
- Choose **"OAuth client ID"**
- Choose **"Web application"**
- Application name is freeform, choose something appropriate
- Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com`
- Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback`
- Choose **"Create"**
7. Take note of the **Client ID** and **Client Secret**
It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the account is still authorized.
#### Restrict auth to specific Google groups on your domain. (optional)
1. Create a service account: https://developers.google.com/identity/protocols/OAuth2ServiceAccount and make sure to download the json file.
2. Make note of the Client ID for a future step.
3. Under "APIs & Auth", choose APIs.
4. Click on Admin SDK and then Enable API.
5. Follow the steps on https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account and give the client id from step 2 the following oauth scopes:
```
https://www.googleapis.com/auth/admin.directory.group.readonly
https://www.googleapis.com/auth/admin.directory.user.readonly
```
6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access.
7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from step 5 for the reason why.
8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances of this flag with different groups
and the user will be checked against all the provided groups.
9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and set the path to the file in the `google-service-account-json` flag.
10. Restart oauth2-proxy.
Note: The user is checked against the group members list on initial authentication and every time the token is refreshed ( about once an hour ).
### Azure Auth Provider
1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **"Azure Active Directory"** in the left menu, select **"App registrations"** and then click on **"New app registration"**.
2. Pick a name and choose **"Webapp / API"** as application type. Use `https://internal.yourcompany.com` as Sign-on URL. Click **"Create"**.
3. On the **"Settings"** / **"Properties"** page of the app, pick a logo and select **"Multi-tenanted"** if you want to allow users from multiple organizations to access your app. Note down the application ID. Click **"Save"**.
4. On the **"Settings"** / **"Required Permissions"** page of the app, click on **"Windows Azure Active Directory"** and then on **"Access the directory as the signed in user"**. Hit **"Save"** and then then on **"Grant permissions"** (you might need another admin to do this).
5. On the **"Settings"** / **"Reply URLs"** page of the app, add `https://internal.yourcompanycom/oauth2/callback` for each host that you want to protect by the oauth2 proxy. Click **"Save"**.
6. On the **"Settings"** / **"Keys"** page of the app, add a new key and note down the value after hitting **"Save"**.
7. Configure the proxy with
```
--provider=azure
--client-id=<application ID from step 3>
--client-secret=<value from step 6>
```
Note: When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the [redis session storage](sessions.md#redis-storage) should resolve this.
### Facebook Auth Provider
1. Create a new FB App from <https://developers.facebook.com/>
2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback`
### GitHub Auth Provider
1. Create a new project: https://github.com/settings/developers
2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback`
The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`
NOTE: When `--github-user` is set, the specified users are allowed to login even if they do not belong to the specified org and team or collaborators.
To restrict by organization only, include the following flag:
-github-org="": restrict logins to members of this organisation
To restrict within an organization to specific teams, include the following flag in addition to `-github-org`:
-github-team="": restrict logins to members of any of these teams (slug), separated by a comma
If you would rather restrict access to collaborators of a repository, those users must either have push access to a public repository or any access to a private repository:
-github-repo="": restrict logins to collaborators of this repository formatted as orgname/repo
If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a [token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be created with at least the `public_repo` scope:
-github-token="": the token to use when verifying repository collaborators
To allow a user to login with their username even if they do not belong to the specified org and team or collaborators, separated by a comma
-github-user="": allow logins by username, separated by a comma
If you are using GitHub enterprise, make sure you set the following to the appropriate url:
-login-url="http(s)://<enterprise github host>/login/oauth/authorize"
-redeem-url="http(s)://<enterprise github host>/login/oauth/access_token"
-validate-url="http(s)://<enterprise github host>/api/v3"
### Keycloak Auth Provider
1. Create new client in your Keycloak with **Access Type** 'confidental' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback'
2. Take note of the Secret in the credential tab of the client
3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'.
Make sure you set the following to the appropriate url:
--provider=keycloak
--client-id=<client you have created>
--client-secret=<your client's secret>
--login-url="http(s)://<keycloak host>/auth/realms/<your realm>/protocol/openid-connect/auth"
--redeem-url="http(s)://<keycloak host>/auth/realms/<your realm>/protocol/openid-connect/token"
--profile-url="http(s)://<keycloak host>/auth/realms/<your realm>/protocol/openid-connect/userinfo"
--validate-url="http(s)://<keycloak host>/auth/realms/<your realm>/protocol/openid-connect/userinfo"
--keycloak-group=<first_allowed_user_group>
--keycloak-group=<second_allowed_user_group>
For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard)
flags can be used to specify which groups to limit access to.
If these are unset but a `groups` mapper is set up above in step (3), the provider will still
populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the
Keycloak userinfo endpoint response.
The group management in keycloak is using a tree. If you create a group named admin in keycloak
you should define the 'keycloak-group' value to /admin.
### GitLab Auth Provider
This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)).
Whether you are using GitLab.com or self-hosting GitLab, follow [these steps to add an application](https://docs.gitlab.com/ce/integration/oauth_provider.html). Make sure to enable at least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. https://myapp.com/oauth2/callback.
If you need projects filtering, add the extra `read_api` scope to your application.
The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow [these steps](./overview.md#generating-a-cookie-secret)
```
--provider="gitlab"
--redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab
--client-id=GITLAB_CLIENT_ID
--client-secret=GITLAB_CLIENT_SECRET
--cookie-secret=COOKIE_SECRET
```
Restricting by group membership is possible with the following option:
--gitlab-group="mygroup,myothergroup": restrict logins to members of any of these groups (slug), separated by a comma
If you are using self-hosted GitLab, make sure you set the following to the appropriate URL:
--oidc-issuer-url="<your gitlab url>"
### LinkedIn Auth Provider
For LinkedIn, the registration steps are:
1. Create a new project: https://www.linkedin.com/secure/developer
2. In the OAuth User Agreement section:
- In default scope, select r_basicprofile and r_emailaddress.
- In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback`
3. Fill in the remaining required fields and Save.
4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key**
### Microsoft Azure AD Provider
For adding an application to the Microsoft Azure AD follow [these steps to add an application](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app).
Take note of your `TenantId` if applicable for your situation. The `TenantId` can be used to override the default `common` authorization server with a tenant specific server.
### OpenID Connect Provider
OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects.
This provider was originally built against CoreOS Dex and we will use it as an example.
The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below.
#### Dex
To configure the OIDC provider for Dex, perform the following steps:
1. Download Dex:
```
go get github.com/dexidp/dex
```
See the [getting started guide](https://github.com/coreos/dex/blob/master/Documentation/getting-started.md) for more details.
2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to the `staticClients` section of `examples/config-dev.yaml`:
```
- id: oauth2-proxy
redirectURIs:
- 'http://127.0.0.1:4180/oauth2/callback'
name: 'oauth2-proxy'
secret: proxy
```
3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run:
```
bin/dex serve examples/config-dev.yaml
```
4. In a second terminal, run the oauth2-proxy with the following args:
```
-provider oidc
-provider-display-name "My OIDC Provider"
-client-id oauth2-proxy
-client-secret proxy
-redirect-url http://127.0.0.1:4180/oauth2/callback
-oidc-issuer-url http://127.0.0.1:5556/dex
-cookie-secure=false
-cookie-secret=secret
-email-domain kilgore.trout
```
To serve the current working directory as a web site under the `/static` endpoint, add:
```
-upstream file://$PWD/#/static/
```
5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static .
See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex.
#### Okta
To configure the OIDC provider for Okta, perform the following steps:
1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com`
2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications,
you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work.
* Navigate to **Security** then select **API**
* Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom authorization server.
* Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'.
* For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com
* Fill out a **Description**
* Add any **Access Policies** you wish to configure to limit application access.
* The default settings will work for other options.
[See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/)
3. Navigate to **Applications** then select **Add Application**.
* Select **Web** for the **Platform** setting.
* Select **OpenID Connect** and click **Create**
* Pick an **Application Name** such as `Example App`.
* Set the **Login redirect URI** to `https://example.corp.com`.
* Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`.
* Leave the rest as default, taking note of the `Client ID` and `Client Secret`.
* Under **Assignments** select the users or groups you wish to access your application.
4. Create a configuration file like the following:
```
provider = "oidc"
redirect_url = "https://example.corp.com/oauth2/callback"
oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234"
upstreams = [
"https://example.corp.com"
]
email_domains = [
"corp.com"
]
client_id = "XXXXX"
client_secret = "YYYYY"
pass_access_token = true
cookie_secret = "ZZZZZ"
skip_provider_button = true
```
The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply https://corp.okta.com .
The `client_id` and `client_secret` are configured in the application settings.
Generate a unique `client_secret` to encrypt the cookie.
Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg`
#### Okta - localhost
1. Signup for developer account: https://developer.okta.com/signup/
2. Create New `Web` Application: https://${your-okta-domain}/dev/console/apps/new
3. Example Application Settings for localhost:
* **Name:** My Web App
* **Base URIs:** http://localhost:4180/
* **Login redirect URIs:** http://localhost:4180/oauth2/callback
* **Logout redirect URIs:** http://localhost:4180/
* **Group assignments:** `Everyone`
* **Grant type allowed:** `Authorization Code` and `Refresh Token`
4. Make note of the `Client ID` and `Client secret`, they are needed in a future step
5. Make note of the **default** Authorization Server Issuer URI from: https://${your-okta-domain}/admin/oauth2/as
6. Example config file `/etc/localhost.cfg`
```
provider = "oidc"
redirect_url = "http://localhost:4180/oauth2/callback"
oidc_issuer_url = "https://${your-okta-domain}/oauth2/default"
upstreams = [
"http://0.0.0.0:8080"
]
email_domains = [
"*"
]
client_id = "XXX"
client_secret = "YYY"
pass_access_token = true
cookie_secret = "ZZZ"
cookie_secure = false
skip_provider_button = true
# Note: use the following for testing within a container
# http_address = "0.0.0.0:4180"
```
7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg`
### login.gov Provider
login.gov is an OIDC provider for the US Government.
If you are a US Government agency, you can contact the login.gov team through the contact information
that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov
accounts for integration/test and production access.
A developer guide is available here: https://developers.login.gov/, though this proxy handles everything
but the data you need to create to register your application in the login.gov dashboard.
As a demo, we will assume that you are running your application that you want to secure locally on
http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that
you have an agency integration account for testing.
First, register your application in the dashboard. The important bits are:
* Identity protocol: make this `Openid connect`
* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`.
* Public key: This is a self-signed certificate in .pem format generated from a 2048 bit RSA private key.
A quick way to do this is `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`,
The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`.
* Return to App URL: Make this be `http://localhost:4180/`
* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`.
* Attribute Bundle: Make sure that email is selected.
Now start the proxy up with the following options:
```
./oauth2-proxy -provider login.gov \
-client-id=${LOGINGOV_ISSUER} \
-redirect-url=http://localhost:4180/oauth2/callback \
-oidc-issuer-url=https://idp.int.identitysandbox.gov/ \
-cookie-secure=false \
-email-domain=gsa.gov \
-upstream=http://localhost:3000/ \
-cookie-secret=somerandomstring12341234567890AB \
-cookie-domain=localhost \
-skip-provider-button=true \
-pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \
-profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \
-jwt-key="${OAUTH2_PROXY_JWT_KEY}"
```
You can also set all these options with environment variables, for use in cloud/docker environments.
One tricky thing that you may encounter is that some cloud environments will pass in environment
variables in a docker env-file, which does not allow multiline variables like a PEM file.
If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level
directory of the repo which contains the key in PEM format and then do your docker build.
The docker build process will copy that file into your image which you can then access by
setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem`
environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline.
Once it is running, you should be able to go to `http://localhost:4180/` in your browser,
get authenticated by the login.gov integration server, and then get proxied on to your
application running on `http://localhost:3000/`. In a real deployment, you would secure
your application with a firewall or something so that it was only accessible from the
proxy, and you would use real hostnames everywhere.
#### Skip OIDC discovery
Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, token and jwks URI endpoints from the provider's metadata.
In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually:
```
-provider oidc
-client-id oauth2-proxy
-client-secret proxy
-redirect-url http://127.0.0.1:4180/oauth2/callback
-oidc-issuer-url http://127.0.0.1:5556
-skip-oidc-discovery
-login-url http://127.0.0.1:5556/authorize
-redeem-url http://127.0.0.1:5556/token
-oidc-jwks-url http://127.0.0.1:5556/keys
-cookie-secure=false
-email-domain example.com
```
### Nextcloud Provider
The Nextcloud provider allows you to authenticate against users in your
Nextcloud instance.
When you are using the Nextcloud provider, you must specify the urls via
configuration, environment variable, or command line argument. Depending
on whether your Nextcloud instance is using pretty urls your urls may be of the
form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`.
Refer to the [OAuth2
documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html)
to setup the client id and client secret. Your "Redirection URI" will be
`https://internalapp.yourcompany.com/oauth2/callback`.
```
-provider nextcloud
-client-id <from nextcloud admin>
-client-secret <from nextcloud admin>
-login-url="<your nextcloud url>/index.php/apps/oauth2/authorize"
-redeem-url="<your nextcloud url>/index.php/apps/oauth2/api/v1/token"
-validate-url="<your nextcloud url>/ocs/v2.php/cloud/user?format=json"
```
Note: in *all* cases the validate-url will *not* have the `index.php`.
### DigitalOcean Auth Provider
1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications)
* You can fill in the name, homepage, and description however you wish.
* In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL.
2. Note the Client ID and Client Secret.
To use the provider, pass the following options:
```
--provider=digitalocean
--client-id=<Client ID>
--client-secret=<Client Secret>
```
Alternatively, set the equivalent options in the config file. The redirect URL defaults to `https://<requested host header>/oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option.
### Bitbucket Auth Provider
1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html)
* In "Callback URL" use `https://<oauth2-proxy>/oauth2/callback`, substituting `<oauth2-proxy>` with the actual hostname that oauth2-proxy is running on.
* In Permissions section select:
* Account -> Email
* Team membership -> Read
* Repositories -> Read
2. Note the Client ID and Client Secret.
To use the provider, pass the following options:
```
--provider=bitbucket
--client-id=<Client ID>
--client-secret=<Client Secret>
```
The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team members use additional configuration option: `--bitbucket-team=<Team name>`. To restrict the access to only these users who has access to one selected repository use `--bitbucket-repository=<Repository name>`.
### Gitea Auth Provider
1. Create a new application: `https://< your gitea host >/user/settings/applications`
2. Under `Redirect URI` enter the correct URL i.e. `https://<proxied host>/oauth2/callback`
3. Note the Client ID and Client Secret.
4. Pass the following options to the proxy:
```
--provider="github"
--redirect-url="https://<proxied host>/oauth2/callback"
--provider-display-name="Gitea"
--client-id="< client_id as generated by Gitea >"
--client-secret="< client_secret as generated by Gitea >"
--login-url="https://< your gitea host >/login/oauth/authorize"
--redeem-url="https://< your gitea host >/login/oauth/access_token"
--validate-url="https://< your gitea host >/api/v1"
```
## Email Authentication
To authorize by email domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use `--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`.
## Adding a new Provider
Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new
`Provider` instance. Add a new `case` to
[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the
new `Provider`.

View File

@ -0,0 +1,534 @@
---
id: overview
title: Overview
---
`oauth2-proxy` can be configured via [config file](#config-file), [command line options](#command-line-options) or [environment variables](#environment-variables).
### Generating a Cookie Secret
To generate a strong cookie secret use `python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(16)).decode())'`
### Config File
Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s).
An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg`
### Command Line Options
| Option | Type | Description | Default |
| ------ | ---- | ----------- | ------- |
| `--acr-values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` |
| `--approval-prompt` | string | OAuth approval_prompt | `"force"` |
| `--auth-logging` | bool | Log authentication attempts | true |
| `--auth-logging-format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) |
| `--authenticated-emails-file` | string | authenticate against emails via file (one per line) | |
| `--azure-tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` |
| `--basic-auth-password` | string | the password to set when passing the HTTP Basic Auth header | |
| `--client-id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | |
| `--client-secret` | string | the OAuth Client Secret | |
| `--client-secret-file` | string | the file with OAuth Client Secret | |
| `--config` | string | path to config file | |
| `--cookie-domain` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | |
| `--cookie-expire` | duration | expire timeframe for cookie | 168h0m0s |
| `--cookie-httponly` | bool | set HttpOnly cookie flag | true |
| `--cookie-name` | string | the name of the cookie that the oauth_proxy creates | `"_oauth2_proxy"` |
| `--cookie-path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` |
| `--cookie-refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers&nbsp;\[[1](#footnote1)\] | |
| `--cookie-secret` | string | the seed string for secure cookies (optionally base64 encoded) | |
| `--cookie-secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true |
| `--cookie-samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` |
| `--custom-templates-dir` | string | path to custom html templates | |
| `--custom-sign-in-logo` | string | path to an custom image for the sign_in page logo. Use \"-\" to disable default logo. |
| `--display-htpasswd-form` | bool | display username / password login form if an htpasswd file is provided | true |
| `--email-domain` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | |
| `--errors-to-info-log` | bool | redirects error-level logging to default log channel instead of stderr | |
| `--extra-jwt-issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | |
| `--exclude-logging-paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` |`""` (no paths excluded) |
| `--flush-interval` | duration | period between flushing response buffers when streaming responses | `"1s"` |
| `--force-https` | bool | enforce https redirect | `false` |
| `--banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | |
| `--footer` | string | custom (html) footer string. Use `"-"` to disable default footer. | |
| `--github-org` | string | restrict logins to members of this organisation | |
| `--github-team` | string | restrict logins to members of any of these teams (slug), separated by a comma | |
| `--github-repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | |
| `--github-token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | |
| `--github-user` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | |
| `--gitlab-group` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
| `--gitlab-projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | |
| `--google-admin-email` | string | the google admin to impersonate for api calls | |
| `--google-group` | string | restrict logins to members of this google group (may be given multiple times). | |
| `--google-service-account-json` | string | the path to the service account json credentials | |
| `--htpasswd-file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | |
| `--htpasswd-user-group` | string \| list | the groups to be set on sessions for htpasswd users | |
| `--http-address` | string | `[http://]<addr>:<port>` or `unix://<path>` to listen on for HTTP clients | `"127.0.0.1:4180"` |
| `--https-address` | string | `<addr>:<port>` to listen on for HTTPS clients | `":443"` |
| `--logging-compress` | bool | Should rotated log files be compressed using gzip | false |
| `--logging-filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) |
| `--logging-local-time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) |
| `--logging-max-age` | int | Maximum number of days to retain old log files | 7 |
| `--logging-max-backups` | int | Maximum number of old log files to retain; 0 to disable | 0 |
| `--logging-max-size` | int | Maximum size in megabytes of the log file before rotation | 100 |
| `--jwt-key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | |
| `--jwt-key-file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | |
| `--login-url` | string | Authentication endpoint | |
| `--insecure-oidc-allow-unverified-email` | bool | don't fail if an email address in an id_token is not verified | false |
| `--insecure-oidc-skip-issuer-verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false |
| `--oidc-issuer-url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | |
| `--oidc-jwks-url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled | |
| `--oidc-email-claim` | string | which OIDC claim contains the user's email | `"email"` |
| `--oidc-groups-claim` | string | which OIDC claim contains the user groups | `"groups"` |
| `--pass-access-token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false |
| `--pass-authorization-header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false |
| `--pass-basic-auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true |
| `--prefer-email-to-user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false |
| `--pass-host-header` | bool | pass the request Host Header to upstream | true |
| `--pass-user-headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true |
| `--profile-url` | string | Profile access endpoint | |
| `--prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` |
| `--provider` | string | OAuth provider | google |
| `--provider-ca-file` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. |
| `--provider-display-name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) |
| `--ping-path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` |
| `--ping-user-agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) |
| `--metrics-address` | string | the address prometheus metrics will be scraped from | `""` |
| `--proxy-prefix` | string | the url root path that this proxy should be nested under (e.g. /`<oauth2>/sign_in`) | `"/oauth2"` |
| `--proxy-websockets` | bool | enables WebSocket proxying | true |
| `--pubjwk-url` | string | JWK pubkey access endpoint: required by login.gov | |
| `--real-client-ip-header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, or X-ProxyUser-IP) | X-Real-IP |
| `--redeem-url` | string | Token redemption endpoint | |
| `--redirect-url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | |
| `--redis-cluster-connection-urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | |
| `--redis-connection-url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
| `--redis-password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
| `--redis-sentinel-password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
| `--redis-sentinel-master-name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | |
| `--redis-sentinel-connection-urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | |
| `--redis-use-cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false |
| `--redis-use-sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false |
| `--request-id-header` | string | Request header to use as the request ID in logging | X-Request-Id |
| `--request-logging` | bool | Log requests | true |
| `--request-logging-format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) |
| `--resource` | string | The resource that is protected (Azure AD only) | |
| `--reverse-proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-{Proto,Host,Uri} headers to be used on redirect selection | false |
| `--scope` | string | OAuth scope specification | |
| `--session-cookie-minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false |
| `--session-store-type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
| `--set-xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false |
| `--set-authorization-header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false |
| `--set-basic-auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false |
| `--show-debug-on-error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false |
| `--signature-key` | string | GAP-Signature request signature key (algorithm:secretkey) | |
| `--silence-ping-logging` | bool | disable logging of requests to ping endpoint | false |
| `--skip-auth-preflight` | bool | will skip authentication for OPTIONS requests | false |
| `--skip-auth-regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | |
| `--skip-auth-route` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR path_regex alone for all methods | |
| `--skip-auth-strip-headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true |
| `--skip-jwt-bearer-tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false |
| `--skip-oidc-discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false |
| `--skip-provider-button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false |
| `--ssl-insecure-skip-verify` | bool | skip validation of certificates presented when using HTTPS providers | false |
| `--ssl-upstream-insecure-skip-verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false |
| `--standard-logging` | bool | Log standard runtime information | true |
| `--standard-logging-format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) |
| `--tls-cert-file` | string | path to certificate file | |
| `--tls-key-file` | string | path to private key file | |
| `--upstream` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://<status_code>` for static response. Routing is based on the path | |
| `--allowed-group` | string \| list | restrict logins to members of this group (may be given multiple times) | |
| `--validate-url` | string | Access token validation endpoint | |
| `--version` | n/a | print version string | |
| `--whitelist-domain` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` to allow subdomains (e.g. `.example.com`)&nbsp;\[[2](#footnote2)\] | |
| `--trusted-ip` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | |
\[<a name="footnote1">1</a>\]: Only these providers support `--cookie-refresh`: GitLab, Google and OIDC
\[<a name="footnote2">2</a>\]: When using the `whitelist-domain` option, any domain prefixed with a `.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`.
See below for provider specific options
### Upstreams Configuration
`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers or serve static files from the file system. HTTP and HTTPS upstreams are configured by providing a URL such as `http://127.0.0.1:8080/` for the upstream parameter. This will forward all authenticated requests to the upstream server. If you instead provide `http://127.0.0.1:8080/some/path/` then it will only be requests that start with `/some/path/` which are forwarded to the upstream.
Static file paths are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`.
Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with.
### Environment variables
Every command line argument can be specified as an environment variable by
prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`)
with underscores (`_`). If the argument can be specified multiple times, the
environment variable should be plural (trailing `S`).
This is particularly useful for storing secrets outside of a configuration file
or the command line.
For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`,
and the `--email-domain` flag becomes `OAUTH2_PROXY_EMAIL_DOMAINS`.
## Logging Configuration
By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command.
If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`).
There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`.
Each type of logging has its own configurable format and variables. By default these formats are similar to the Apache Combined Log.
Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) can be disabled with `--silence-ping-logging` reducing log volume. This flag appends the `--ping-path` to `--exclude-logging-paths`.
### Auth Log Format
Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format:
```
<REMOTE_ADDRESS> - <REQUEST ID> - <user@domain.com> [19/Mar/2015:17:20:19 -0400] [<STATUS>] <MESSAGE>
```
The status block will contain one of the below strings:
- `AuthSuccess` If a user has authenticated successfully by any method
- `AuthFailure` If the user failed to authenticate explicitly
- `AuthError` If there was an unexpected error during authentication
If you require a different format than that, you can configure it with the `--auth-logging-format` flag.
The default format is configured as follows:
```
{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}}
```
Available variables for auth logging:
| Variable | Example | Description |
| --- | --- | --- |
| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. |
| Host | domain.com | The value of the Host header. |
| Message | Authenticated via OAuth2 | The details of the auth attempt. |
| Protocol | HTTP/1.0 | The request protocol. |
| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty |
| RequestMethod | GET | The request method. |
| Timestamp | 19/Mar/2015:17:20:19 -0400 | The date and time of the logging event. |
| UserAgent | - | The full user agent as reported by the requesting client. |
| Username | username@email.com | The email or username of the auth request. |
| Status | AuthSuccess | The status of the auth request. See above for details. |
### Request Log Format
HTTP request logs will output by default in the below format:
```
<REMOTE_ADDRESS> - <REQUEST ID> - <user@domain.com> [19/Mar/2015:17:20:19 -0400] <HOST_HEADER> GET <UPSTREAM_HOST> "/path/" HTTP/1.1 "<USER_AGENT>" <RESPONSE_CODE> <RESPONSE_BYTES> <REQUEST_DURATION>
```
If you require a different format than that, you can configure it with the `--request-logging-format` flag.
The default format is configured as follows:
```
{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}}
```
Available variables for request logging:
| Variable | Example | Description |
| --- | --- | --- |
| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. |
| Host | domain.com | The value of the Host header. |
| Protocol | HTTP/1.0 | The request protocol. |
| RequestDuration | 0.001 | The time in seconds that a request took to process. |
| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty |
| RequestMethod | GET | The request method. |
| RequestURI | "/oauth2/auth" | The URI path of the request. |
| ResponseSize | 12 | The size in bytes of the response. |
| StatusCode | 200 | The HTTP status code of the response. |
| Timestamp | 19/Mar/2015:17:20:19 -0400 | The date and time of the logging event. |
| Upstream | - | The upstream data of the HTTP request. |
| UserAgent | - | The full user agent as reported by the requesting client. |
| Username | username@email.com | The email or username of the auth request. |
### Standard Log Format
All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below:
```
[19/Mar/2015:17:20:19 -0400] [main.go:40] <MESSAGE>
```
If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows:
```
[{{.Timestamp}}] [{{.File}}] {{.Message}}
```
Available variables for standard logging:
| Variable | Example | Description |
| --- | --- | --- |
| Timestamp | 19/Mar/2015:17:20:19 -0400 | The date and time of the logging event. |
| File | main.go:40 | The file and line number of the logging statement. |
| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. |
## Configuring for use with the Nginx `auth_request` directive
The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example:
```nginx
server {
listen 443 ssl;
server_name ...;
include ssl/ssl.conf;
location /oauth2/ {
proxy_pass http://127.0.0.1:4180;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Auth-Request-Redirect $request_uri;
# or, if you are handling multiple domains:
# proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri;
}
location = /oauth2/auth {
proxy_pass http://127.0.0.1:4180;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
# nginx auth_request includes headers but not body
proxy_set_header Content-Length "";
proxy_pass_request_body off;
}
location / {
auth_request /oauth2/auth;
error_page 401 = /oauth2/sign_in;
# pass information via X-User and X-Email headers to backend,
# requires running with --set-xauthrequest flag
auth_request_set $user $upstream_http_x_auth_request_user;
auth_request_set $email $upstream_http_x_auth_request_email;
proxy_set_header X-User $user;
proxy_set_header X-Email $email;
# if you enabled --pass-access-token, this will pass the token to the backend
auth_request_set $token $upstream_http_x_auth_request_access_token;
proxy_set_header X-Access-Token $token;
# if you enabled --cookie-refresh, this is needed for it to work with auth_request
auth_request_set $auth_cookie $upstream_http_set_cookie;
add_header Set-Cookie $auth_cookie;
# When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb
# limit and so the OAuth2 Proxy splits these into multiple parts.
# Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response,
# so if your cookies are larger than 4kb, you will need to extract additional cookies manually.
auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1;
# Extract the Cookie attributes from the first Set-Cookie header and append them
# to the second part ($upstream_cookie_* variables only contain the raw cookie content)
if ($auth_cookie ~* "(; .*)") {
set $auth_cookie_name_0 $auth_cookie;
set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1";
}
# Send both Set-Cookie headers now if there was a second part
if ($auth_cookie_name_upstream_1) {
add_header Set-Cookie $auth_cookie_name_0;
add_header Set-Cookie $auth_cookie_name_1;
}
proxy_pass http://backend/;
# or "root /path/to/site;" or "fastcgi_pass ..." etc
}
}
```
When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`.
Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua.
Note that `nginxinc/kubernetes-ingress` does not include the Lua module.
```yaml
nginx.ingress.kubernetes.io/auth-response-headers: Authorization
nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri
nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth
nginx.ingress.kubernetes.io/configuration-snippet: |
auth_request_set $name_upstream_1 $upstream_cookie_name_1;
access_by_lua_block {
if ngx.var.name_upstream_1 ~= "" then
ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)")
end
}
```
It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure).
You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=".
## Configuring for use with the Traefik (v2) `ForwardAuth` middleware
**This option requires `--reverse-proxy` option to be set.**
### ForwardAuth with 401 errors middleware
The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration:
```yaml
http:
routers:
a-service:
rule: "Host(`a-service.example.com`)"
service: a-service-backend
middlewares:
- oauth-errors
- oauth-auth
tls:
certResolver: default
domains:
- main: "example.com"
sans:
- "*.example.com"
oauth:
rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)"
middlewares:
- auth-headers
service: oauth-backend
tls:
certResolver: default
domains:
- main: "example.com"
sans:
- "*.example.com"
services:
a-service-backend:
loadBalancer:
servers:
- url: http://172.16.0.2:7555
oauth-backend:
loadBalancer:
servers:
- url: http://172.16.0.1:4180
middlewares:
auth-headers:
headers:
sslRedirect: true
stsSeconds: 315360000
browserXssFilter: true
contentTypeNosniff: true
forceSTSHeader: true
sslHost: example.com
stsIncludeSubdomains: true
stsPreload: true
frameDeny: true
oauth-auth:
forwardAuth:
address: https://oauth.example.com/oauth2/auth
trustForwardHeader: true
oauth-errors:
errors:
status:
- "401-403"
service: oauth-backend
query: "/oauth2/sign_in"
```
### ForwardAuth with static upstreams configuration
Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/forwardauth/) pointing to oauth2-proxy service's `/` endpoint
**Following options need to be set on `oauth2-proxy`:**
- `--upstream=static://202`: Configures a static response for authenticated sessions
- `--reverseproxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly
```yaml
http:
routers:
a-service-route-1:
rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)"
service: a-service-backend
middlewares:
- oauth-auth-redirect # redirects all unauthenticated to oauth2 signin
tls:
certResolver: default
domains:
- main: "example.com"
sans:
- "*.example.com"
a-service-route-2:
rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)"
service: a-service-backend
middlewares:
- oauth-auth-wo-redirect # unauthenticated session will return a 401
tls:
certResolver: default
domains:
- main: "example.com"
sans:
- "*.example.com"
services-oauth2-route:
rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)"
middlewares:
- auth-headers
service: oauth-backend
tls:
certResolver: default
domains:
- main: "example.com"
sans:
- "*.example.com"
oauth2-proxy-route:
rule: "Host(`oauth.example.com`) && PathPrefix(`/`)"
middlewares:
- auth-headers
service: oauth-backend
tls:
certResolver: default
domains:
- main: "example.com"
sans:
- "*.example.com"
services:
a-service-backend:
loadBalancer:
servers:
- url: http://172.16.0.2:7555
b-service-backend:
loadBalancer:
servers:
- url: http://172.16.0.3:7555
oauth-backend:
loadBalancer:
servers:
- url: http://172.16.0.1:4180
middlewares:
auth-headers:
headers:
sslRedirect: true
stsSeconds: 315360000
browserXssFilter: true
contentTypeNosniff: true
forceSTSHeader: true
sslHost: example.com
stsIncludeSubdomains: true
stsPreload: true
frameDeny: true
oauth-auth-redirect:
forwardAuth:
address: https://oauth.example.com/
trustForwardHeader: true
authResponseHeaders:
- X-Auth-Request-Access-Token
- Authorization
oauth-auth-wo-redirect:
forwardAuth:
address: https://oauth.example.com/oauth2/auth
trustForwardHeader: true
authResponseHeaders:
- X-Auth-Request-Access-Token
- Authorization
```
:::note
If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated.
:::

View File

@ -0,0 +1,67 @@
---
id: session_storage
title: Session Storage
---
Sessions allow a user's authentication to be tracked between multiple HTTP
requests to a service.
The OAuth2 Proxy uses a Cookie to track user sessions and will store the session
data in one of the available session storage backends.
At present the available backends are (as passed to `--session-store-type`):
- [cookie](#cookie-storage) (default)
- [redis](#redis-storage)
### Cookie Storage
The Cookie storage backend is the default backend implementation and has
been used in the OAuth2 Proxy historically.
With the Cookie storage backend, all session information is stored in client
side cookies and transferred with each and every request.
The following should be known when using this implementation:
- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless
- Cookies are signed server side to prevent modification client-side
- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data.
- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation
cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force
users to re-authenticate
### Redis Storage
The Redis Storage backend stores sessions, encrypted, in redis. Instead sending all the information
back the the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back
to the user as the cookie value instead.
A ticket is composed as the following:
`{CookieName}-{ticketID}.{secret}`
Where:
- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default)
- The `ticketID` is a 128 bit random number, hex-encoded
- The `secret` is a 128 bit random number, base64url encoded (no padding). The secret is unique for every session.
- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key
to which the session is stored. The encoded session is encrypted with the secret and stored
in redis via the `SETEX` command.
Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from
disclosure.
#### Usage
When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via
`--redis-connection-url=redis://host[:port][/db-number]`.
You may also configure the store for Redis Sentinel. In this case, you will want to use the
`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name`
and `--redis-sentinel-connection-urls` appropriately.
Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the
`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately.
Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive.

View File

@ -0,0 +1,70 @@
---
id: tls
title: TLS Configuration
---
There are two recommended configurations.
1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`.
The command line to run `oauth2-proxy` in this configuration would look like this:
```bash
./oauth2-proxy \
--email-domain="yourcompany.com" \
--upstream=http://127.0.0.1:8080/ \
--tls-cert-file=/path/to/cert.pem \
--tls-key-file=/path/to/cert.key \
--cookie-secret=... \
--cookie-secure=true \
--provider=... \
--client-id=... \
--client-secret=...
```
2. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ....
Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an
external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or
`--http-address="http://:4180"`.
Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`.
`oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example
would be `https://internal.yourcompany.com/`.
An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL
via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security):
```
server {
listen 443 default ssl;
server_name internal.yourcompany.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/cert.key;
add_header Strict-Transport-Security max-age=2592000;
location / {
proxy_pass http://127.0.0.1:4180;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 1;
proxy_send_timeout 30;
proxy_read_timeout 30;
}
}
```
The command line to run `oauth2-proxy` in this configuration would look like this:
```bash
./oauth2-proxy \
--email-domain="yourcompany.com" \
--upstream=http://127.0.0.1:8080/ \
--cookie-secret=... \
--cookie-secure=true \
--provider=... \
--reverse-proxy=true \
--client-id=... \
--client-secret=...
```

View File

@ -0,0 +1,36 @@
---
id: endpoints
title: Endpoints
---
OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable.
- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info
- /ping - returns a 200 OK response, which is intended for use with health checks
- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default
- /oauth2/sign_in - the login page, which also doubles as a sign out page (it clears cookies)
- /oauth2/sign_out - this URL is used to clear the session cookie
- /oauth2/start - a URL that will redirect to start the OAuth cycle
- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url.
- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format.
- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/overview.md#configuring-for-use-with-the-nginx-auth_request-directive)
### Sign out
To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign out page afterwards using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!):
```
/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page
```
Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header:
```
GET /oauth2/sign_out HTTP/1.1
X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page
...
```
(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.)
BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored.

View File

@ -0,0 +1,24 @@
---
id: installation
title: Installation
slug: /
---
1. Choose how to deploy:
a. Download [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.1.0`)
b. Build with `$ go get github.com/oauth2-proxy/oauth2-proxy/v7` which will put the binary in `$GOPATH/bin`
c. Using the prebuilt docker image [quay.io/oauth2-proxy/oauth2-proxy](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, ARMv6 and ARM64 tags available)
Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`.
```
$ sha256sum -c sha256sum.txt 2>&1 | grep OK
oauth2-proxy-x.y.z.linux-amd64: OK
```
2. [Select a Provider and Register an OAuth Application with a Provider](configuration/auth.md)
3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md)
4. [Configure SSL or Deploy behind a SSL endpoint](configuration/tls.md) (example provided for Nginx)

View File

@ -0,0 +1,61 @@
{
"version-7.1.x/docs": [
{
"type": "doc",
"id": "version-7.1.x/installation"
},
{
"type": "doc",
"id": "version-7.1.x/behaviour"
},
{
"collapsed": false,
"type": "category",
"label": "Configuration",
"items": [
{
"type": "doc",
"id": "version-7.1.x/configuration/overview"
},
{
"type": "doc",
"id": "version-7.1.x/configuration/oauth_provider"
},
{
"type": "doc",
"id": "version-7.1.x/configuration/session_storage"
},
{
"type": "doc",
"id": "version-7.1.x/configuration/tls"
},
{
"type": "doc",
"id": "version-7.1.x/configuration/alpha-config"
}
]
},
{
"collapsed": false,
"type": "category",
"label": "Features",
"items": [
{
"type": "doc",
"id": "version-7.1.x/features/endpoints"
}
]
},
{
"collapsed": false,
"type": "category",
"label": "Community",
"items": [
{
"type": "doc",
"id": "version-7.1.x/community/security"
}
]
}
]
}

View File

@ -1,4 +1,5 @@
[
"7.1.x",
"7.0.x",
"6.1.x"
]