Merge pull request #3308 from oauth2-proxy/release/v7.14.0

release v7.14.0
This commit is contained in:
Jan Larwig 2026-01-17 11:15:40 +01:00 committed by GitHub
commit 707e6c4a1c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
71 changed files with 5112 additions and 493 deletions

View File

@ -1,28 +0,0 @@
# Adopters
This list showcases organizations that leverage OAuth2-Proxy within their
infrastructure. If your organization uses OAuth2-Proxy and isn't yet listed, we
encourage you to add it!
This list aims to be a comprehensive and trusted resource for the OAuth2-Proxy
community, demonstrating successful adoption across all kinds of industries.
Contributing to this list is a simple way to impact the project's growth,
maturity, and momentum. Thank you to all adopters and contributors of the
OAuth2-Proxy project!
## Updating this list
To add your organization to this list, you can just [open a PR](https://github.com/oauth2-proxy/oauth2-proxy/pulls)
to directly update this list.
Add your organization name, your github username and if you desire a short
description on how you utilize oauth2-proxy.
## OAuth2-Proxy Adopters
This list is sorted in the order that organizations were added to it.
| Organization | Contact | Description of Use |
| ------------ | ------- | ------------------ |
| | | |

View File

@ -6,14 +6,101 @@
## Breaking Changes
## Changes since v7.14.0
# V7.14.0
## Release Highlights
- 🕵️‍♀️ Vulnerabilities have been addressed
- [CVE-2025-61729](https://access.redhat.com/security/cve/cve-2025-61729)
- [CVE-2025-61727](https://access.redhat.com/security/cve/cve-2025-61727)
- [CVE-2025-47914](https://access.redhat.com/security/cve/cve-2025-47914)
- [CVE-2025-58181](https://access.redhat.com/security/cve/cve-2025-58181)
- 🗂️ AMajor Alpha Config YAML parsing revamped for better extensibility and preparing v8
- 🐛 Squashed some bugs
## Important Notes
This release introduces a breaking change for Alpha Config users and moves us significantly
closer to removing legacy configuration parameters, making the codebase of OAuth2 Proxy more
future proof and extensible.
From v7.14.0 onward, header injection sources must be explicitly nested. If you
previously relied on squashed fields, update to the new structure before upgrading:
```yaml
# before v7.14.0
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claim: user
- name: X-Custom-Secret-header
values:
- value: my-super-secret
# v7.14.0 and later
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claimSource:
claim: user
- name: X-Custom-Secret-header
values:
- secretSource:
value: my-super-secret
```
Furthermore, Alpha Config now fully supports configuring the `Server` struct using YAML.
```yaml
// Server represents the configuration for the Proxy HTTP(S) configuration.
type Server struct {
// BindAddress is the address on which to serve traffic.
BindAddress string `yaml:"bindAddress,omitempty"`
// SecureBindAddress is the address on which to serve secure traffic.
SecureBindAddress string `yaml:"secureBindAddress,omitempty"`
// TLS contains the information for loading the certificate and key for the
// secure traffic and further configuration for the TLS server.
TLS *TLS `yaml:"tls,omitempty"`
}
// TLS contains the information for loading a TLS certificate and key
// as well as an optional minimal TLS version that is acceptable.
type TLS struct {
// Key is the TLS key data to use.
Key *SecretSource `yaml:"key,omitempty"`
// Cert is the TLS certificate data to use.
Cert *SecretSource `yaml:"cert,omitempty"`
// MinVersion is the minimal TLS version that is acceptable.
MinVersion string `yaml:"minVersion,omitempty"`
// CipherSuites is a list of TLS cipher suites that are allowed.
CipherSuites []string `yaml:"cipherSuites,omitempty"`
}
```
More about how to use Alpha Config can be found in the [documentation](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#server).
We are committed to Semantic Versioning and usually avoid breaking changes without a major version release.
Advancing Alpha Config toward its Beta stage required this exception, and even for the Alpha Config we try
to keep breaking changes in v7 to a minium. Thank you for understanding the need for this step to prepare
the project for future maintainability and future improvements like structured logging.
## Breaking Changes
- Alpha Config: header injection no longer supports squashed claim/secret sources; they must now be set explicitly (see example above).
## Changes since v7.13.0
- [#3290](https://github.com/oauth2-proxy/oauth2-proxy/pull/3290) fix: WebSocket proxy to respect PassHostHeader setting (@UnsignedLong)
- [#2628](https://github.com/oauth2-proxy/oauth2-proxy/pull/2628) feat(structured config): revamp of yaml parsing using mapstructure decoder and custom decoders (@tuunit)
- [#3197](https://github.com/oauth2-proxy/oauth2-proxy/pull/3197) fix: NewRemoteKeySet is not using DefaultHTTPClient (@rsrdesarrollo / @tuunit)
- [#3292](https://github.com/oauth2-proxy/oauth2-proxy/pull/3292) chore(deps): upgrade gomod and bump to golang v1.25.5 (@tuunit)
- [#3304](https://github.com/oauth2-proxy/oauth2-proxy/pull/3304) fix: added conditional so default is not always set and env vars are honored fixes 3303 (@pixeldrew)
- [#3264](https://github.com/oauth2-proxy/oauth2-proxy/pull/3264) fix: more aggressively truncate logged access_token (@MartinNowak / @tuunit)
- [#3267](https://github.com/oauth2-proxy/oauth2-proxy/pull/3267) fix: Session refresh handling in OIDC provider (@gysel)
- [#3290](https://github.com/oauth2-proxy/oauth2-proxy/pull/3290) fix: WebSocket proxy to respect PassHostHeader setting (@UnsignedLong)
# V7.13.0

View File

@ -1,134 +1,112 @@
# Contributor Covenant Code of Conduct
## CNCF Community Code of Conduct v1.3
## Our Pledge
Other languages available:
- [Arabic/العربية](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/ar.md)
- [Bengali/বাংলা](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/bn.md)
- [Bulgarian/Български](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/bg.md)
- [Chinese/中文](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/zh.md)
- [Czech/Česky](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/cs.md)
- [Farsi/فارسی](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/fa.md)
- [French/Français](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/fr.md)
- [German/Deutsch](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/de.md)
- [Hebrew/עברית](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/he.md)
- [Hindi/हिन्दी](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/hi.md)
- [Hungarian/Magyar](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/hu.md)
- [Indonesian/Bahasa Indonesia](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/id.md)
- [Italian/Italiano](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/it.md)
- [Japanese/日本語](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/ja.md)
- [Korean/한국어](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/ko.md)
- [Polish/Polski](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/pl.md)
- [Portuguese/Português](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/pt.md)
- [Russian/Русский](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/ru.md)
- [Spanish/Español](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/es.md)
- [Turkish/Türkçe](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/tr.md)
- [Ukrainian/Українська](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/uk.md)
- [Vietnamese/Tiếng Việt](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/vi.md)
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.
### Community Code of Conduct
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
As contributors, maintainers, and participants in the CNCF community, and in the interest of fostering
an open and welcoming community, we pledge to respect all people who participate or contribute
through reporting issues, posting feature requests, updating documentation,
submitting pull requests or patches, attending conferences or events, or engaging in other community or project activities.
We are committed to making participation in the CNCF community a harassment-free experience for everyone, regardless of age, body size, caste, disability, ethnicity, level of experience, family status, gender, gender identity and expression, marital status, military or veteran status, nationality, personal appearance, race, religion, sexual orientation, socioeconomic status, tribe, or any other dimension of diversity.
## Scope
This code of conduct applies:
* within project and community spaces,
* in other spaces when an individual CNCF community participant's words or actions are directed at or are about a CNCF project, the CNCF community, or another CNCF community participant in the context of a CNCF activity.
### CNCF Events
CNCF events that are produced by the Linux Foundation with professional events staff are governed by the Linux Foundation [Events Code of Conduct](https://events.linuxfoundation.org/code-of-conduct/) available on the event page. This is designed to be used in conjunction with the CNCF Code of Conduct.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
The CNCF Community is open, inclusive and respectful. Every member of our community has the right to have their identity respected.
Examples of behavior that contributes to a positive environment include but are not limited to:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
community
* Focusing on what is best not just for us as individuals, but for the
overall community
* Using welcoming and inclusive language
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of
any kind
Examples of unacceptable behavior include but are not limited to:
* The use of sexualized language or imagery
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address,
without their explicit permission
* Public or private harassment in any form
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Violence, threatening violence, or encouraging others to engage in violent behavior
* Stalking or following someone without their consent
* Unwelcome physical contact
* Unwelcome sexual or romantic attention or advances
* Using CNCF projects or community spaces for political campaigning or promotion of political causes
that are unrelated to the advancement of cloud native technology. To clarify, this policy does not restrict individuals' personal attire, including attire that expresses personal beliefs or aspects of identity.
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
The following behaviors are also prohibited:
* Providing knowingly false or misleading information in connection with a Code of Conduct investigation or otherwise intentionally tampering with an investigation.
* Retaliating against a person because they reported an incident or provided information about an incident as a witness.
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct.
By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect
of managing a CNCF project.
Project maintainers who do not follow or enforce the Code of Conduct may be temporarily or permanently removed from the project team.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Reporting
## Scope
For incidents occurring in the Kubernetes community, contact the [Kubernetes Code of Conduct Committee](https://git.k8s.io/community/committee-code-of-conduct) via <conduct@kubernetes.io>. You can expect a response within three business days.
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official email address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
For other projects, or for incidents that are project-agnostic or impact multiple CNCF projects, please contact the [CNCF Code of Conduct Committee](https://www.cncf.io/conduct/committee/) via <conduct@cncf.io>. Alternatively, you can contact any of the individual members of the [CNCF Code of Conduct Committee](https://www.cncf.io/conduct/committee/) to submit your report. For more detailed instructions on how to submit a report, including how to submit a report anonymously, please see our [Incident Resolution Procedures](https://github.com/cncf/foundation/blob/main/code-of-conduct/coc-incident-resolution-procedures.md). You can expect a response within three business days.
For incidents occurring at CNCF event that is produced by the Linux Foundation, please contact <eventconduct@cncf.io>.
## Frequently asked questions
For more information about this Code of Conduct, please see the [CNCF Code of Conduct Frequently Asked Questions](https://www.cncf.io/conduct/faq/).
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
https://gophers.slack.com/messages/CM2RSS25N or directly contacting one of the
maintainers from the MAINTAINERS file.
All complaints will be reviewed and investigated promptly and fairly.
Upon review and investigation of a reported incident, the CoC response team that has jurisdiction will determine what action is appropriate based on this Code of Conduct and its related documentation.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
For information about which Code of Conduct incidents are handled by project leadership, which incidents are handled by the CNCF Code of Conduct Committee, and which incidents are handled by the Linux Foundation (including its events team), see our [Jurisdiction Policy](https://github.com/cncf/foundation/blob/main/code-of-conduct/coc-committee-jurisdiction-policy.md).
## Enforcement Guidelines
## Amendments
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
Consistent with the CNCF Charter, any substantive changes to this Code of Conduct must be approved by the Technical Oversight Committee.
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of
actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the
community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
## Acknowledgements
This Code of Conduct is adapted from the Contributor Covenant
(http://contributor-covenant.org), version 2.0 available at
http://contributor-covenant.org/version/2/0/code_of_conduct/

34
DCO.md Normal file
View File

@ -0,0 +1,34 @@
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.

View File

@ -1,5 +1,2 @@
Joel Speed <joel@oauth2-proxy.dev> (@JoelSpeed)
Nick Meves <nick@oauth2-proxy.dev> (@NickMeves)
Braunson <braunson@oauth2-proxy.dev> (@braunsonm)
Jan Larwig <jan@oauth2-proxy.dev> (@tuunit)
Koen van Zuijlen <koen@oauth2-proxy.dev> (@kvanzuijlen)
Moved to https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS.md

33
MAINTAINERS.md Normal file
View File

@ -0,0 +1,33 @@
# Maintainers
The table below lists all current maintainers for the oauth2-proxy as defined
by our [project governance](GOVERNANCE.md).
| Name | GitHub Handle | Domains of reponsibility | Email Alias | Affiliation |
| ---------------- | ------------------------------------------------------ | ------------------------ | -------------------------- | ----------- |
| Joel Speed | [@JoelSpeed](https://github.com/joelspeed) | Governance, Core | joel@oauth2-proxy.dev | Red Hat |
| Jan Larwig | [@tuunit](https://github.com/tuunit) | Governance, Core | jan@oauth2-proxy.dev | IONOS Cloud |
| JJ Łakis | [@jjlakis](https://github.com/jjlakis) | Provider | jj@oauth2-proxy.dev | - |
| Koen van Zuijlen | [@kvanzuijlen](https://github.com/kvanzuijlen) | CI | koen@oauth2-proxy.dev | - |
| Pierluigi Lenoci | [@pierluigilenoci](https://github.com/pierluigilenoci) | Helm | pierluigi@oauth2-proxy.dev | SAP |
## Emeritus Maintainers
We would like to highlight that this project does have prior maintainers and
core contributors that, if they so wished, could (and should) be granted the
status of emeritus maintainers.
| Name | GitHub Handle |
| ------------- | ------------------------------------------------------ |
| Nick Meves | [@NickMeves](https://github.com/NickMeves) |
| Braunson | [@braunsonm](https://github.com/braunsonm) |
| Henry Jenkins | [@steakunderscore](https://github.com/steakunderscore) |
## Security Response Team and GitHub Organization Owners
The following maintainers are members of the security response team and owners
of the GitHub organization.
- Joel Speed
- Jan Larwig

View File

@ -1,22 +1,24 @@
[![Continuous Integration](https://github.com/oauth2-proxy/oauth2-proxy/actions/workflows/ci.yml/badge.svg)](https://github.com/oauth2-proxy/oauth2-proxy/actions/workflows/ci.yml)
[![Go Report Card](https://goreportcard.com/badge/github.com/oauth2-proxy/oauth2-proxy)](https://goreportcard.com/report/github.com/oauth2-proxy/oauth2-proxy)
[![GoDoc](https://godoc.org/github.com/oauth2-proxy/oauth2-proxy?status.svg)](https://godoc.org/github.com/oauth2-proxy/oauth2-proxy)
[![Go Report Card](https://goreportcard.com/badge/github.com/oauth2-proxy/oauth2-proxy)](https://goreportcard.com/report/github.com/oauth2-proxy/oauth2-proxy/v7)
[![GoDoc](https://godoc.org/github.com/oauth2-proxy/oauth2-proxy?status.svg)](https://godoc.org/github.com/oauth2-proxy/oauth2-proxy/v7)
[![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
[![Maintainability](https://api.codeclimate.com/v1/badges/a58ff79407212e2beacb/maintainability)](https://codeclimate.com/github/oauth2-proxy/oauth2-proxy/maintainability)
[![Test Coverage](https://api.codeclimate.com/v1/badges/a58ff79407212e2beacb/test_coverage)](https://codeclimate.com/github/oauth2-proxy/oauth2-proxy/test_coverage)
[![Maintainability](https://qlty.sh/gh/oauth2-proxy/projects/oauth2-proxy/maintainability.svg)](https://qlty.sh/gh/oauth2-proxy/projects/oauth2-proxy)
[![Code Coverage](https://qlty.sh/gh/oauth2-proxy/projects/oauth2-proxy/coverage.svg)](https://qlty.sh/gh/oauth2-proxy/projects/oauth2-proxy)
[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/oauth2-proxy/oauth2-proxy/badge)](https://scorecard.dev/viewer/?uri=github.com/oauth2-proxy/oauth2-proxy)
[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/11223/badge)](https://www.bestpractices.dev/projects/11223)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy?ref=badge_shield)
![OAuth2 Proxy](docs/static/img/logos/OAuth2_Proxy_horizontal.svg)
OAuth2-Proxy is a flexible, open-source tool that can act as either a standalone reverse proxy or a middleware component integrated into existing reverse proxy or load balancer setups. It provides a simple and secure way to protect your web applications with OAuth2 / OIDC authentication. As a reverse proxy, it intercepts requests to your application and redirects users to an OAuth2 provider for authentication. As a middleware, it can be seamlessly integrated into your existing infrastructure to handle authentication for multiple applications.
OAuth2 Proxy is a flexible, open-source tool that can act as either a standalone reverse proxy or a middleware component integrated into existing reverse proxy or load balancer setups. It provides a simple and secure way to protect your web applications with OAuth2 / OIDC authentication. As a reverse proxy, it intercepts requests to your application and redirects users to an OAuth2 provider for authentication. As a middleware, it can be seamlessly integrated into your existing infrastructure to handle authentication for multiple applications.
OAuth2-Proxy supports a lot of OAuth2 as well as OIDC providers. Either through a generic OIDC client or a specific implementation for Google, Microsoft Entra ID, GitHub, login.gov and others. Through specialised provider implementations oauth2-proxy can extract more details about the user like preferred usernames and groups. Those details can then be forwarded as HTTP headers to your upstream applications.
OAuth2 Proxy supports a lot of OAuth2 as well as OIDC providers. Either through a generic OIDC client or a specific implementation for Google, Microsoft Entra ID, GitHub, login.gov and others. Through specialised provider implementations oauth2-proxy can extract more details about the user like preferred usernames and groups. Those details can then be forwarded as HTTP headers to your upstream applications.
![Simplified Architecture](docs/static/img/simplified-architecture.svg)
## Get Started
OAuth2-Proxy's [Installation Docs](https://oauth2-proxy.github.io/oauth2-proxy/installation) cover how to install and configure your setup. Additionally you can take a further look at the [example setup files](https://github.com/oauth2-proxy/oauth2-proxy/tree/master/contrib/local-environment).
OAuth2 Proxy's [Installation Docs](https://oauth2-proxy.github.io/oauth2-proxy/installation) cover how to install and configure your setup. Additionally you can take a further look at the [example setup files](https://github.com/oauth2-proxy/oauth2-proxy/tree/master/contrib/local-environment).
## Releases
@ -35,24 +37,26 @@ Since 2023-11-18 we build nightly images directly from the `master` branch and p
These images are considered unstable and therefore should **NOT** be used for production purposes unless you know what you're doing.
## Sponsors
![Microsoft](https://upload.wikimedia.org/wikipedia/commons/9/96/Microsoft_logo_%282012%29.svg)
Microsoft Azure credits for open source projects
Would you like to sponsor the project then please contact us at [sponsors@oauth2-proxy.dev](mailto:sponsors@oauth2-proxy.dev)
![SAP](https://avatars.githubusercontent.com/u/2531208?s=300&v=4)
SAP Open Source Program
## Former Sponsors
![Microsoft](https://avatars.githubusercontent.com/u/6154722?s=100&v=4)
Microsoft Azure credits for open source projects
## Getting Involved
[![Slack](https://img.shields.io/badge/slack-Gopher_%23oauth2--proxy-red?logo=slack)](https://gophers.slack.com/archives/CM2RSS25N)
Join the #oauth2-proxy [Slack channel](https://gophers.slack.com/archives/CM2RSS25N) to chat with other users of oauth2-proxy or reach out to the maintainers directly. Use the [public invite link](https://invite.slack.golangbridge.org/) to get an invite for the Gopher Slack space.
OAuth2-Proxy is a community-driven project. We rely on the contributions of our users to continually improve it. While review times can vary, we appreciate your patience and understanding. As a volunteer-driven project, we strive to keep this project stable and might take longer to merge changes.
OAuth2 Proxy is a community-driven project. We rely on the contributions of our users to continually improve it. While review times can vary, we appreciate your patience and understanding. As a volunteer-driven project, we strive to keep this project stable and might take longer to merge changes.
If you want to contribute to the project. Please see our [Contributing](https://oauth2-proxy.github.io/oauth2-proxy/community/contribution) guide.
Who uses OAuth2-Proxy? Have a look at our new [ADOPTERS](ADOPTERS.md) file and
feel free to open a PR to add your organisation.
Thanks to all the people who already contributed ❤
<a href="https://github.com/oauth2-proxy/oauth2-proxy/graphs/contributors">
@ -66,7 +70,7 @@ Made with [contrib.rocks](https://contrib.rocks).
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 maintainers, please compose an email and send it to the list of people listed in our [MAINTAINERS](MAINTAINERS) file.
Security disclosures **MUST** be done in private. If you have found an issue that you would like to bring to the attention of the maintainers, please compose an email and send it to the list of people listed in our [MAINTAINERS.md](MAINTAINERS.md) file.
For more details read our full [Security Docs](https://oauth2-proxy.github.io/oauth2-proxy/community/security#security-disclosures)
@ -82,9 +86,20 @@ See [open redirect vulnerability](https://github.com/oauth2-proxy/oauth2-proxy/s
**2020-03-29:** This project was formerly hosted as `pusher/oauth2_proxy` but has been renamed to `oauth2-proxy/oauth2-proxy`. Going forward, all images shall be available at `quay.io/oauth2-proxy/oauth2-proxy` and binaries will be named `oauth2-proxy`.
## Code of Conduct
Participation in the OAuth2 Proxy project is governed by the [CNCF Code of Conduct](CODE_OF_CONDUCT.md).
## License
OAuth2-Proxy is distributed under [The MIT License](LICENSE).
OAuth2 Proxy is distributed under [The MIT License](LICENSE).
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy?ref=badge_large)
## Trademarks
OAuth2 Proxy is a [Cloud Native Computing Foundation](https://cncf.io) Sandbox project.
![CNCF](https://www.cncf.io/wp-content/uploads/2023/04/cncf-main-site-logo.svg)
The Linux Foundation® (TLF) has registered trademarks and uses trademarks. For a list of TLF trademarks, see [Trademark Usage](https://www.linuxfoundation.org/legal/trademark-usage).

View File

@ -14,7 +14,7 @@ version: "3.0"
services:
oauth2-proxy:
container_name: oauth2-proxy
image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0
image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml
hostname: oauth2-proxy
volumes:

View File

@ -14,7 +14,7 @@ version: '3.0'
services:
oauth2-proxy:
container_name: oauth2-proxy
image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0
image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
command: --config /oauth2-proxy.cfg
hostname: oauth2-proxy
volumes:

View File

@ -14,7 +14,7 @@ version: '3.0'
services:
oauth2-proxy:
container_name: oauth2-proxy
image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0
image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
command: --config /oauth2-proxy.cfg
hostname: oauth2-proxy
volumes:

View File

@ -22,7 +22,7 @@
version: '3.0'
services:
oauth2-proxy:
image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0
image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
ports: []
hostname: oauth2-proxy
container_name: oauth2-proxy

View File

@ -23,7 +23,7 @@ version: '3.0'
services:
oauth2-proxy:
image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0
image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
ports: []
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.13.0
image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
command: --config /oauth2-proxy.cfg
hostname: oauth2-proxy
volumes:

View File

@ -39,7 +39,7 @@ For starting oauth2-proxy locally open the debugging tab and create the `launch.
"version": "0.2.0",
"configurations": [
{
"name": "Launch OAuth2-Proxy with Dex",
"name": "Launch OAuth2 Proxy with Dex",
"type": "go",
"request": "launch",
"mode": "auto",
@ -52,7 +52,7 @@ For starting oauth2-proxy locally open the debugging tab and create the `launch.
]
},
{
"name": "Launch OAuth2-Proxy with Keycloak",
"name": "Launch OAuth2 Proxy with Keycloak",
"type": "go",
"request": "launch",
"mode": "auto",
@ -85,7 +85,7 @@ The username and password for all setups is usually `admin@example.com` and `pas
The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me
- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180
- OAuth2 Proxy: http://oauth2-proxy.localtest.me:4180
- Upstream: http://httpbin.localtest.me:8080
- Dex: http://dex.localtest.me:5556

View File

@ -21,7 +21,7 @@ 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.
list of maintainers in our [MAINTAINERS.md](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS.md) file.
Please include as much detail as possible.
Ideally, your disclosure should include:

View File

@ -24,17 +24,56 @@ When using alpha configuration, your config file will look something like below:
upstreams:
- id: ...
...: ...
providers:
- id: ...
...: ...
cookie:
secret: ...
...: ...
injectRequestHeaders:
- name: ...
...: ...
- secretSource:
...: ...
injectResponseHeaders:
- name: ...
...: ...
- claimSource:
...: ...
```
Please browse the [reference](#configuration-reference) below for the structure
of the new configuration format.
# Migration Guide
This section details breaking changes and migration steps for moving to the new
alpha configuration format.
## Migrating header injections in v7.14.0
From v7.14.0 onward, header injection sources must be explicitly nested. If you
previously relied on squashed fields, update to the new structure before
upgrading:
```yaml
# before v7.14.0
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claim: user
- name: X-Custom-Secret-header
values:
- value: my-super-secret
# v7.14.0 and later
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claimSource:
claim: user
- name: X-Custom-Secret-header
values:
- secretSource:
value: my-super-secret
```
## Using Alpha Configuration
To use the new **alpha** configuration, generate a YAML file based on the format
@ -67,9 +106,9 @@ the new config.
oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
```
## Using ENV variables in the alpha configuration
### How to use environment variables
The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file.
The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file.
When using environment variables, your yaml will look like this:
```yaml
@ -81,6 +120,46 @@ When using environment variables, your yaml will look like this:
Where CLIENT_SECRET is an environment variable.
More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs)
### How to inject custom headers
Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML.
```yaml
injectRequestHeaders:
- name: "X-User-Email"
values:
- claimSource:
claim: "email" # extract the email claim contents from the id token
- name: "X-Static-Secret"
values:
# secrets need to be encoded with base64 when directly in the yaml config but will be send decoded
- secretSource:
value: "c3VwZXItc2VjcmV0"
- name: "X-Static-File-Secret"
- secretSource:
fromFile: "/path/to/my/secret"
- name: "X-Static-Env-Secret"
- secretSource:
value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded
injectResponseHeaders:
# Following will result in a header "Authorization: Basic <user:password> (encoded)"
- name: "Authorization"
values:
- claimSource:
claim: user
prefix: "Basic "
basicAuthPassword:
value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password
```
**Value sources:**
* `claimSource` - `claim` (session claims either from id token or from profile URL)
* `secretSource` - `value` (base64), `fromFile` (file path)
**Request option:** `preserveRequestValue: true` retains existing header values
**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
## Removed options
The following flags/options and their respective environment variables are no

View File

@ -24,17 +24,56 @@ When using alpha configuration, your config file will look something like below:
upstreams:
- id: ...
...: ...
providers:
- id: ...
...: ...
cookie:
secret: ...
...: ...
injectRequestHeaders:
- name: ...
...: ...
- secretSource:
...: ...
injectResponseHeaders:
- name: ...
...: ...
- claimSource:
...: ...
```
Please browse the [reference](#configuration-reference) below for the structure
of the new configuration format.
# Migration Guide
This section details breaking changes and migration steps for moving to the new
alpha configuration format.
## Migrating header injections in v7.14.0
From v7.14.0 onward, header injection sources must be explicitly nested. If you
previously relied on squashed fields, update to the new structure before
upgrading:
```yaml
# before v7.14.0
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claim: user
- name: X-Custom-Secret-header
values:
- value: my-super-secret
# v7.14.0 and later
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claimSource:
claim: user
- name: X-Custom-Secret-header
values:
- secretSource:
value: my-super-secret
```
## Using Alpha Configuration
To use the new **alpha** configuration, generate a YAML file based on the format
@ -67,9 +106,9 @@ the new config.
oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
```
## Using ENV variables in the alpha configuration
### How to use environment variables
The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file.
The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file.
When using environment variables, your yaml will look like this:
```yaml
@ -81,6 +120,46 @@ When using environment variables, your yaml will look like this:
Where CLIENT_SECRET is an environment variable.
More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs)
### How to inject custom headers
Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML.
```yaml
injectRequestHeaders:
- name: "X-User-Email"
values:
- claimSource:
claim: "email" # extract the email claim contents from the id token
- name: "X-Static-Secret"
values:
# secrets need to be encoded with base64 when directly in the yaml config but will be send decoded
- secretSource:
value: "c3VwZXItc2VjcmV0"
- name: "X-Static-File-Secret"
- secretSource:
fromFile: "/path/to/my/secret"
- name: "X-Static-Env-Secret"
- secretSource:
value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded
injectResponseHeaders:
# Following will result in a header "Authorization: Basic <user:password> (encoded)"
- name: "Authorization"
values:
- claimSource:
claim: user
prefix: "Basic "
basicAuthPassword:
value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password
```
**Value sources:**
* `claimSource` - `claim` (session claims either from id token or from profile URL)
* `secretSource` - `value` (base64), `fromFile` (file path)
**Request option:** `preserveRequestValue: true` retains existing header values
**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
## Removed options
The following flags/options and their respective environment variables are no

View File

@ -64,9 +64,9 @@ the refresh flow to get a new Access-Token. If it is longer, it might be that th
expired.
The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the
Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will
Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2 Proxy will
refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification
Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an
Access-Tokens are not required to follow a specific format. Therefore OAuth2 Proxy cannot check for any expiry date without an
introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely
encounter expiry issues.

View File

@ -5,7 +5,7 @@ title: Installation
1. Choose how to deploy:
a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.13.0`)
a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.0`)
b. Using Go to install the latest release
```bash

View File

@ -21,3 +21,13 @@ A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy
## Architecture
![OAuth2 Proxy Architecture](/img/simplified-architecture.svg)
## Cloud Native Computing Foundation
OAuth2 Proxy is a [Cloud Native Computing Foundation](https://cncf.io) Sandbox project.
![CNCF](https://www.cncf.io/wp-content/uploads/2023/04/cncf-main-site-logo.svg)
The Linux Foundation® (TLF) has registered trademarks and uses trademarks. For a list of TLF trademarks, see [Trademark Usage](https://www.linuxfoundation.org/legal/trademark-usage).

View File

@ -118,7 +118,7 @@ const config = {
},
footer: {
style: 'dark',
copyright: `Copyright © ${new Date().getFullYear()} OAuth2 Proxy.`,
copyright: `Copyright © ${new Date().getFullYear()} OAuth2 Proxy a Series of LF Projects, LLC.<br>For website terms of use, trademark policy and other project policies please see lfprojects.org/policies/`,
},
prism: {
theme: prismThemes.github,

View File

@ -1,310 +0,0 @@
---
id: integration
title: Integration
---
## Configuring for use with the Nginx `auth_request` directive
**This option requires `--reverse-proxy` option to be set.**
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-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-Forwarded-Uri $request_uri;
# 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 =403 /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 can configure the same behavior with the following annotations on your Ingress resource:
```yaml
nginx.ingress.kubernetes.io/auth-url: "https://<oauth2-proxy-fqdn>/oauth2/auth"
nginx.ingress.kubernetes.io/auth-signin: "https://<oauth2-proxy-fqdn>/oauth2/start?rd=$escaped_request_uri"
```
This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/.
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/http/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?rd={url}"
```
### 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/http/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
- `--reverse-proxy=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
```
## Configuring for use with the Caddy (v2) `forward_auth` directive
The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`.
This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint.
**Following options need to be set on `oauth2-proxy`:**
- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly
```nginx title="Caddyfile"
example.com {
# Requests to /oauth2/* are proxied to oauth2-proxy without authentication.
# You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive.
handle /oauth2/* {
reverse_proxy oauth2-proxy.internal:4180 {
# oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers.
# The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers.
header_up X-Real-IP {remote_host}
header_up X-Forwarded-Uri {uri}
}
}
# Requests to other paths are first processed by oauth2-proxy for authentication.
handle {
forward_auth oauth2-proxy.internal:4180 {
uri /oauth2/auth
# oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers.
# The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers.
header_up X-Real-IP {remote_host}
# If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream.
# Make sure to configure the --set-xauthrequest flag to enable this feature.
#copy_headers X-Auth-Request-User X-Auth-Request-Email
# If oauth2-proxy returns a 401 status, redirect the client to the sign-in page.
@error status 401
handle_response @error {
redir * /oauth2/sign_in?rd={scheme}://{host}{uri}
}
}
# If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream.
reverse_proxy upstream.internal:3000
}
}
```
:::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,63 @@
---
id: caddy
title: Caddy
---
Integrate OAuth2 Proxy with Caddy v2 using the `forward_auth` directive.
**Key features:**
- Simple forward_auth setup
- Automatic header handling
- Custom error handling and redirects
## Configuring for use with the Caddy (v2) `forward_auth` directive
The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`.
This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint.
**Following options need to be set on `oauth2-proxy`:**
- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly
```nginx title="Caddyfile"
example.com {
# Requests to /oauth2/* are proxied to oauth2-proxy without authentication.
# You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive.
handle /oauth2/* {
reverse_proxy oauth2-proxy.internal:4180 {
# oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers.
# The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers.
header_up X-Real-IP {remote_host}
header_up X-Forwarded-Uri {uri}
}
}
# Requests to other paths are first processed by oauth2-proxy for authentication.
handle {
forward_auth oauth2-proxy.internal:4180 {
uri /oauth2/auth
# oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers.
# The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers.
header_up X-Real-IP {remote_host}
# If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream.
# Make sure to configure the --set-xauthrequest flag to enable this feature.
#copy_headers X-Auth-Request-User X-Auth-Request-Email
# If oauth2-proxy returns a 401 status, redirect the client to the sign-in page.
@error status 401
handle_response @error {
redir * /oauth2/sign_in?rd={scheme}://{host}{uri}
}
}
# If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream.
reverse_proxy upstream.internal:3000
}
}
```
:::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,105 @@
---
id: headlamp
title: Headlamp
---
Modern, actively maintained Kubernetes web UI with OAuth2 Proxy integration examples.
**Key features:**
- Active development and maintenance
- Modern, intuitive interface
- Multi-cluster support
- Plugin system
- Works with all OAuth2 providers
## Configuring for use with Headlamp
[Headlamp](https://headlamp.dev/) is a modern, user-friendly Kubernetes web UI that can be integrated with OAuth2 Proxy for authentication. This is a recommended alternative to the deprecated Kubernetes Dashboard.
### Architecture
```
User → Ingress → OAuth2 Proxy → Authentication Provider (e.g., Azure Entra ID)
Headlamp
```
### Prerequisites
- Kubernetes cluster (e.g., AKS, EKS, GKE, or self-hosted)
- Headlamp installed in the cluster
- OAuth2 provider configured (Azure Entra ID, Google, GitHub, etc.)
- Ingress controller (Nginx, Traefik, etc.)
### Configuration Overview
When integrating Headlamp with OAuth2 Proxy, the OAuth2 Proxy acts as a reverse proxy in front of Headlamp:
1. User requests access to Headlamp
2. Ingress forwards to OAuth2 Proxy
3. OAuth2 Proxy authenticates the user via the OAuth2 provider
4. After successful authentication, OAuth2 Proxy proxies requests to Headlamp
5. Headlamp receives the authenticated user information via headers
### OAuth2 Proxy Configuration
Configure OAuth2 Proxy to proxy to the Headlamp service:
```yaml
upstreamConfig:
upstreams:
- id: headlamp
path: /
uri: http://headlamp-service.headlamp-namespace.svc.cluster.local:4466
```
Enable the necessary headers:
```yaml
extraArgs:
reverse-proxy: true
pass-authorization-header: true
set-xauthrequest: true
email-domain: "*" # Or restrict to your organization
```
### Example with Azure Entra ID on AKS
For detailed instructions on deploying Headlamp with OAuth2 Proxy on Azure Kubernetes Service using Azure Entra ID, see the official Headlamp documentation:
https://headlamp.dev/docs/latest/installation/in-cluster/aks-cluster-oauth/
Key steps include:
1. **Set up AKS with OIDC**: Enable Microsoft Entra ID authentication with Kubernetes RBAC
2. **Create Azure App Registration**: Configure redirect URI and create client secret
3. **Deploy Headlamp**: Install Headlamp via Helm in your cluster
4. **Deploy OAuth2 Proxy**: Configure OAuth2 Proxy with Entra ID provider settings and upstream pointing to Headlamp
5. **Configure Ingress**: Set up Ingress to route traffic through OAuth2 Proxy to Headlamp
6. **Set RBAC Policies**: Apply Kubernetes RBAC bindings based on users or groups
### Integration with Other Providers
The same integration pattern works with other OAuth2 providers supported by OAuth2 Proxy:
- **Google**: Use the Google provider configuration
- **GitHub**: Use the GitHub provider configuration
- **GitLab**: Use the GitLab provider configuration
- **Keycloak**: Use the Keycloak OIDC provider configuration
- **Any OIDC Provider**: Use the generic OIDC provider configuration
For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation.
### Benefits Over Kubernetes Dashboard
Headlamp offers several advantages:
- **Active Development**: Headlamp is actively maintained and developed
- **Modern UI**: Clean, intuitive interface with better UX
- **Plugin System**: Extensible with custom plugins
- **Multi-cluster Support**: Built-in support for managing multiple clusters
- **Desktop App**: Available as both web UI and desktop application
:::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,41 @@
---
id: index
title: Integrations
---
This section provides configuration examples for integrating OAuth2 Proxy with various reverse proxies, ingress controllers, and Kubernetes web UIs.
## Reverse Proxies and Ingress Controllers
OAuth2 Proxy can be integrated with popular reverse proxies and ingress controllers to add authentication to your applications:
- [Nginx](nginx.md)
- [Traefik](traefik.md)
- [caddy](caddy.md)
## Kubernetes Web UIs
OAuth2 Proxy can also be used to add authentication to Kubernetes web user interfaces:
- [Headlamp](headlamp.md) ✨ *Recommended*
- [Kubernetes Dashboard](kubernetes-dashboard.md) ⚠️ *Deprecated*
:::tip
When integrating with Kubernetes web UIs, make sure to:
1. Configure the Ingress to pass the Authorization header with the bearer token
2. Increase buffer sizes for large OIDC tokens (especially with Azure Entra ID)
3. Set up appropriate Kubernetes RBAC permissions for your users or groups
:::
## General Requirements
Most integrations require the following OAuth2 Proxy configuration:
- `--reverse-proxy=true`: Required to correctly handle `X-Forwarded-*` headers
- **Session storage**: For production deployments with large tokens due to a lot of claims like AD groups, use `--session-store-type=redis`
For provider-specific configuration, see the [OAuth Provider Configuration](../providers/index.md) documentation.
:::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,289 @@
---
id: kubernetes-dashboard
title: Kubernetes Dashboard
---
:::warning Deprecated Project
Kubernetes Dashboard has been deprecated and discontinued as of January 2025. See the [official announcement](https://github.com/kubernetes/dashboard/commit/0ba796dce6916bb6ca5da5ca0b3ab22cecfd1e18) for more information.
You may want to consider alternative solutions such as [Headlamp](./headlamp.md).
:::
## Kubernetes Dashboard on AKS with Azure Entra ID
Integration guide for the deprecated Kubernetes Dashboard, including comprehensive Azure Entra ID configuration on AKS with detailed troubleshooting and RBAC setup.
### Architecture
```
User → Nginx Ingress → OAuth2 Proxy → Entra ID
Kubernetes Dashboard
```
The integration flow:
1. Unauthenticated requests to Dashboard are intercepted by Nginx Ingress
2. Nginx redirects to OAuth2 Proxy for authentication
3. OAuth2 Proxy redirects to Entra ID login
4. After successful authentication, OAuth2 Proxy receives ID token from Entra ID
5. OAuth2 Proxy sets Authorization header with the bearer token
6. Nginx forwards the request with token to Kubernetes Dashboard
7. Dashboard validates the token and grants access based on AKS RBAC configuration
### Prerequisites
- AKS cluster with Entra ID integration enabled
- Kubernetes Dashboard installed (version 7.x or later)
- NGINX Ingress Controller installed
- Entra ID App Registration configured with:
- Redirect URI: `https://your-oauth2-domain.com/oauth2/callback`
- API Permissions: `openid`, `email`, `profile`
- Groups claim enabled (if using group-based RBAC)
- Users or groups assigned appropriate Kubernetes RBAC permissions
### Alpha Configuration Example
Using [Alpha Configuration](../alpha_config.md) with the OAuth2 Proxy Helm chart:
```yaml
alphaConfig:
enabled: true
configData:
providers:
- id: azure-entra
provider: entra-id
clientID: YOUR_CLIENT_ID
clientSecret: YOUR_CLIENT_SECRET
oidcConfig:
issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0
audienceClaims:
- aud
emailClaim: email
groupsClaim: groups
userIDClaim: oid
scope: openid email profile
upstreamConfig:
upstreams:
- id: static
path: /
static: true
staticCode: 200
# Response headers passed to Dashboard via Nginx
injectResponseHeaders:
- name: Authorization
values:
- claim: id_token
prefix: "Bearer "
- name: X-Auth-Request-User
values:
- claim: email
- name: X-Auth-Request-Email
values:
- claim: email
- name: X-Auth-Request-Groups
values:
- claim: groups
server:
BindAddress: "0.0.0.0:4180"
extraArgs:
cookie-domain: ".your-domain.com"
whitelist-domain: ".your-domain.com"
email-domain: "*" # Or restrict to your organization
skip-provider-button: true
reverse-proxy: true
pass-authorization-header: true
set-xauthrequest: true
sessionStorage:
type: redis
redis:
enabled: true
auth:
enabled: true
ingress:
enabled: true
className: nginx
hosts:
- OAuth2 Proxy.your-domain.com
path: /oauth2
pathType: Prefix
```
### Kubernetes Dashboard Ingress
**Critical**: The Ingress must include `Authorization` in the `auth-response-headers` annotation:
```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: kubernetes-dashboard
namespace: kubernetes-dashboard
annotations:
nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
# OAuth2 Proxy authentication
nginx.ingress.kubernetes.io/auth-url: "https://OAuth2 Proxy.your-domain.com/oauth2/auth"
nginx.ingress.kubernetes.io/auth-signin: "https://OAuth2 Proxy.your-domain.com/oauth2/start?rd=$scheme://$best_http_host$request_uri"
# Include Authorization header with bearer token
nginx.ingress.kubernetes.io/auth-response-headers: "Authorization, X-Auth-Request-User, X-Auth-Request-Email"
# Buffer sizes for large tokens (Entra tokens can exceed 4KB)
nginx.ingress.kubernetes.io/proxy-buffer-size: "256k"
nginx.ingress.kubernetes.io/proxy-buffers-number: "4"
nginx.ingress.kubernetes.io/proxy-busy-buffers-size: "256k"
spec:
ingressClassName: nginx
tls:
- hosts:
- dashboard.your-domain.com
secretName: dashboard-tls
rules:
- host: dashboard.your-domain.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: kubernetes-dashboard-kong-proxy
port:
number: 443
```
### RBAC Configuration
Assign Kubernetes permissions to Entra ID users or groups.
**User-based:**
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: dashboard-user-admin
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: User
name: "user@your-domain.com" # Email from Entra ID token
apiGroup: rbac.authorization.k8s.io
```
**Group-based (recommended):**
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: dashboard-admins-group
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: Group
name: "YOUR_ENTRA_GROUP_OBJECT_ID" # Entra ID Group Object ID
apiGroup: rbac.authorization.k8s.io
```
For production, create custom roles with limited permissions instead of using `cluster-admin`.
### Troubleshooting
**Dashboard still asks for token after authentication**
Verify that:
1. `injectResponseHeaders` in alphaConfig includes Authorization header with id_token claim
2. Dashboard Ingress includes `Authorization` in `auth-response-headers` annotation
3. Buffer sizes are sufficient for large tokens (set to 256k as shown above)
4. Check OAuth2 Proxy logs for successful token generation: `kubectl logs -n OAuth2 Proxy <pod-name>`
**"Unauthorized" or "Invalid token" errors**
Common causes:
1. User/group not configured in Kubernetes RBAC
- Check: `kubectl get clusterrolebindings | grep <user-email>`
2. Token validation failed
- Verify AKS Entra ID integration is enabled
- Check Dashboard logs: `kubectl logs -n kubernetes-dashboard <pod-name>`
3. Incorrect OAuth2 Proxy configuration
- Ensure `reverse-proxy: true` is set
- Verify issuer URL matches your tenant
**Groups not included in token**
To include groups in the token:
1. In Entra ID App Registration, go to **Token configuration**
2. Add **groups claim** and select security groups
3. Or edit the manifest and add: `"groupMembershipClaims": "SecurityGroup"`
4. For 200+ groups, ensure scope includes `User.Read` for group overage handling
5. Verify groups appear in token: check OAuth2 Proxy logs
**Session expires too quickly**
Configure cookie expiration:
```yaml
extraArgs:
cookie-expire: "24h"
cookie-refresh: "1h"
```
### Using Workload Identity (Passwordless)
For production environments, use Workload Identity instead of client secrets:
```yaml
config:
clientID: "YOUR_CLIENT_ID"
secretKeys: # Exclude client-secret
- client-id
- cookie-secret
cookieSecret: "YOUR_COOKIE_SECRET"
serviceAccount:
annotations:
azure.workload.identity/client-id: YOUR_CLIENT_ID
azure.workload.identity/tenant-id: YOUR_TENANT_ID
podLabels:
azure.workload.identity/use: "true"
alphaConfig:
enabled: true
configData:
providers:
- id: azure-entra
provider: entra-id
clientID: YOUR_CLIENT_ID
oidcConfig:
issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0
# ... other config
entraIdConfig:
federatedTokenAuth: true
```
This requires:
- AKS with OIDC issuer and Workload Identity enabled
- Federated identity credential configured in Entra ID App Registration
- Service account annotated with `azure.workload.identity/client-id`
For detailed Workload Identity setup instructions, see the [Workload Identity section](../providers/ms_entra_id.md#workload-identity) in the Microsoft Entra ID provider documentation.
## Integration with Other Providers
While this guide focuses on Azure Entra ID, Kubernetes Dashboard can be integrated with other OAuth2 providers supported by OAuth2 Proxy. The key requirements remain the same:
1. **Authorization Header**: Pass the bearer token via the `Authorization` header
2. **RBAC Configuration**: Configure Kubernetes RBAC for your authentication provider's users/groups
3. **Buffer Sizes**: Ensure adequate buffer sizes for tokens (especially important for OIDC providers)
For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation.

View File

@ -0,0 +1,107 @@
---
id: nginx
title: Nginx
---
Configure OAuth2 Proxy with Nginx using the `auth_request` directive. Includes examples for both standalone Nginx configurations and Kubernetes ingress-nginx with annotations.
**Key features:**
- Support for `auth_request` directive
- Kubernetes Ingress annotations
- Multi-part cookie handling for large tokens
- Session refresh support
## Configuring for use with the Nginx `auth_request` directive
**This option requires `--reverse-proxy` option to be set.**
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-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-Forwarded-Uri $request_uri;
# 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 =403 /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 can configure the same behavior with the following annotations on your Ingress resource:
```yaml
nginx.ingress.kubernetes.io/auth-url: "https://<oauth2-proxy-fqdn>/oauth2/auth"
nginx.ingress.kubernetes.io/auth-signin: "https://<oauth2-proxy-fqdn>/oauth2/start?rd=$escaped_request_uri"
```
This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/.
It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure).
:::tip Kubernetes Dashboard with Azure Entra ID
For a complete example of integrating oauth2-proxy with Kubernetes Dashboard on AKS using Azure Entra ID, including RBAC configuration and troubleshooting, see the [Kubernetes Dashboard on AKS](../providers/ms_entra_id.md#kubernetes-dashboard-on-aks) section in the Microsoft Entra ID provider documentation.
:::
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=".
:::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,184 @@
---
id: traefik
title: Traefik
---
Set up OAuth2 Proxy with Traefik v2 using the `ForwardAuth` middleware. Includes examples for both error-based redirects and static upstream configurations.
**Key features:**
- ForwardAuth middleware integration
- Error middleware for 401 redirects
- Static upstream configuration (202 responses)
- Dynamic file configuration examples
## 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/http/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?rd={url}"
```
### 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/http/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
- `--reverse-proxy=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

@ -14,7 +14,7 @@ OAuth2 Proxy responds directly to the following endpoints. All other endpoints w
- /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/integration#configuring-for-use-with-the-nginx-auth_request-directive)
- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integrations/nginx)
- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages
### Sign out

View File

@ -0,0 +1,26 @@
---
id: behaviour
title: Behaviour
---
1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints.
- Exception: If the request matches a skipped route (configured via `--skip-auth-route`):
- Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request.
- Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds.
2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default.
- Ajax Requests: If the request has `Accept: application/json` header:
- Returns `401 Unauthorized`.
- Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT:
- Redirects to the login page by default.
- Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`.
3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set.
4. Request Forwarding: The authenticated request is processed based on configuration:
- Forwarded to the configured upstream application with added user info and authentication headers, or
- Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik).
---
Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management.

View File

@ -0,0 +1,91 @@
---
id: contribution
title: Contribution Guide
---
We track bugs and issues using Github.
If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes.
If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo.
Please mention open bug issue number(s) within your PR if applicable.
We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension.
# Go version
See the `go.mod` file in the root of this repository for the version of Go used by this project.
You can follow [the installation guide for Go](https://go.dev/doc/install),
and you can find this specific Go version on [the Go downloads page](https://go.dev/dl/).
# Preparing your fork
Clone your fork, create a feature branch and update the depedencies to get started.
```bash
git clone git@github.com:<YOUR_FORK>/oauth2-proxy
cd oauth2-proxy
git branch feature/<BRANCH_NAME>
git push --set-upstream origin feature/<BRANCH_NAME>
go mod download
```
# Testing / Debugging
For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`.
![Debugging Tab](/img/debug-tab.png)
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch OAuth2 Proxy with Dex",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}",
"args": [
"--config",
// The following configuration contains settings for a locally deployed
// upstream and dex as an idetity provider
"contrib/local-environment/oauth2-proxy.cfg"
]
},
{
"name": "Launch OAuth2 Proxy with Keycloak",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}",
"args": [
"--config",
// The following configuration contains settings for a locally deployed
// upstream and keycloak as an idetity provider
"contrib/local-environment/oauth2-proxy-keycloak.cfg"
]
}
]
}
```
Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP.
Inside the `contrib/local-environment` directory you can use the `Makefile` for
starting different example setups:
- Dex as your IdP: `make up` or `make down`
- Dex as your IdP using the alpha-config: `make alpha-config-up`
- Keycloak as your IdP: `make keycloak-up`
- Dex as your IdP & nginx reverse proxy: `make nginx-up`
- and many more...
Check out the `Makefile` to see what is available.
The username and password for all setups is usually `admin@example.com` and `password`.
The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me
- OAuth2 Proxy: http://oauth2-proxy.localtest.me:4180
- Upstream: http://httpbin.localtest.me:8080
- Dex: http://dex.localtest.me:5556

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.md](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS.md) 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,637 @@
---
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: ...
...: ...
providers:
- id: ...
...: ...
cookie:
secret: ...
...: ...
injectRequestHeaders:
- secretSource:
...: ...
injectResponseHeaders:
- claimSource:
...: ...
```
Please browse the [reference](#configuration-reference) below for the structure
of the new configuration format.
# Migration Guide
This section details breaking changes and migration steps for moving to the new
alpha configuration format.
## Migrating header injections in v7.14.0
From v7.14.0 onward, header injection sources must be explicitly nested. If you
previously relied on squashed fields, update to the new structure before
upgrading:
```yaml
# before v7.14.0
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claim: user
- name: X-Custom-Secret-header
values:
- value: my-super-secret
# v7.14.0 and later
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claimSource:
claim: user
- name: X-Custom-Secret-header
values:
- secretSource:
value: my-super-secret
```
## 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
```
### How to use environment variables
The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file.
When using environment variables, your yaml will look like this:
```yaml
providers:
- provider: azure
clientSecret: ${CLIENT_SECRET}
...
```
Where CLIENT_SECRET is an environment variable.
More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs)
### How to inject custom headers
Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML.
```yaml
injectRequestHeaders:
- name: "X-User-Email"
values:
- claimSource:
claim: "email" # extract the email claim contents from the id token
- name: "X-Static-Secret"
values:
# secrets need to be encoded with base64 when directly in the yaml config but will be send decoded
- secretSource:
value: "c3VwZXItc2VjcmV0"
- name: "X-Static-File-Secret"
- secretSource:
fromFile: "/path/to/my/secret"
- name: "X-Static-Env-Secret"
- secretSource:
value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded
injectResponseHeaders:
# Following will result in a header "Authorization: Basic <user:password> (encoded)"
- name: "Authorization"
values:
- claimSource:
claim: user
prefix: "Basic "
basicAuthPassword:
value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password
```
**Value sources:**
* `claimSource` - `claim` (session claims either from id token or from profile URL)
* `secretSource` - `value` (base64), `fromFile` (file path)
**Request option:** `preserveRequestValue: true` retains existing header values
**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
## 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`
<!-- Legacy provider FlagSet -->
- `client-id`/`client_id`
- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file`
- `provider`
- `provider-display-name`/`provider_display_name`
- `provider-ca-file`/`provider_ca_files`
- `login-url`/`login_url`
- `redeem-url`/`redeem_url`
- `profile-url`/`profile_url`
- `resource`
- `validate-url`/`validate_url`
- `scope`
- `prompt`
- `approval-prompt`/`approval_prompt`
- `acr-values`/`acr_values`
- `user-id-claim`/`user_id_claim`
- `allowed-group`/`allowed_groups`
- `allowed-role`/`allowed_roles`
- `jwt-key`/`jwt_key`
- `jwt-key-file`/`jwt_key_file`
- `pubjwk-url`/`pubjwk_url`
and all provider-specific options, i.e. any option whose name includes `oidc`,
`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to
use any of these options via flags or via config when `--alpha-config` is
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!!! -->
### ADFSOptions
(**Appears on:** [Provider](#provider))
| Field | Type | Description |
| ----- | ---- | ----------- |
| `skipScope` | _bool_ | Skip adding the scope parameter in login request<br/>Default value is 'false' |
### 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 |
| ----- | ---- | ----------- |
| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig 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. |
| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not<br/>yet working.** [This feature is tracked in<br/>#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) |
### AzureOptions
(**Appears on:** [Provider](#provider))
| Field | Type | Description |
| ----- | ---- | ----------- |
| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint<br/>Default value is 'common' |
| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph<br/>Default value is 'id' |
### BitbucketOptions
(**Appears on:** [Provider](#provider))
| Field | Type | Description |
| ----- | ---- | ----------- |
| `team` | _string_ | Team sets restrict logins to members of this team |
| `repository` | _string_ | Repository sets restrict logins to user with access to this repository |
### 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. Available claims: `access_token` `id_token` `created_at`<br/>`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. |
| `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. |
### GitHubOptions
(**Appears on:** [Provider](#provider))
| Field | Type | Description |
| ----- | ---- | ----------- |
| `org` | _string_ | Org sets restrict logins to members of this organisation |
| `team` | _string_ | Team sets restrict logins to members of this team |
| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository |
| `token` | _string_ | Token is the token to use when verifying repository collaborators<br/>it must have push access to the repository |
| `users` | _[]string_ | Users allows users with these usernames to login<br/>even if they do not belong to the specified org and team or collaborators |
### GitLabOptions
(**Appears on:** [Provider](#provider))
| Field | Type | Description |
| ----- | ---- | ----------- |
| `group` | _[]string_ | Group sets restrict logins to members of this group |
| `projects` | _[]string_ | Projects restricts logins to members of these projects |
### GoogleOptions
(**Appears on:** [Provider](#provider))
| Field | Type | Description |
| ----- | ---- | ----------- |
| `group` | _[]string_ | Groups sets restrict logins to members of this Google group |
| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls |
| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials |
| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON |
| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials |
| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim |
| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly |
### 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 applies to injected request headers.<br/>Defaults to false (headers that match this header will be stripped). |
| `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name<br/>According to RFC 7230 Section 3.2 there aren't any rules about<br/>capitalization of header names, but the standard practice is to use<br/>Title-Case (e.g. X-Forwarded-For). By default, header names will be<br/>normalized to Title-Case and any incoming headers that match will be<br/>treated as the same header. Additionally underscores (_) in header names<br/>will be converted to dashes (-) when normalizing.<br/>Defaults to false (header names will be normalized). |
| `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. Available claims: `access_token` `id_token` `created_at`<br/>`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. |
| `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. |
### KeycloakOptions
(**Appears on:** [Provider](#provider))
| Field | Type | Description |
| ----- | ---- | ----------- |
| `groups` | _[]string_ | Group enables to restrict login to members of indicated group |
| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) |
### LoginGovOptions
(**Appears on:** [Provider](#provider))
| Field | Type | Description |
| ----- | ---- | ----------- |
| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, |
| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT |
| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint |
### LoginURLParameter
(**Appears on:** [Provider](#provider))
LoginURLParameter is the configuration for a single query parameter that
can be passed through from the `/oauth2/start` endpoint to the IdP login
URL. The "default" option specifies the default value or values (if any)
that will be passed to the IdP for this parameter, and "allow" is a list
of options for ways in which this parameter can be set or overridden via
the query string to `/oauth2/start`.
If _only_ a default is specified and no "allow" then the parameter is
effectively fixed - the default value will always be used and anything
passed to the start URL will be ignored. If _only_ "allow" is specified
but no default then the parameter will only be passed on to the IdP if
the caller provides it, and no value will be sent otherwise.
Examples:
# A parameter whose value is fixed
```
name: organization
default:
- myorg
```
A parameter that is not passed by default, but may be set to one of a
fixed set of values
```
name: prompt
allow:
- value: login
- value: consent
- value: select_account
```
A parameter that is passed by default but may be overridden by one of
a fixed set of values
```
name: prompt
default: ["login"]
allow:
- value: consent
- value: select_account
```
A parameter that may be overridden, but only by values that match a
regular expression. For example to restrict `login_hint` to email
addresses in your organization's domain:
```
name: login_hint
allow:
- pattern: '^[^@]*@example\.com$'
# this allows at most one "@" sign, and requires "example.com" domain.
```
Note that the YAML rules around exactly which characters are allowed
and/or require escaping in different types of string literals are
convoluted. For regular expressions the single quoted form is simplest
as backslash is not considered to be an escape character. Alternatively
use the "chomped block" format `|-`:
```
- pattern: |-
^[^@]*@example\.com$
```
The hyphen is important, a `|` block would have a trailing newline
character.
| Field | Type | Description |
| ----- | ---- | ----------- |
| `name` | _string_ | Name specifies the name of the query parameter. |
| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be<br/>passed to the IdP if not overridden. |
| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be<br/>overridden via the query string to `/oauth2/start`. Only<br/>values that match one or more of the allow rules will be<br/>forwarded to the IdP. |
### MicrosoftEntraIDOptions
(**Appears on:** [Provider](#provider))
| Field | Type | Description |
| ----- | ---- | ----------- |
| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are<br/>issued by different issuers and OIDC issuer verification needs to be disabled.<br/>When not specified, all tenants are allowed. Redundant for single-tenant apps<br/>(regular ID token validation matches the issuer). |
| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected<br/>by Entra Workload Identity plugin, instead of client secret. |
### OIDCOptions
(**Appears on:** [Provider](#provider))
| Field | Type | Description |
| ----- | ---- | ----------- |
| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL<br/>eg: https://accounts.google.com |
| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified<br/>default set to 'false' |
| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL<br/>default set to 'false' |
| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match<br/>the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked<br/>after the initial OAuth redeem & subsequent token refreshes.<br/>default set to 'true'<br/>Warning: In a future release, this will change to 'false' by default for enhanced security. |
| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints<br/>default set to 'false' |
| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL<br/>eg: https://www.googleapis.com/oauth2/v3/certs |
| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use<br/>for verifying JWT tokens |
| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,<br/>default set to 'email' |
| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups<br/>default set to 'groups' |
| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID<br/>default set to 'email' |
| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id<br/>By default `aud` claim is used for verification. |
| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed<br/>to pass verification in addition to the client id. |
### Provider
(**Appears on:** [Providers](#providers))
Provider holds all configuration for a single provider
| Field | Type | Description |
| ----- | ---- | ----------- |
| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider<br/>This value is required for all providers. |
| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider<br/>This value is required for all providers. |
| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file<br/>containing the OAuth Client Secret, it will be used if ClientSecret is not set. |
| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. |
| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. |
| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. |
| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. |
| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. |
| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. |
| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. |
| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. |
| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider<br/>or providers utilize OIDC configurations. |
| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. |
| `id` | _string_ | ID should be a unique identifier for the provider.<br/>This value is required for all providers. |
| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider<br/>must be set from the supported providers group,<br/>otherwise 'Google' is set as default |
| `name` | _string_ | Name is the providers display name<br/>if set, it will be shown to the users in the login page. |
| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.<br/>If not specified, the default Go trust sources are used instead |
| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used<br/>If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. |
| `loginURL` | _string_ | LoginURL is the authentication endpoint |
| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL |
| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request |
| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint |
| `profileURL` | _string_ | ProfileURL is the profile access endpoint |
| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token<br/>default set to 'false' |
| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) |
| `validateURL` | _string_ | ValidateURL is the access token validation endpoint |
| `scope` | _string_ | Scope is the OAuth scope specification |
| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group |
| `code_challenge_method` | _string_ | The code challenge method |
| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session |
### ProviderType
#### (`string` alias)
(**Appears on:** [Provider](#provider))
ProviderType is used to enumerate the different provider type options
Valid options are: adfs, azure, bitbucket, digitalocean facebook, github,
gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud
and oidc.
### Providers
#### ([[]Provider](#provider) alias)
(**Appears on:** [AlphaOptions](#alphaoptions))
The provider can be selected using the `provider` configuration value, or
set in the [`providers` array using
AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers).
However, [**the feature to implement multiple providers is not
complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926).
### 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 address on which to serve traffic.<br/>Leave blank or set to "-" to disable. |
| `secureBindAddress` | _string_ | SecureBindAddress is 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 and further configuration for the TLS server. |
### TLS
(**Appears on:** [Server](#server))
TLS contains the information for loading a TLS certificate and key
as well as an optional minimal TLS version that is acceptable.
| Field | Type | Description |
| ----- | ---- | ----------- |
| `key` | _[SecretSource](#secretsource)_ | Key is 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. |
| `minVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.<br/>E.g. Set to "TLS1.3" to select TLS version 1.3 |
| `cipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.<br/>E.g.:<br/>- TLS_RSA_WITH_RC4_128_SHA<br/>- TLS_RSA_WITH_AES_256_GCM_SHA384<br/>If not specified, the default Go safe cipher list is used.<br/>List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). |
### URLParameterRule
(**Appears on:** [LoginURLParameter](#loginurlparameter))
URLParameterRule represents a rule by which query parameters
passed to the `/oauth2/start` endpoint are checked to determine whether
they are valid overrides for the given parameter passed to the IdP's
login URL. Either Value or Pattern should be supplied, not both.
| Field | Type | Description |
| ----- | ---- | ----------- |
| `value` | _string_ | A Value rule matches just this specific value |
| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by<br/>some substring of the value. The expression is _not_ automatically<br/>anchored to the start and end of the value, if you _want_ to restrict<br/>the whole parameter value you must anchor it yourself with `^` and `$`. |
### Upstream
(**Appears on:** [UpstreamConfig](#upstreamconfig))
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.<br/>Path can also take a pattern when used with RewriteTarget.<br/>Path segments can be captured and matched using regular experessions.<br/>Eg:<br/>- `^/foo$`: Match only the explicit path `/foo`<br/>- `^/bar/$`: Match any path prefixed with `/bar/`<br/>- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget |
| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to<br/>the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem<br/>(for a `file:` upstream).<br/>Use the Path to capture segments for reuse within the rewrite target.<br/>Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite<br/>the request `/baz/abc/123` to `/foo/abc/123` before proxying to the<br/>upstream server. Or if the upstream were `file:///app`, a request for<br/>`/baz/info.html` would return the contents of the file `/app/foo/info.html`. |
| `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/>between OAuth2 Proxy and the upstream 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_ | 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. |
| `timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.<br/>Defaults to 30 seconds. |
| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.<br/>Defaults to false. |
### UpstreamConfig
(**Appears on:** [AlphaOptions](#alphaoptions))
UpstreamConfig is a collection of definitions for upstream servers.
| Field | Type | Description |
| ----- | ---- | ----------- |
| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls<br/>like: "/%2F/" which would otherwise be redirected to "/" |
| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.<br/>Requests will be proxied to this upstream if the path matches the request path. |

View File

@ -0,0 +1,218 @@
---
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: ...
...: ...
providers:
- id: ...
...: ...
cookie:
secret: ...
...: ...
injectRequestHeaders:
- secretSource:
...: ...
injectResponseHeaders:
- claimSource:
...: ...
```
Please browse the [reference](#configuration-reference) below for the structure
of the new configuration format.
# Migration Guide
This section details breaking changes and migration steps for moving to the new
alpha configuration format.
## Migrating header injections in v7.14.0
From v7.14.0 onward, header injection sources must be explicitly nested. If you
previously relied on squashed fields, update to the new structure before
upgrading:
```yaml
# before v7.14.0
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claim: user
- name: X-Custom-Secret-header
values:
- value: my-super-secret
# v7.14.0 and later
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claimSource:
claim: user
- name: X-Custom-Secret-header
values:
- secretSource:
value: my-super-secret
```
## 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
```
### How to use environment variables
The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file.
When using environment variables, your yaml will look like this:
```yaml
providers:
- provider: azure
clientSecret: ${CLIENT_SECRET}
...
```
Where CLIENT_SECRET is an environment variable.
More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs)
### How to inject custom headers
Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML.
```yaml
injectRequestHeaders:
- name: "X-User-Email"
values:
- claimSource:
claim: "email" # extract the email claim contents from the id token
- name: "X-Static-Secret"
values:
# secrets need to be encoded with base64 when directly in the yaml config but will be send decoded
- secretSource:
value: "c3VwZXItc2VjcmV0"
- name: "X-Static-File-Secret"
- secretSource:
fromFile: "/path/to/my/secret"
- name: "X-Static-Env-Secret"
- secretSource:
value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded
injectResponseHeaders:
# Following will result in a header "Authorization: Basic <user:password> (encoded)"
- name: "Authorization"
values:
- claimSource:
claim: user
prefix: "Basic "
basicAuthPassword:
value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password
```
**Value sources:**
* `claimSource` - `claim` (session claims either from id token or from profile URL)
* `secretSource` - `value` (base64), `fromFile` (file path)
**Request option:** `preserveRequestValue: true` retains existing header values
**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
## 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`
<!-- Legacy provider FlagSet -->
- `client-id`/`client_id`
- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file`
- `provider`
- `provider-display-name`/`provider_display_name`
- `provider-ca-file`/`provider_ca_files`
- `login-url`/`login_url`
- `redeem-url`/`redeem_url`
- `profile-url`/`profile_url`
- `resource`
- `validate-url`/`validate_url`
- `scope`
- `prompt`
- `approval-prompt`/`approval_prompt`
- `acr-values`/`acr_values`
- `user-id-claim`/`user_id_claim`
- `allowed-group`/`allowed_groups`
- `allowed-role`/`allowed_roles`
- `jwt-key`/`jwt_key`
- `jwt-key-file`/`jwt_key_file`
- `pubjwk-url`/`pubjwk_url`
and all provider-specific options, i.e. any option whose name includes `oidc`,
`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to
use any of these options via flags or via config when `--alpha-config` is
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,63 @@
---
id: caddy
title: Caddy
---
Integrate OAuth2 Proxy with Caddy v2 using the `forward_auth` directive.
**Key features:**
- Simple forward_auth setup
- Automatic header handling
- Custom error handling and redirects
## Configuring for use with the Caddy (v2) `forward_auth` directive
The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`.
This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint.
**Following options need to be set on `oauth2-proxy`:**
- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly
```nginx title="Caddyfile"
example.com {
# Requests to /oauth2/* are proxied to oauth2-proxy without authentication.
# You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive.
handle /oauth2/* {
reverse_proxy oauth2-proxy.internal:4180 {
# oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers.
# The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers.
header_up X-Real-IP {remote_host}
header_up X-Forwarded-Uri {uri}
}
}
# Requests to other paths are first processed by oauth2-proxy for authentication.
handle {
forward_auth oauth2-proxy.internal:4180 {
uri /oauth2/auth
# oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers.
# The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers.
header_up X-Real-IP {remote_host}
# If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream.
# Make sure to configure the --set-xauthrequest flag to enable this feature.
#copy_headers X-Auth-Request-User X-Auth-Request-Email
# If oauth2-proxy returns a 401 status, redirect the client to the sign-in page.
@error status 401
handle_response @error {
redir * /oauth2/sign_in?rd={scheme}://{host}{uri}
}
}
# If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream.
reverse_proxy upstream.internal:3000
}
}
```
:::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,105 @@
---
id: headlamp
title: Headlamp
---
Modern, actively maintained Kubernetes web UI with OAuth2 Proxy integration examples.
**Key features:**
- Active development and maintenance
- Modern, intuitive interface
- Multi-cluster support
- Plugin system
- Works with all OAuth2 providers
## Configuring for use with Headlamp
[Headlamp](https://headlamp.dev/) is a modern, user-friendly Kubernetes web UI that can be integrated with OAuth2 Proxy for authentication. This is a recommended alternative to the deprecated Kubernetes Dashboard.
### Architecture
```
User → Ingress → OAuth2 Proxy → Authentication Provider (e.g., Azure Entra ID)
Headlamp
```
### Prerequisites
- Kubernetes cluster (e.g., AKS, EKS, GKE, or self-hosted)
- Headlamp installed in the cluster
- OAuth2 provider configured (Azure Entra ID, Google, GitHub, etc.)
- Ingress controller (Nginx, Traefik, etc.)
### Configuration Overview
When integrating Headlamp with OAuth2 Proxy, the OAuth2 Proxy acts as a reverse proxy in front of Headlamp:
1. User requests access to Headlamp
2. Ingress forwards to OAuth2 Proxy
3. OAuth2 Proxy authenticates the user via the OAuth2 provider
4. After successful authentication, OAuth2 Proxy proxies requests to Headlamp
5. Headlamp receives the authenticated user information via headers
### OAuth2 Proxy Configuration
Configure OAuth2 Proxy to proxy to the Headlamp service:
```yaml
upstreamConfig:
upstreams:
- id: headlamp
path: /
uri: http://headlamp-service.headlamp-namespace.svc.cluster.local:4466
```
Enable the necessary headers:
```yaml
extraArgs:
reverse-proxy: true
pass-authorization-header: true
set-xauthrequest: true
email-domain: "*" # Or restrict to your organization
```
### Example with Azure Entra ID on AKS
For detailed instructions on deploying Headlamp with OAuth2 Proxy on Azure Kubernetes Service using Azure Entra ID, see the official Headlamp documentation:
https://headlamp.dev/docs/latest/installation/in-cluster/aks-cluster-oauth/
Key steps include:
1. **Set up AKS with OIDC**: Enable Microsoft Entra ID authentication with Kubernetes RBAC
2. **Create Azure App Registration**: Configure redirect URI and create client secret
3. **Deploy Headlamp**: Install Headlamp via Helm in your cluster
4. **Deploy OAuth2 Proxy**: Configure OAuth2 Proxy with Entra ID provider settings and upstream pointing to Headlamp
5. **Configure Ingress**: Set up Ingress to route traffic through OAuth2 Proxy to Headlamp
6. **Set RBAC Policies**: Apply Kubernetes RBAC bindings based on users or groups
### Integration with Other Providers
The same integration pattern works with other OAuth2 providers supported by OAuth2 Proxy:
- **Google**: Use the Google provider configuration
- **GitHub**: Use the GitHub provider configuration
- **GitLab**: Use the GitLab provider configuration
- **Keycloak**: Use the Keycloak OIDC provider configuration
- **Any OIDC Provider**: Use the generic OIDC provider configuration
For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation.
### Benefits Over Kubernetes Dashboard
Headlamp offers several advantages:
- **Active Development**: Headlamp is actively maintained and developed
- **Modern UI**: Clean, intuitive interface with better UX
- **Plugin System**: Extensible with custom plugins
- **Multi-cluster Support**: Built-in support for managing multiple clusters
- **Desktop App**: Available as both web UI and desktop application
:::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,41 @@
---
id: index
title: Integrations
---
This section provides configuration examples for integrating OAuth2 Proxy with various reverse proxies, ingress controllers, and Kubernetes web UIs.
## Reverse Proxies and Ingress Controllers
OAuth2 Proxy can be integrated with popular reverse proxies and ingress controllers to add authentication to your applications:
- [Nginx](nginx.md)
- [Traefik](traefik.md)
- [caddy](caddy.md)
## Kubernetes Web UIs
OAuth2 Proxy can also be used to add authentication to Kubernetes web user interfaces:
- [Headlamp](headlamp.md) ✨ *Recommended*
- [Kubernetes Dashboard](kubernetes-dashboard.md) ⚠️ *Deprecated*
:::tip
When integrating with Kubernetes web UIs, make sure to:
1. Configure the Ingress to pass the Authorization header with the bearer token
2. Increase buffer sizes for large OIDC tokens (especially with Azure Entra ID)
3. Set up appropriate Kubernetes RBAC permissions for your users or groups
:::
## General Requirements
Most integrations require the following OAuth2 Proxy configuration:
- `--reverse-proxy=true`: Required to correctly handle `X-Forwarded-*` headers
- **Session storage**: For production deployments with large tokens due to a lot of claims like AD groups, use `--session-store-type=redis`
For provider-specific configuration, see the [OAuth Provider Configuration](../providers/index.md) documentation.
:::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,289 @@
---
id: kubernetes-dashboard
title: Kubernetes Dashboard
---
:::warning Deprecated Project
Kubernetes Dashboard has been deprecated and discontinued as of January 2025. See the [official announcement](https://github.com/kubernetes/dashboard/commit/0ba796dce6916bb6ca5da5ca0b3ab22cecfd1e18) for more information.
You may want to consider alternative solutions such as [Headlamp](./headlamp.md).
:::
## Kubernetes Dashboard on AKS with Azure Entra ID
Integration guide for the deprecated Kubernetes Dashboard, including comprehensive Azure Entra ID configuration on AKS with detailed troubleshooting and RBAC setup.
### Architecture
```
User → Nginx Ingress → OAuth2 Proxy → Entra ID
Kubernetes Dashboard
```
The integration flow:
1. Unauthenticated requests to Dashboard are intercepted by Nginx Ingress
2. Nginx redirects to OAuth2 Proxy for authentication
3. OAuth2 Proxy redirects to Entra ID login
4. After successful authentication, OAuth2 Proxy receives ID token from Entra ID
5. OAuth2 Proxy sets Authorization header with the bearer token
6. Nginx forwards the request with token to Kubernetes Dashboard
7. Dashboard validates the token and grants access based on AKS RBAC configuration
### Prerequisites
- AKS cluster with Entra ID integration enabled
- Kubernetes Dashboard installed (version 7.x or later)
- NGINX Ingress Controller installed
- Entra ID App Registration configured with:
- Redirect URI: `https://your-oauth2-domain.com/oauth2/callback`
- API Permissions: `openid`, `email`, `profile`
- Groups claim enabled (if using group-based RBAC)
- Users or groups assigned appropriate Kubernetes RBAC permissions
### Alpha Configuration Example
Using [Alpha Configuration](../alpha_config.md) with the OAuth2 Proxy Helm chart:
```yaml
alphaConfig:
enabled: true
configData:
providers:
- id: azure-entra
provider: entra-id
clientID: YOUR_CLIENT_ID
clientSecret: YOUR_CLIENT_SECRET
oidcConfig:
issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0
audienceClaims:
- aud
emailClaim: email
groupsClaim: groups
userIDClaim: oid
scope: openid email profile
upstreamConfig:
upstreams:
- id: static
path: /
static: true
staticCode: 200
# Response headers passed to Dashboard via Nginx
injectResponseHeaders:
- name: Authorization
values:
- claim: id_token
prefix: "Bearer "
- name: X-Auth-Request-User
values:
- claim: email
- name: X-Auth-Request-Email
values:
- claim: email
- name: X-Auth-Request-Groups
values:
- claim: groups
server:
BindAddress: "0.0.0.0:4180"
extraArgs:
cookie-domain: ".your-domain.com"
whitelist-domain: ".your-domain.com"
email-domain: "*" # Or restrict to your organization
skip-provider-button: true
reverse-proxy: true
pass-authorization-header: true
set-xauthrequest: true
sessionStorage:
type: redis
redis:
enabled: true
auth:
enabled: true
ingress:
enabled: true
className: nginx
hosts:
- OAuth2 Proxy.your-domain.com
path: /oauth2
pathType: Prefix
```
### Kubernetes Dashboard Ingress
**Critical**: The Ingress must include `Authorization` in the `auth-response-headers` annotation:
```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: kubernetes-dashboard
namespace: kubernetes-dashboard
annotations:
nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
# OAuth2 Proxy authentication
nginx.ingress.kubernetes.io/auth-url: "https://OAuth2 Proxy.your-domain.com/oauth2/auth"
nginx.ingress.kubernetes.io/auth-signin: "https://OAuth2 Proxy.your-domain.com/oauth2/start?rd=$scheme://$best_http_host$request_uri"
# Include Authorization header with bearer token
nginx.ingress.kubernetes.io/auth-response-headers: "Authorization, X-Auth-Request-User, X-Auth-Request-Email"
# Buffer sizes for large tokens (Entra tokens can exceed 4KB)
nginx.ingress.kubernetes.io/proxy-buffer-size: "256k"
nginx.ingress.kubernetes.io/proxy-buffers-number: "4"
nginx.ingress.kubernetes.io/proxy-busy-buffers-size: "256k"
spec:
ingressClassName: nginx
tls:
- hosts:
- dashboard.your-domain.com
secretName: dashboard-tls
rules:
- host: dashboard.your-domain.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: kubernetes-dashboard-kong-proxy
port:
number: 443
```
### RBAC Configuration
Assign Kubernetes permissions to Entra ID users or groups.
**User-based:**
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: dashboard-user-admin
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: User
name: "user@your-domain.com" # Email from Entra ID token
apiGroup: rbac.authorization.k8s.io
```
**Group-based (recommended):**
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: dashboard-admins-group
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: Group
name: "YOUR_ENTRA_GROUP_OBJECT_ID" # Entra ID Group Object ID
apiGroup: rbac.authorization.k8s.io
```
For production, create custom roles with limited permissions instead of using `cluster-admin`.
### Troubleshooting
**Dashboard still asks for token after authentication**
Verify that:
1. `injectResponseHeaders` in alphaConfig includes Authorization header with id_token claim
2. Dashboard Ingress includes `Authorization` in `auth-response-headers` annotation
3. Buffer sizes are sufficient for large tokens (set to 256k as shown above)
4. Check OAuth2 Proxy logs for successful token generation: `kubectl logs -n OAuth2 Proxy <pod-name>`
**"Unauthorized" or "Invalid token" errors**
Common causes:
1. User/group not configured in Kubernetes RBAC
- Check: `kubectl get clusterrolebindings | grep <user-email>`
2. Token validation failed
- Verify AKS Entra ID integration is enabled
- Check Dashboard logs: `kubectl logs -n kubernetes-dashboard <pod-name>`
3. Incorrect OAuth2 Proxy configuration
- Ensure `reverse-proxy: true` is set
- Verify issuer URL matches your tenant
**Groups not included in token**
To include groups in the token:
1. In Entra ID App Registration, go to **Token configuration**
2. Add **groups claim** and select security groups
3. Or edit the manifest and add: `"groupMembershipClaims": "SecurityGroup"`
4. For 200+ groups, ensure scope includes `User.Read` for group overage handling
5. Verify groups appear in token: check OAuth2 Proxy logs
**Session expires too quickly**
Configure cookie expiration:
```yaml
extraArgs:
cookie-expire: "24h"
cookie-refresh: "1h"
```
### Using Workload Identity (Passwordless)
For production environments, use Workload Identity instead of client secrets:
```yaml
config:
clientID: "YOUR_CLIENT_ID"
secretKeys: # Exclude client-secret
- client-id
- cookie-secret
cookieSecret: "YOUR_COOKIE_SECRET"
serviceAccount:
annotations:
azure.workload.identity/client-id: YOUR_CLIENT_ID
azure.workload.identity/tenant-id: YOUR_TENANT_ID
podLabels:
azure.workload.identity/use: "true"
alphaConfig:
enabled: true
configData:
providers:
- id: azure-entra
provider: entra-id
clientID: YOUR_CLIENT_ID
oidcConfig:
issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0
# ... other config
entraIdConfig:
federatedTokenAuth: true
```
This requires:
- AKS with OIDC issuer and Workload Identity enabled
- Federated identity credential configured in Entra ID App Registration
- Service account annotated with `azure.workload.identity/client-id`
For detailed Workload Identity setup instructions, see the [Workload Identity section](../providers/ms_entra_id.md#workload-identity) in the Microsoft Entra ID provider documentation.
## Integration with Other Providers
While this guide focuses on Azure Entra ID, Kubernetes Dashboard can be integrated with other OAuth2 providers supported by OAuth2 Proxy. The key requirements remain the same:
1. **Authorization Header**: Pass the bearer token via the `Authorization` header
2. **RBAC Configuration**: Configure Kubernetes RBAC for your authentication provider's users/groups
3. **Buffer Sizes**: Ensure adequate buffer sizes for tokens (especially important for OIDC providers)
For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation.

View File

@ -0,0 +1,107 @@
---
id: nginx
title: Nginx
---
Configure OAuth2 Proxy with Nginx using the `auth_request` directive. Includes examples for both standalone Nginx configurations and Kubernetes ingress-nginx with annotations.
**Key features:**
- Support for `auth_request` directive
- Kubernetes Ingress annotations
- Multi-part cookie handling for large tokens
- Session refresh support
## Configuring for use with the Nginx `auth_request` directive
**This option requires `--reverse-proxy` option to be set.**
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-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-Forwarded-Uri $request_uri;
# 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 =403 /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 can configure the same behavior with the following annotations on your Ingress resource:
```yaml
nginx.ingress.kubernetes.io/auth-url: "https://<oauth2-proxy-fqdn>/oauth2/auth"
nginx.ingress.kubernetes.io/auth-signin: "https://<oauth2-proxy-fqdn>/oauth2/start?rd=$escaped_request_uri"
```
This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/.
It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure).
:::tip Kubernetes Dashboard with Azure Entra ID
For a complete example of integrating oauth2-proxy with Kubernetes Dashboard on AKS using Azure Entra ID, including RBAC configuration and troubleshooting, see the [Kubernetes Dashboard on AKS](../providers/ms_entra_id.md#kubernetes-dashboard-on-aks) section in the Microsoft Entra ID provider documentation.
:::
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=".
:::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,184 @@
---
id: traefik
title: Traefik
---
Set up OAuth2 Proxy with Traefik v2 using the `ForwardAuth` middleware. Includes examples for both error-based redirects and static upstream configurations.
**Key features:**
- ForwardAuth middleware integration
- Error middleware for 401 redirects
- Static upstream configuration (202 responses)
- Dynamic file configuration examples
## 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/http/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?rd={url}"
```
### 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/http/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
- `--reverse-proxy=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,406 @@
---
id: overview
title: Overview
---
`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings).
## Generating a Cookie Secret
To generate a strong cookie secret use one of the below commands:
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs defaultValue="python">
<TabItem value="python" label="Python">
```shell
python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())'
```
</TabItem>
<TabItem value="bash" label="Bash">
```shell
dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo
```
</TabItem>
<TabItem value="openssl" label="OpenSSL">
```shell
openssl rand -base64 32 | tr -- '+/' '-_'
```
</TabItem>
<TabItem value="powershell" label="PowerShell">
```powershell
# Add System.Web assembly to session, just in case
Add-Type -AssemblyName System.Web
[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_")
```
</TabItem>
<TabItem value="terraform" label="Terraform">
```hcl
# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret
resource "random_password" "cookie_secret" {
length = 32
override_special = "-_"
}
```
</TabItem>
</Tabs>
## 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`
## Config Options
### Command Line Options
| Flag | Description |
| ----------- | -------------------- |
| `--config` | path to config file |
| `--version` | print version string |
### General Provider Options
Provider specific options can be found on their respective subpages.
| Flag / Config Field | Type | Description | Default |
| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
| flag: `--acr-values`<br/>toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` |
| flag: `--allowed-group`<br/>toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | |
| flag: `--approval-prompt`<br/>toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` |
| flag: `--backend-logout-url`<br/>toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | |
| flag: `--client-id`<br/>toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | |
| flag: `--client-secret-file`<br/>toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | |
| flag: `--client-secret`<br/>toml: `client_secret` | string | the OAuth Client Secret | |
| flag: `--code-challenge-method`<br/>toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | |
| flag: `--insecure-oidc-allow-unverified-email`<br/>toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false |
| flag: `--insecure-oidc-skip-issuer-verification`<br/>toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false |
| flag: `--insecure-oidc-skip-nonce`<br/>toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true |
| flag: `--jwt-key-file`<br/>toml: `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 | |
| flag: `--jwt-key`<br/>toml: `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 | |
| flag: `--login-url`<br/>toml: `login_url` | string | Authentication endpoint | |
| flag: `--auth-request-response-mode`<br/>toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | |
| flag: `--oidc-audience-claim`<br/>toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` |
| flag: `--oidc-email-claim`<br/>toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` |
| flag: `--oidc-extra-audience`<br/>toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` |
| flag: `--oidc-groups-claim`<br/>toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` |
| flag: `--oidc-issuer-url`<br/>toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | |
| flag: `--oidc-jwks-url`<br/>toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | |
| flag: `--oidc-public-key-file`<br/>toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list |
| flag: `--profile-url`<br/>toml: `profile_url` | string | Profile access endpoint | |
| flag: `--prompt`<br/>toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` |
| flag: `--provider-ca-file`<br/>toml: `provider_ca_files` | 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. |
| flag: `--provider-display-name`<br/>toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) |
| flag: `--provider`<br/>toml: `provider` | string | OAuth provider | google |
| flag: `--pubjwk-url`<br/>toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | |
| flag: `--redeem-url`<br/>toml: `redeem_url` | string | Token redemption endpoint | |
| flag: `--scope`<br/>toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | |
| flag: `--skip-claims-from-profile-url`<br/>toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false |
| flag: `--skip-oidc-discovery`<br/>toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false |
| flag: `--use-system-trust-store`<br/>toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false |
| flag: `--validate-url`<br/>toml: `validate_url` | string | Access token validation endpoint | |
### Cookie Options
| Flag / Config Field | Type | Description | Default |
| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |
| flag: `--cookie-csrf-expire`<br/>toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m |
| flag: `--cookie-csrf-per-request`<br/>toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false |
| flag: `--cookie-csrf-per-request-limit`<br/>toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" |
| flag: `--cookie-domain`<br/>toml: `cookie_domains` | 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). | |
| flag: `--cookie-expire`<br/>toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s |
| flag: `--cookie-httponly`<br/>toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true |
| flag: `--cookie-name`<br/>toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` |
| flag: `--cookie-path`<br/>toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` |
| flag: `--cookie-refresh`<br/>toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers&nbsp;[^1] | |
| flag: `--cookie-samesite`<br/>toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` |
| flag: `--cookie-secret`<br/>toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | |
| flag: `--cookie-secret-file`<br/>toml: `cookie_secret_file` | string | File containing the cookie secret (must be raw binary, exactly 16, 24, or 32 bytes). Use dd if=/dev/urandom bs=32 count=1 > cookie.secret to generate | |
| flag: `--cookie-secure`<br/>toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true |
[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens)
### Header Options
| Flag / Config Field | Type | Description | Default |
| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| flag: `--basic-auth-password`<br/>toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | |
| flag: `--set-xauthrequest`<br/>toml: `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 |
| flag: `--set-authorization-header`<br/>toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false |
| flag: `--set-basic-auth`<br/>toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false |
| flag: `--skip-auth-strip-headers`<br/>toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true |
| flag: `--pass-access-token`<br/>toml: `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 |
| flag: `--pass-authorization-header`<br/>toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false |
| flag: `--pass-basic-auth`<br/>toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true |
| flag: `--prefer-email-to-user`<br/>toml: `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 |
| flag: `--pass-user-headers`<br/>toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true |
### Logging Options
| Flag / Config Field | Type | Description | Default |
| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- |
| flag: `--auth-logging-format`<br/>toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) |
| flag: `--auth-logging`<br/>toml: `auth_logging` | bool | Log authentication attempts | true |
| flag: `--errors-to-info-log`<br/>toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false |
| flag: `--exclude-logging-path`<br/>toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) |
| flag: `--logging-compress`<br/>toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false |
| flag: `--logging-filename`<br/>toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) |
| flag: `--logging-local-time`<br/>toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) |
| flag: `--logging-max-age`<br/>toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 |
| flag: `--logging-max-backups`<br/>toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 |
| flag: `--logging-max-size`<br/>toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 |
| flag: `--request-id-header`<br/>toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id |
| flag: `--request-logging-format`<br/>toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) |
| flag: `--request-logging`<br/>toml: `request_logging` | bool | Log requests | true |
| flag: `--silence-ping-logging`<br/>toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false |
| flag: `--standard-logging-format`<br/>toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) |
| flag: `--standard-logging`<br/>toml: `standard_logging` | bool | Log standard runtime information | true |
### Page Template Options
| Flag / Config Field | Type | Description | Default |
| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- |
| flag: `--banner`<br/>toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | |
| flag: `--custom-sign-in-logo`<br/>toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. |
| flag: `--custom-templates-dir`<br/>toml: `custom_templates_dir` | string | path to custom html templates | |
| flag: `--display-htpasswd-form`<br/>toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true |
| flag: `--footer`<br/>toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | |
| flag: `--show-debug-on-error`<br/>toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false |
### Probe Options
| Flag / Config Field | Type | Description | Default |
| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- |
| flag: `--ping-path`<br/>toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` |
| flag: `--ping-user-agent`<br/>toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) |
| flag: `--ready-path`<br/>toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` |
| flag: `--gcp-healthchecks`<br/>toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false |
### Proxy Options
| Flag / Config Field | Type | Description | Default |
| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| flag: `--allow-query-semicolons`<br/>toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` |
| flag: `--api-route`<br/>toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | |
| flag: `--authenticated-emails-file`<br/>toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | |
| flag: `--bearer-token-login-fallback`<br/>toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true |
| flag: `--email-domain`<br/>toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | |
| flag: `--encode-state`<br/>toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false |
| flag: `--extra-jwt-issuers`<br/>toml: `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`) | |
| flag: `--force-https`<br/>toml: `force_https` | bool | enforce https redirect | `false` |
| flag: `--force-json-errors`<br/>toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` |
| flag: `--htpasswd-file`<br/>toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | |
| flag: `--htpasswd-user-group`<br/>toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | |
| flag: `--proxy-prefix`<br/>toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`<oauth2>/sign_in`) | `"/oauth2"` |
| flag: `--real-client-ip-header`<br/>toml: `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, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP |
| flag: `--redirect-url`<br/>toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | |
| flag: `--relative-redirect-url`<br/>toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false |
| flag: `--reverse-proxy`<br/>toml: `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 |
| flag: `--signature-key`<br/>toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | |
| flag: `--skip-auth-preflight`<br/>toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false |
| flag: `--skip-auth-regex`<br/>toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | |
| flag: `--skip-auth-route`<br/>toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | |
| flag: `--skip-jwt-bearer-tokens`<br/>toml: `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 |
| flag: `--skip-provider-button`<br/>toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false |
| flag: `--ssl-insecure-skip-verify`<br/>toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false |
| flag: `--trusted-ip`<br/>toml: `trusted_ips` | 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. | |
| flag: `--whitelist-domain`<br/>toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`)&nbsp;[^2] | |
[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or 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:*`.
### Server Options
| Flag / Config Field | Type | Description | Default |
| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| flag: `--http-address`<br/>toml: `http_address` | string | `[http://]<addr>:<port>` or `unix://<path>` or `fd:<int>` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` |
| flag: `--https-address`<br/>toml: `https_address` | string | `[https://]<addr>:<port>` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` |
| flag: `--metrics-address`<br/>toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` |
| flag: `--metrics-secure-address`<br/>toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` |
| flag: `--metrics-tls-cert-file`<br/>toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` |
| flag: `--metrics-tls-key-file`<br/>toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` |
| flag: `--tls-cert-file`<br/>toml: `tls_cert_file` | string | path to certificate file | |
| flag: `--tls-key-file`<br/>toml: `tls_key_file` | string | path to private key file | |
| flag: `--tls-cipher-suite`<br/>toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | |
| flag: `--tls-min-version`<br/>toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` |
### Session Options
| Flag / Config Field | Type | Description | Default |
| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| flag: `--session-cookie-minimal`<br/>toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false |
| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
| flag: `--redis-cluster-connection-urls`<br/>toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | |
| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
| flag: `--redis-sentinel-master-name`<br/>toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | |
| flag: `--redis-sentinel-connection-urls`<br/>toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | |
| flag: `--redis-use-cluster`<br/>toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false |
| flag: `--redis-use-sentinel`<br/>toml: `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 |
| flag: `--redis-connection-idle-timeout`<br/>toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 |
### Upstream Options
| Flag / Config Field | Type | Description | Default |
| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
| flag: `--flush-interval`<br/>toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` |
| flag: `--pass-host-header`<br/>toml: `pass_host_header` | bool | pass the request Host Header to upstream | true |
| flag: `--proxy-websockets`<br/>toml: `proxy_websockets` | bool | enables WebSocket proxying | true |
| flag: `--ssl-upstream-insecure-skip-verify`<br/>toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false |
| flag: `--disable-keep-alives`<br/>toml: `disable_keep_alives` | bool | disable HTTP keep-alive connections to the upstream server | false |
| flag: `--upstream-timeout`<br/>toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s |
| flag: `--upstream`<br/>toml: `upstreams` | 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 | |
## Upstreams Configuration
`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system.
To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request.
* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`.
* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`.
If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones.
**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`.
**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 a configuration file
or the command line.
For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`.
If a flag has the type `string | list` like the `--email-domain` flag it is
available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS`
Values for type `string | list` usually have a plural environment variable name
and need to be seperated by `,` e.g.
`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"`
Please check the type for each [config option](#config-options) first.
## 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`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume.
## 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> [2015/03/19 17:20:19] [<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 | 2015/03/19 17:20:19 | 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> [2015/03/19 17:20:19] <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 | 2015/03/19 17:20:19 | 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:
```
[2015/03/19 17:20:19] [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 | 2015/03/19 17:20:19 | 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. |

View File

@ -0,0 +1,19 @@
---
id: adfs
title: ADFS
---
1. Open the ADFS administration console on your Windows Server and add a new Application Group
2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next
3. Follow the wizard to get the client-id, client-secret and configure the application credentials
4. Configure the proxy with
```
--provider=adfs
--client-id=<application ID from step 3>
--client-secret=<value from step 3>
```
Note: When using the ADFS 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.

View File

@ -0,0 +1,25 @@
---
id: bitbucket
title: BitBucket
---
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 have access to one selected repository use `--bitbucket-repository=<Repository name>`.

View File

@ -0,0 +1,37 @@
---
id: cidaas
title: Cidaas
---
[Cidaas](https://www.cidaas.com/) is an Identity as a Service (IDaaS) solution that provides authentication and authorization services.
It supports various protocols including OpenID Connect, OAuth 2.0, and SAML.
However, Cidaas provides groups and their roles as hierarchical claims, which are not supported by oauth2-proxy yet.
The Cidaas provider transforms the hierarchical claims into a flat list of groups, which can be used by oauth2-proxy.
Example of groups and roles in Cidaas:
```json
{
"groups": [
{
"groupId": "group1",
"roles": ["role1", "role2"]
},
{
"groupId": "group2",
"roles": ["role3"]
}
]
}
```
This will be transformed into a flat list of groups:
```json
{
"groups": ["group1:role1", "group2:role2", "group2:role3"]
}
```
Apart from that the Cidaas provider inherits all the features of the [OpenID Connect provider](openid_connect.md).

View File

@ -0,0 +1,44 @@
---
id: cisco_duo
title: Cisco Duo
---
Cisco Duo SSO can be configured with OAuth2 Proxy using the OIDC provider.
1. Create a new **Generic OIDC Relying Party - Single Sign-On** application in the Duo Admin Portal
2. Configure OAuth2 Proxy with the following options:
```
provider = "oidc"
provider_display_name = "Duo SSO"
scope = "openid email profile"
pass_access_token = true
code_challenge_method = "S256"
```
3. Configure Provider endpoints. Copy the following values from the corresponding fields in the Duo Admin Portal:
```
# Copy from "Client ID" field
client_id = "XXXXXXXX"
# Copy from "Client Secret" field
client_secret = "XXXXXXXX"
# Copy from "Issuer" field
oidc_issuer_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx"
# Copy from "JWKS URL" field
oidc_jwks_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/jwks"
# Copy from "Token Introspection URL" field
validate_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token_introspection"
# Copy from "UserInfo" field
profile_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/userinfo"
# Copy from "Token URL" field
redeem_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token"
```
4. Complete Configuration by filling in any remaining required fields and save your configuration.

View File

@ -0,0 +1,21 @@
---
id: digitalocean
title: DigitalOcean
---
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.

View File

@ -0,0 +1,7 @@
---
id: facebook
title: Facebook
---
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`

View File

@ -0,0 +1,24 @@
---
id: gitea
title: Gitea / Forgejo
---
:::note
This is not actually a fully serparate provider. For more details and options please refer to the [GitHub Provider Options](github.md)
:::
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/user/emails"
```

View File

@ -0,0 +1,81 @@
---
id: github
title: GitHub
---
## Config Options
| Flag | Toml Field | Type | Description | Default |
| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- |
| `--github-org` | `github_org` | string | restrict logins to members of this organisation | |
| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | |
| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | |
| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | |
| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | |
## Usage
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=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1`
NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified
org and team or collaborators.
To restrict access to your organization:
```shell
# restrict logins to members of this organisation
--github-org="your-org"
```
To restrict access to specific teams within an organization:
```shell
--github-org="your-org"
# restrict logins to members of any of these teams (slug), comma separated
--github-team="team1,team2,team3"
```
To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so:
```shell
# keep empty
--github-org=""
# restrict logins to members to any of the following teams (format <org>:<slug>, like octo:team1), comma separated
--github-team="org1:team1,org2:team1,org3:team42,octo:cat"
```
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:
```shell
# restrict logins to collaborators of this repository formatted as orgname/repo
--github-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:
```shell
# the token to use when verifying repository collaborators
--github-token=""
```
To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators:
```shell
# allow logins by username, comma separated
--github-user=""
```
If you are using GitHub enterprise, make sure you set the following to the appropriate url:
```shell
--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"
```

View File

@ -0,0 +1,49 @@
---
id: gitlab
title: GitLab
---
## Config Options
| Flag | Toml Field | Type | Description | Default |
| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
| `--gitlab-projects` | `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 | |
## Usage
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/integration/oauth_provider/). 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:
```shell
--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:
```shell
--oidc-issuer-url="<your gitlab url>"
```
If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain
(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth.

View File

@ -0,0 +1,84 @@
---
id: google
title: Google (default)
---
## Config Options
| Flag | Toml Field | Type | Description | Default |
|-------------------------------------------------|----------------------------------------------| ------ |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------|
| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | |
| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | |
| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | |
| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | |
| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC |
| `--google-use-organization-id` | `google_use_organization_id` | bool | use organization id as preferred username | false |
| `--google-admin-api-user-scope` | `google_admin_api_user_scope` | string | the OAuth scope to use when querying the Google Admin SDK for organization id, can be 'readonly', 'user' or 'cloud'<br/> | `readonly` |
## Usage
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 **"APIs & Services"**
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/oauth2/service-account) and configure it
to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or,
alternatively download the JSON.
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 [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account)
and give the client id from step 2 the following oauth scopes:
```
https://www.googleapis.com/auth/admin.directory.group.member.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.
(Only if using a JSON file (see step 1))
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 ).
##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended)
oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials).
When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC
can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity)
to set up Workload Identity.
When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option.
##### Using Organization ID as Preferred Username (optional)
By default, the google provider uses the google id as username. If you would like to use an organization id instead, you can set the `google-use-organization-id` flag to true.
This requires that the service account used to query the Google Admin SDK has one of the following scopes granted in step 5 above:
- `https://www.googleapis.com/auth/admin.directory.user.readonly`,
- `https://www.googleapis.com/auth/admin.directory.user`
- `https://www.googleapis.com/auth/cloud-platform`

View File

@ -0,0 +1,46 @@
---
id: index
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 :
- [ADFS](adfs.md)
- [Bitbucket](bitbucket.md)
- [Cidaas](cidaas.md)
- [CiscoDuo](cisco_duo.md)
- [DigitalOcean](digitalocean.md)
- [Facebook](facebook.md)
- [Gitea](gitea.md)
- [GitHub](github.md)
- [GitLab](gitlab.md)
- [Google](google.md) _default_
- [Keycloak](keycloak.md) (Deprecated)
- [Keycloak OIDC](keycloak_oidc.md)
- [LinkedIn](linkedin.md)
- [login.gov](login_gov.md)
- [Microsoft Azure](ms_azure_ad.md) (Deprecated)
- [Microsoft Entra ID](ms_entra_id.md)
- [Nextcloud](nextcloud.md)
- [OpenID Connect](openid_connect.md)
- [SourceHut](sourcehut.md)
The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926).
Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the
OpenID Connect provider.
## Email Authentication
To authorize a specific 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,36 @@
---
id: keycloak
title: Keycloak (Deprecated)
---
:::note
This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible.
:::
1. Create new client in your Keycloak realm with **Access Type** 'confidential' 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.

View File

@ -0,0 +1,151 @@
---
id: keycloak_oidc
title: Keycloak OIDC
---
## Config Options
| Flag | Toml Field | Type | Description | Default |
| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- |
| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | |
## Usage
```
--provider=keycloak-oidc
--client-id=<your client's id>
--client-secret=<your client's secret>
--redirect-url=https://internal.yourcompany.com/oauth2/callback
--oidc-issuer-url=https://<keycloak host>/realms/<your realm> // For Keycloak versions <17: --oidc-issuer-url=https://<keycloak host>/auth/realms/<your realm>
--email-domain=<yourcompany.com> // Validate email domain for users, see option documentation
--allowed-role=<realm role name> // Optional, required realm role
--allowed-role=<client id>:<client role name> // Optional, required client role
--allowed-group=</group name> // Optional, requires group client scope
--code-challenge-method=S256 // PKCE
```
:::note
Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The
legacy admin console has been announced for removal with the release of version 21.0.0.
:::
**Keycloak legacy admin console**
1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect'
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'.
4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set
to your client name.
**Keycloak new admin console (default as of v19.0.0)**
The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best
practices, it is recommended to consult the Keycloak documentation.
The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token.
The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of
either `--client-id` or `--oidc-extra-audience`.
_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or
through "dedicated" client mappers._
**Creating the client**
1. Create a new OIDC client in your Keycloak realm by navigating to:
**Clients** -> **Create client**
* **Client Type** 'OpenID Connect'
* **Client ID** `<your client's id>`, please complete the remaining fields as appropriate and click **Next**.
* **Client authentication** 'On'
* **Authentication flow**
* **Standard flow** 'selected'
* **Direct access grants** 'deselect'
* _Save the configuration._
* **Settings / Access settings**:
* **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback`
* _Save the configuration._
* Under the **Credentials** tab you will now be able to locate `<your client's secret>`.
2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\<your client's id\>** -> **Client scopes**.
* Access the dedicated mappers pane by clicking **\<your client's id\>-dedicated**, located under *Assigned client scope*.
_(It should have a description of "Dedicated scope and mappers for this client")_
* Click **Configure a new mapper** and select **Audience**
* **Name** 'aud-mapper-\<your client's id\>'
* **Included Client Audience** select `<your client's id>` from the dropdown.
* _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services.
If you require additional audience entries, you can use the **Included Custom Audience** field in addition
to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and
only specify its intended recipients._
* **Add to ID token** 'On'
* **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916)
* _Save the configuration._
* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** ->
**By configuration** -> *Select mapper*
You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set
an email address matching `<yourcompany.com>` and select _Email verified_.
**Authorization**
_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into
account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options
`--allowed-role` or `--allowed-group`_
**Roles**
_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the
pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when
using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._
_Creating a realm role_
* Navigate to **Realm roles** -> **Create role**
* **Role name**, *`<realm role name>`* -> **save**
_Creating a client role_
* Navigate to **Clients** -> `<your client's id>` -> **Roles** -> **Create role**
* **Role name**, *`<client role name>`* -> **save**
_Assign a role to a user_
**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**.
Keycloak "realm roles" can be authorized using the `--allowed-role=<realm role name>` option, while "client roles" can be
evaluated using `--allowed-role=<your client's id>:<client role name>`.
You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to:
**Clients** -> `<your client's id>` -> **Client scopes** -> _\<your client's id\>-dedicated_ -> **Scope**
Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned
to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you
want to reduce the size and impact of the JWT token.
**Groups**
You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`.
We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak
documentation.
To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows:
* Create a new Client Scope with the name **groups** in Keycloak.
* Include a mapper of type **Group Membership**.
* Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy.
* If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the
`--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group".
After creating the _Client Scope_ named _groups_ you will need to attach it to your client.
**Clients** -> `<your client's id>` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional
and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them.
Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member.
The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership
Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information.
**Tip**
To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following
these steps: **Clients** -> `<your client's id>` -> **Client scopes** -> **Evaluate**.
Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access
or id token to examine its contents.

View File

@ -0,0 +1,13 @@
---
id: linkedin
title: LinkedIn
---
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**

View File

@ -0,0 +1,79 @@
---
id: login_gov
title: Login.gov
---
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
```

View File

@ -0,0 +1,59 @@
---
id: azure
title: Azure (Deprecated)
---
:::note
This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible.
:::
## Config Options
| Flag | Toml Field | Type | Description | Default |
| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- |
| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` |
| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | |
## Usage
1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select
**App registrations** and then click on **New registration**.
2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new
**Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g.
https://internal.yourcompanycom/oauth2/callback). Click **Register**.
3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on
**Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select
**Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this).
<br/>**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually
be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login,
most likely this is what you're missing!
4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2`
in the App registration manifest file.
5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**.
6. Configure the proxy with:
- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize)
```
--provider=azure
--client-id=<application ID from step 3>
--client-secret=<value from step 5>
--azure-tenant={tenant-id}
--oidc-issuer-url=https://sts.windows.net/{tenant-id}/
```
- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize)
```
--provider=azure
--client-id=<application ID from step 3>
--client-secret=<value from step 5>
--azure-tenant={tenant-id}
--oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0
```
***Notes***:
- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction
with `--resource` flag, be sure to append `/.default` at the end of the resource name. See
https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details.
- 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.

View File

@ -0,0 +1,197 @@
---
id: ms_entra_id
title: Microsoft Entra ID
---
Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps.
## Config Options
The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are:
| Flag | Toml Field | Type | Description | Default |
| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | |
| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false |
## Configure App registration
To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only.
<details>
<summary>See Azure Portal example</summary>
<div class="videoBlock">
<iframe src="https://www.youtube.com/embed/IUNfxhOzr4E"></iframe>
</div>
</details>
<details>
<summary>See Terraform example</summary>
```
resource "azuread_application" "auth" {
display_name = "oauth2-proxy"
sign_in_audience = "AzureADMyOrg" # Others are also supported
web {
redirect_uris = [
"https://podinfo.lakis.tech/oauth2/callback",
]
}
// We don't specify any required API permissions - we allow user consent only
}
resource "azuread_service_principal" "sp" {
client_id = azuread_application.auth.client_id
app_role_assignment_required = false
}
resource "azuread_service_principal_password" "pass" {
service_principal_id = azuread_service_principal.sp.id
}
```
</details>
### Configure groups
If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration.
<details>
<summary>See Azure Portal example</summary>
<div class="videoBlock">
<div class="videoBlock">
<iframe src="https://www.youtube.com/embed/QZmP5MKEJis"></iframe>
</div>
</div>
</details>
<details>
<summary>See Terraform example</summary>
```
resource "azuread_application" "auth" {
display_name = "oauth2-proxy"
sign_in_audience = "AzureADMyOrg"
group_membership_claims = [
"SecurityGroup"
]
web {
redirect_uris = [
"https://podinfo.lakis.tech/oauth2/callback",
]
}
}
resource "azuread_service_principal" "sp" {
client_id = azuread_application.auth.client_id
app_role_assignment_required = false
}
resource "azuread_service_principal_password" "pass" {
service_principal_id = azuread_service_principal.sp.id
}
```
</details>
### Scopes and claims
For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)).
To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups.
When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages).
Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource.
For personal microsoft accounts, required scope is `openid profile email`.
See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview).
### Multi-tenant apps
To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification:
```toml
oidc_issuer_url=https://login.microsoftonline.com/common/v2.0
insecure_oidc_skip_issuer_verification=true
```
`insecure_oidc_skip_issuer_verification` setting is required to disable following checks:
* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation).
* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation).
To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template.
### Workload Identity
Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met:
* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`.
* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity).
* Appropriate federated credential is added to application registration.
<details>
<summary>See federated credential terraform example</summary>
```
resource "azuread_application_federated_identity_credential" "fedcred" {
application_id = azuread_application.application.id # ID of your application
display_name = "federation-cred"
description = "Workload identity for oauth2-proxy"
audiences = ["api://AzureADTokenExchange"] # Fixed value
issuer = "https://cluster-oidc-issuer-url..."
subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name
}
```
</details>
* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: <app-registration-client-id>`
* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"`
* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`.
`client_secret` setting can be omitted when using federated token authentication.
See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/).
### Example configurations
Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider:
```toml
provider="entra-id"
oidc_issuer_url="https://login.microsoftonline.com/<tenant-id>/v2.0"
client_id="<client-id>"
client_secret="<client-secret>"
scope="openid"
```
Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider:
```toml
provider="entra-id"
oidc_issuer_url="https://login.microsoftonline.com/<tenant-id>/v2.0"
client_id="<client-id>"
client_secret="<client-secret>"
scope="openid"
allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"]
```
Single-tenant app with more than 200 groups:
```toml
provider="entra-id"
oidc_issuer_url="https://login.microsoftonline.com/<tenant-id>/v2.0"
client_id="<client-id>"
client_secret="<client-secret>"
scope="openid User.Read"
allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"]
```
Single-tenant app with more than 200 groups and workload identity enabled:
```toml
provider="entra-id"
oidc_issuer_url="https://login.microsoftonline.com/<tenant-id>/v2.0"
client_id="<client-id>"
scope="openid User.Read"
allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"]
entra_id_federated_token_auth=true
```
Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered:
```toml
provider="entra-id"
oidc_issuer_url="https://login.microsoftonline.com/common/v2.0"
client_id="<client-id>"
client_secret="<client-secret>"
insecure_oidc_skip_issuer_verification=true
scope="openid profile email User.Read"
entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad","<my-tenant-id>"] # Allow only <my-tenant-id> and Personal MS Accounts tenant
email_domains="*"
```

View File

@ -0,0 +1,28 @@
---
id: nextcloud
title: NextCloud
---
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 set up 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`.

View File

@ -0,0 +1,146 @@
---
id: openid_connect
title: OpenID Connect
---
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://dexidp.io/docs/getting-started/) 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:
```shell
--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 website under the `/static` endpoint, add:
```shell
--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 `cookie_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`
```shell
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`

View File

@ -0,0 +1,25 @@
---
id: sourcehut
title: SourceHut
---
1. Create a new OAuth client: https://meta.sr.ht/oauth2
2. Under `Redirection URI` enter the correct URL, i.e.
`https://internal.yourcompany.com/oauth2/callback`
To use the provider, start with `--provider=sourcehut`.
If you are hosting your own SourceHut instance, make sure you set the following
to the appropriate URLs:
```shell
--login-url="https://<meta.your.instance>/oauth2/authorize"
--redeem-url="https://<meta.your.instance>/oauth2/access-token"
--profile-url="https://<meta.your.instance>/query"
--validate-url="https://<meta.your.instance>/profile"
```
The default configuration allows everyone with an account to authenticate.
Restricting access is currently only supported by
[email](index.md#email-authentication).

View File

@ -0,0 +1,99 @@
---
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 encrypted sessions in redis. Instead of sending all the information
back 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. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT,
which can get quite big.
Two settings are used to configure the OAuth2 Proxy cookie lifetime:
--cookie-refresh duration refresh the cookie after this duration; 0 to disable
--cookie-expire duration expire timeframe for cookie 168h0m0s
The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server.
If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start
the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already
expired.
The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the
Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2 Proxy will
refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification
Access-Tokens are not required to follow a specific format. Therefore OAuth2 Proxy cannot check for any expiry date without an
introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely
encounter expiry issues.
Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s".
It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate
it. This is especially relevant if the backend uses the JWT to make requests to other backends.
For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan.
Recommended settings:
* cookie_refresh := Access-Token lifespan - 1m
* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle)
#### 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.
Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout`
must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes
`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14`

View File

@ -0,0 +1,43 @@
---
id: systemd_socket
title: Systemd Socket Activation
---
Pass an existing listener created by systemd.socket to oauth2-proxy.
To do this create a socket:
oauth2-proxy.socket
```
[Socket]
ListenStream=%t/oauth2.sock
SocketGroup=www-data
SocketMode=0660
```
Now it's possible to call this socket from e.g. nginx:
```
server {
location /oauth2/ {
proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock;
}
```
The oauth2-proxy should have `--http-address=fd:3` as a parameter.
Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor,
systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes
the listener it created onto the process, starting with file descriptor 3.
```
./oauth2-proxy \
--http-address="fd:3" \
--email-domain="yourcompany.com" \
--upstream=http://127.0.0.1:8080/ \
--cookie-secret=... \
--cookie-secure=true \
--provider=... \
--client-id=... \
--client-secret=...
```
Currently TLS is not supported (but it's doable).

View File

@ -0,0 +1,85 @@
---
id: tls
title: TLS Configuration
---
There are two recommended configurations:
- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy)
- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx)
### Terminate TLS at OAuth2 Proxy
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. With this configuration approach the customization of the TLS settings is limited.
The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`.
The defaults set `TLS1.2` as the minimal version.
Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version.
TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`.
If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used.
A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants).
### Terminate TLS at Reverse Proxy, e.g. Nginx
1. 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_connect_timeout 1;
proxy_send_timeout 30;
proxy_read_timeout 30;
}
}
```
2. 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,59 @@
---
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.
- / - the proxy endpoint provides authentication and returns the appropriate 40x error if not authenticated or authorized then passes the request upstream.
- /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
- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected
- /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/integrations/nginx)
- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages
### 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 afterward 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. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081").
### Auth
This endpoint returns 202 Accepted response or a 401 Unauthorized response.
It can be configured using the following query parameters:
- `allowed_groups`: comma separated list of allowed groups
- `allowed_email_domains`: comma separated list of allowed email domains
- `allowed_emails`: comma separated list of allowed emails
### Proxy (/)
This endpoint returns the upstream response if authenticated.
If unauthenticated it returns a 401 Unauthorized. If the authenticatd user
is not in one of the allowed groups, or emails then it returns a 403 forbidden
It can be configured using the following query parameters:
- `allowed_groups`: comma separated list of allowed groups
- `allowed_email_domains`: comma separated list of allowed email domains
- `allowed_emails`: comma separated list of allowed emails

View File

@ -0,0 +1,32 @@
---
id: installation
title: Installation
---
1. Choose how to deploy:
a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.0`)
b. Using Go to install the latest release
```bash
$ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest
```
This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install`
c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available)
d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available)
e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm)
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
oauth2-proxy-x.y.z.linux-amd64: OK
```
2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md)
3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md)
4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx)
5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd)

View File

@ -0,0 +1,32 @@
---
id: welcome
title: Welcome
hide_table_of_contents: true
slug: /
---
![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg)
A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others)
to validate accounts by email, domain or group.
:::note
This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018.
Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork.
A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md).
:::
![Sign In Page](/img/sign-in-page.png)
## Architecture
![OAuth2 Proxy Architecture](/img/simplified-architecture.svg)
## Cloud Native Computing Foundation
OAuth2 Proxy is a [Cloud Native Computing Foundation](https://cncf.io) Sandbox project.
![CNCF](https://www.cncf.io/wp-content/uploads/2023/04/cncf-main-site-logo.svg)
The Linux Foundation® (TLF) has registered trademarks and uses trademarks. For a list of TLF trademarks, see [Trademark Usage](https://www.linuxfoundation.org/legal/trademark-usage).

View File

@ -22,7 +22,21 @@
"collapsed": false,
"items": [
"configuration/overview",
"configuration/integration",
{
"type": "category",
"label": "Integration Guides",
"link": {
"type": "doc",
"id": "configuration/integrations/index"
},
"items": [
"configuration/integrations/nginx",
"configuration/integrations/traefik",
"configuration/integrations/caddy",
"configuration/integrations/headlamp",
"configuration/integrations/kubernetes-dashboard"
]
},
{
"type": "category",
"label": "OAuth Provider Configuration",

View File

@ -0,0 +1,100 @@
{
"docs": [
{
"type": "doc",
"id": "welcome"
},
{
"type": "doc",
"id": "installation"
},
{
"type": "doc",
"id": "behaviour"
},
{
"type": "category",
"label": "Configuration",
"link": {
"type": "doc",
"id": "configuration/overview"
},
"collapsed": false,
"items": [
"configuration/overview",
{
"type": "category",
"label": "Integration Guides",
"link": {
"type": "doc",
"id": "configuration/integrations/index"
},
"items": [
"configuration/integrations/nginx",
"configuration/integrations/traefik",
"configuration/integrations/caddy",
"configuration/integrations/headlamp",
"configuration/integrations/kubernetes-dashboard"
]
},
{
"type": "category",
"label": "OAuth Provider Configuration",
"link": {
"type": "doc",
"id": "configuration/providers/index"
},
"items": [
"configuration/providers/adfs",
"configuration/providers/azure",
"configuration/providers/bitbucket",
"configuration/providers/cidaas",
"configuration/providers/cisco_duo",
"configuration/providers/digitalocean",
"configuration/providers/facebook",
"configuration/providers/gitea",
"configuration/providers/github",
"configuration/providers/gitlab",
"configuration/providers/google",
"configuration/providers/keycloak",
"configuration/providers/keycloak_oidc",
"configuration/providers/linkedin",
"configuration/providers/login_gov",
"configuration/providers/ms_entra_id",
"configuration/providers/nextcloud",
"configuration/providers/openid_connect",
"configuration/providers/sourcehut"
]
},
"configuration/session_storage",
"configuration/tls",
"configuration/alpha-config"
]
},
{
"type": "category",
"label": "Features",
"link": {
"type": "doc",
"id": "features/endpoints"
},
"collapsed": false,
"items": [
"features/endpoints"
]
},
{
"type": "category",
"label": "Community",
"link": {
"type": "doc",
"id": "community/security"
},
"collapsed": false,
"items": [
"community/contribution",
"community/security"
]
}
]
}

View File

@ -1,4 +1,5 @@
[
"7.14.x",
"7.13.x",
"7.12.x",
"7.11.x",

View File

@ -157,6 +157,8 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr
// Ensure we always pass the original request path
setProxyDirector(proxy)
// TODO (@tuunit) - this should be inverted or get a better name in the future to set the upstream host header
// only if PassHostHeader is explicitly set to true. Currently this would be a breaking change.
if !ptr.Deref(upstream.PassHostHeader, options.DefaultUpstreamPassHostHeader) {
setProxyUpstreamHostHeader(proxy, target)
}
@ -215,6 +217,8 @@ func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool, passHostHeader *b
// Apply the customized transport to our proxy before returning it
wsProxy.Transport = transport
// TODO (@tuunit) - this should be inverted or get a better name in the future to set the upstream host header
// only if PassHostHeader is explicitly set to true. Currently this would be a breaking change.
// Set upstream host header if PassHostHeader is false (same as regular HTTP proxy)
if !ptr.Deref(passHostHeader, options.DefaultUpstreamPassHostHeader) {
setProxyUpstreamHostHeader(wsProxy, u)