Internet-Draft | OAuth 2.0 for Browser-Based Apps | September 2022 |
Parecki & Waite | Expires 10 March 2023 | [Page] |
This specification details the security considerations and best practices that must be taken into account when developing browser-based applications that use OAuth 2.0.¶
This note is to be removed before publishing as an RFC.¶
Discussion of this document takes place on the Web Authorization Protocol Working Group mailing list (oauth@ietf.org), which is archived at https://mailarchive.ietf.org/arch/browse/oauth/.¶
Source for this draft and an issue tracker can be found at https://github.com/oauth-wg/oauth-browser-based-apps.¶
This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79.¶
Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is at https://datatracker.ietf.org/drafts/current/.¶
Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."¶
This Internet-Draft will expire on 10 March 2023.¶
Copyright (c) 2022 IETF Trust and the persons identified as the document authors. All rights reserved.¶
This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (https://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Revised BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Revised BSD License.¶
This specification describes the current best practices for implementing OAuth 2.0 authorization flows in applications executing in a browser.¶
For native application developers using OAuth 2.0 and OpenID Connect, an IETF BCP (best current practice) was published that guides integration of these technologies. This document is formally known as [RFC8252] or BCP 212, but nicknamed "AppAuth" after the OpenID Foundation-sponsored set of libraries that assist developers in adopting these practices. [RFC8252] makes specific recommendations for how to securely implement OAuth in native applications, including incorporating additional OAuth extensions where needed.¶
OAuth 2.0 for Browser-Based Apps addresses the similarities between implementing OAuth for native apps and browser-based apps, and includes additional considerations when running in a browser. This is primarily focused on OAuth, except where OpenID Connect provides additional considerations.¶
Many of these recommendations are derived from the OAuth 2.0 Security Best Current Practice [oauth-security-topics] and browser-based apps are expected to follow those recommendations as well. This draft expands on and further restricts various recommendations in [oauth-security-topics].¶
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119].¶
In addition to the terms defined in referenced specifications, this document uses the following terms:¶
At the time that OAuth 2.0 [RFC6749] and [RFC6750] were created, browser-based JavaScript applications needed a solution that strictly complied with the same-origin policy. Common deployments of OAuth 2.0 involved an application running on a different domain than the authorization server, so it was historically not possible to use the Authorization Code flow which would require a cross-origin POST request. This was one of the motivations for the definition of the Implicit flow, which returns the access token in the front channel via the fragment part of the URL, bypassing the need for a cross-origin POST request.¶
However, there are several drawbacks to the Implicit flow, generally involving vulnerabilities associated with the exposure of the access token in the URL. See Section 9.8 for an analysis of these attacks and the drawbacks of using the Implicit flow in browsers. Additional attacks and security considerations can be found in [oauth-security-topics].¶
In recent years, widespread adoption of Cross-Origin Resource Sharing (CORS), which enables exceptions to the same-origin policy, allows browser-based apps to use the OAuth 2.0 Authorization Code flow and make a POST request to exchange the authorization code for an access token at the token endpoint. In this flow, the access token is never exposed in the less-secure front channel. Furthermore, adding PKCE to the flow ensures that even if an authorization code is intercepted, it is unusable by an attacker.¶
For this reason, and from other lessons learned, the current best practice for browser-based applications is to use the OAuth 2.0 Authorization Code flow with PKCE.¶
Browser-based applications:¶
MUST Protect themselves against CSRF attacks by either:¶
OAuth 2.0 authorization servers supporting browser-based applications:¶
While OAuth was initially created to allow third-party applications to access an API on behalf of a user, it has proven to be useful in a first-party scenario as well. First-party apps are applications where the same organization provides both the API and the application.¶
Examples of first-party applications are a web email client provided by the operator of the email account, or a mobile banking application created by bank itself. (Note that there is no requirement that the application actually be developed by the same company; a mobile banking application developed by a contractor that is branded as the bank's application is still considered a first-party application.) The first-party app consideration is about the user's relationship to the application and the service.¶
To conform to this best practice, first-party applications using OAuth or OpenID Connect MUST use a redirect-based flow (such as the OAuth Authorization Code flow) as described later in this document.¶
The resource owner password credentials grant MUST NOT be used, as described in [oauth-security-topics] Section 2.4. Instead, by using the Authorization Code flow and redirecting the user to the authorization server, this provides the authorization server the opportunity to prompt the user for multi-factor authentication options, take advantage of single sign-on sessions, or use third-party identity providers. In contrast, the resource owner password credentials grant does not provide any built-in mechanism for these, and would instead be extended with custom code.¶
Here are the main architectural patterns available when building browser-based applications.¶
a JavaScript application accessing resource servers¶
These architectures have different use cases and considerations.¶
For simple system architectures, such as when the JavaScript application is served from a domain that can share cookies with the domain of the API (resource server) and the authorization server, OAuth adds additional attack vectors that could be avoided with a different solution.¶
In particular, using any redirect-based mechanism of obtaining an access token enables the redirect-based attacks described in [oauth-security-topics] Section 4, but if the application, authorization server and resource server share a domain, then it is unnecessary to use a redirect mechanism to communicate between them.¶
An additional concern with handling access tokens in a browser is that in case of successful XSS attack, tokens could be read and further used or transmitted by the injected code if no secure storage mechanism is in place.¶
As such, it could be considered to use an HTTP-only cookie between the JavaScript application
and API so that the JavaScript code can't access the cookie value itself. The Secure
cookie attribute should be used to ensure the cookie is not included in unencrypted HTTP requests. Additionally, the SameSite
cookie attribute can be used to counter some CSRF attacks,
but should not be considered the extent of the CSRF protection, as described in [draft-ietf-httpbis-rfc6265bis]¶
OAuth was originally created for third-party or federated access to APIs, so it may not be the best solution in a common-domain deployment. That said, there are still some advantages in using OAuth even in a common-domain architecture:¶
Using OAuth for browser-based apps in a first-party same-domain scenario provides these advantages, and can be accomplished by any of the architectural patterns described below.¶
+-------------+ +--------------+ +---------------+ | | | | | | |Authorization| | Token | | Resource | | Endpoint | | Endpoint | | Server | | | | | | | +-------------+ +--------------+ +---------------+ ^ ^ ^ | (D)| (G)| | v v | | +--------------------------------------+ | | | | | Backend for Frontend Proxy (BFF) | (B)| | | | +--------------------------------------+ | | ^ ^ + ^ + | (A)| (C)| (E)| (F)| |(H) v v + v + v +-------------------------------------------------+ | | | Browser | | | +-------------------------------------------------+¶
In this architecture, commonly referred to as "backend for frontend" or "BFF", the JavaScript code is loaded from a dynamic Application Server (A) that has the ability to execute code and handle the full authentication flow itself. This enables the ability to keep the call to actually get an access token outside the JavaScript application.¶
Note that this BFF is not the Resource Server, it is the OAuth client and would be accessing data at a separate resource server.¶
In this case, the BFF initiates the OAuth flow itself, by redirecting the browser to the authorization endpoint (B). When the user is redirected back, the browser delivers the authorization code to the application server (C), where it can then exchange it for an access token at the token endpoint (D) using its client secret and PKCE code verifier. The application server then keeps the access token and refresh token stored internally, and creates a separate session with the browser-based app via a traditional browser cookie (E).¶
When the JavaScript application in the browser wants to make a request to the Resource Server, it instead makes the request to the Application Server (F), and the Application Server will make the request with the access token to the Resource Server (G), and forward the response (H) back to the browser.¶
(Common examples of this architecture are an Angular front-end with a .NET backend, or a React front-end with a Spring Boot backend.)¶
The Application Server SHOULD be considered a confidential client, and issued its own client secret. The Application Server SHOULD use the OAuth 2.0 Authorization Code grant with PKCE to initiate a request for an access token. Detailed recommendations for confidential clients can be found in [oauth-security-topics] Section 2.1.1.¶
In this scenario, the connection between the browser and Application Server SHOULD be a session cookie provided by the Application Server.¶
Security of the connection between code running in the browser and this Application Server is
assumed to utilize browser-level protection mechanisms. Details are out of scope of
this document, but many recommendations can be found in the OWASP Cheat Sheet series (https://cheatsheetseries.owasp.org/),
such as setting an HTTP-only and Secure
cookie to authenticate the session between the
browser and Application Server.¶
Additionally, cookies MUST be protected from leakage by other means, such as logs.¶
This architecture protects against tokens leakage from the browser, but creates a CSRF attack vector: once the user is authenticated, the BFF proxy will automatically add tokens to calls to the resource server.¶
+---------------+ +--------------+ | | | | | Authorization | | Resource | | Server | | Server | | | | | +---------------+ +--------------+ ^ ^ ^ + | | | | |(B) |(C) |(D) |(E) | | | | | | | | + v + v +-----------------+ +-------------------------------+ | | (A) | | | Static Web Host | +-----> | Browser | | | | | +-----------------+ +-------------------------------+¶
In this architecture, the JavaScript code is first loaded from a static web host into the browser (A), and the application then runs in the browser. This application is considered a public client, since there is no way to issue it a client secret in this model.¶
The code in the browser initiates the Authorization Code flow with the PKCE extension (described in Section 7) (B) above, and obtains an access token via a POST request (C).¶
The application is then responsible for storing the access token (and optional refresh token) as securely as possible using appropriate browser APIs.¶
When the JavaScript application in the browser wants to make a request to the Resource Server, it can interact with the Resource Server directly. It includes the access token in the request (D) and receives the Resource Server's response (E).¶
In this scenario, the Authorization Server and Resource Server MUST support the necessary CORS headers to enable the JavaScript code to make these POST requests from the domain on which the script is executing. (See Section 9.6 for additional details.)¶
In case of successful XSS attack, the injected code has full access to stored tokens and can leak them to the attacker.¶
Remarks and mitigations: * As a general rule, XSS will lead to full compromise of the application and all precautions MUST be taken against it. * The application SHOULD be designed to restrict access tokens to strictly needed resources, to avoid escalating the scope of the attack. * To avoid information disclosure from ID Tokens, the application SHOULD be designed to not have any claim that isn't used by the frontend. * The application designer SHOULD consider not having refresh tokens at all to avoid the risk of giving prolonged access to the attacker.¶
In this scenario, a Service Worker is responsible for obtaining tokens from the authorization server and making requests to the resource server.¶
Service workers are run in a separate context from the DOM, have no access to the DOM, and the DOM has no access to the service worker. This makes service workers inherently safe from XSS, thus they can be used as a safe store for tokens.¶
In this architecture, a service worker intercepts calls from the frontend to the resource server. As such, it completely isolates calls to the authorization server from XSS attack surface, as all tokens are safely kept in the service worker context without any access from other JavaScript contexts. The service worker is then solely responsible for adding the token in the authorization header to calls to the resource server.¶
Resource Authorization User Application Service Worker server server | browse | | | | | ------------>| | | | | |-------------------> | /authorize | | | --------------------------------------------------------> | | | redirect w/ authorization code | | | < - - - - - - - - - - - - - - - - - - - - - - - - - - - | | | | | | | | | token request w/ auth code | /token | | | | ------------------------------------------------------> | | | <- - - - - - - - - - - - - - - - - - - - - - - - - - -| | | | | | | | resource request | | | | |-------------------> resource request with token | | | | | ---------------------------->| | | | | | | User Application Service Worker Resource Authorization server server¶
Refresh tokens provide a way for applications to obtain a new access token when the initial access token expires. With public clients, the risk of a leaked refresh token is greater than leaked access tokens, since an attacker may be able to continue using the stolen refresh token to obtain new access tokens potentially without being detectable by the authorization server.¶
Javascript-accessible storage mechanisms like Local Storage provide an attacker with several opportunities by which a refresh token can be leaked, just as with access tokens. As such, these mechanisms are considered a higher risk for handling refresh tokens.¶
Authorization servers may choose whether or not to issue refresh tokens to browser-based applications. [oauth-security-topics] describes some additional requirements around refresh tokens on top of the recommendations of [RFC6749]. Applications and authorization servers conforming to this BCP MUST also follow the recommendations in [oauth-security-topics] around refresh tokens if refresh tokens are issued to browser-based applications.¶
In particular, authorization servers:¶
For example:¶
By limiting the overall refresh token lifetime to the lifetime of the initial refresh token, this ensures a stolen refresh token cannot be used indefinitely.¶
Authorization servers MAY set different policies around refresh token issuance, lifetime and expiration for browser-based applications compared to other public clients.¶
Browser-based applications are considered public clients as defined by Section 2.1 of OAuth 2.0 [RFC6749], and MUST be registered with the authorization server as such. Authorization servers MUST record the client type in the client registration details in order to identify and process requests accordingly.¶
Authorization servers MUST require that browser-based applications register one or more redirect URIs.¶
Since a browser-based application's source code is delivered to the end-user's browser, it cannot contain provisioned secrets. As such, a browser-based app with native OAuth support is considered a public client as defined by Section 2.1 of OAuth 2.0 [RFC6749].¶
Secrets that are statically included as part of an app distributed to multiple users should not be treated as confidential secrets, as one user may inspect their copy and learn the shared secret. For this reason, and those stated in Section 5.3.1 of [RFC6819], it is NOT RECOMMENDED for authorization servers to require client authentication of browser-based applications using a shared secret, as this serves little value beyond client identification which is already provided by the client_id request parameter.¶
Authorization servers that still require a statically included shared secret for SPA clients MUST treat the client as a public client, and not accept the secret as proof of the client's identity. Without additional measures, such clients are subject to client impersonation (see Section 9.3 below).¶
As stated in Section 10.2 of OAuth 2.0 [RFC6749], the authorization server SHOULD NOT process authorization requests automatically without user consent or interaction, except when the identity of the client can be assured.¶
If authorization servers restrict redirect URIs to a fixed set of absolute HTTPS URIs, preventing the use of wildcard domains, wildcard paths, or wildcard query string components, this exact match of registered absolute HTTPS URIs MAY be accepted by authorization servers as proof of identity of the client for the purpose of deciding whether to automatically process an authorization request when a previous request for the client_id has already been approved.¶
Clients MUST prevent Cross-Site Request Forgery (CSRF) attacks against their redirect URI. Clients can accomplish this by either ensuring the authorization server supports PKCE and relying on the CSRF protection that PKCE provides, or if the client is also an OpenID Connect client, using the OpenID Connect "nonce" parameter, or by using the "state" parameter to carry one-time-use CSRF tokens as described in Section 7.1.¶
See Section 2.1 of [oauth-security-topics] for additional details.¶
Authorization server mix-up attacks mark a severe threat to every client that supports at least two authorization servers. To conform to this BCP such clients MUST apply countermeasures to defend against mix-up attacks.¶
It is RECOMMENDED to defend against mix-up attacks by identifying and validating the issuer of the authorization response. This can be achieved either by using the "iss" response parameter, as defined in [oauth-iss-auth-resp], or by using the "iss" Claim of the ID token when OpenID Connect is used.¶
Alternative countermeasures, such as using distinct redirect URIs for each issuer, SHOULD only be used if identifying the issuer as described is not possible.¶
Section 4.4 of [oauth-security-topics] provides additional details about mix-up attacks and the countermeasures mentioned above.¶
To complete the Authorization Code flow, the browser-based application will need to exchange the authorization code for an access token at the token endpoint. If the authorization server provides additional endpoints to the application, such as metadata URLs, dynamic client registration, revocation, introspection, discovery or user info endpoints, these endpoints may also be accessed by the browser-based app. Since these requests will be made from a browser, authorization servers MUST support the necessary CORS headers (defined in [Fetch]) to allow the browser to make the request.¶
This specification does not include guidelines for deciding whether a CORS policy for the token endpoint should be a wildcard origin or more restrictive. Note, however, that the browser will attempt to GET or POST to the API endpoint before knowing any CORS policy; it simply hides the succeeding or failing result from JavaScript if the policy does not allow sharing.¶
A browser-based application that wishes to use either long-lived refresh tokens or privileged scopes SHOULD restrict its JavaScript execution to a set of statically hosted scripts via a Content Security Policy ([CSP2]) or similar mechanism. A strong Content Security Policy can limit the potential attack vectors for malicious JavaScript to be executed on the page.¶
The OAuth 2.0 Implicit flow (defined in Section 4.2 of OAuth 2.0 [RFC6749]) works by the authorization server issuing an access token in the authorization response (front channel) without the code exchange step. In this case, the access token is returned in the fragment part of the redirect URI, providing an attacker with several opportunities to intercept and steal the access token.¶
Authorization servers MUST NOT issue access tokens in the authorization response, and MUST issue access tokens only from the token endpoint.¶
Many attacks on the Implicit flow described by [RFC6819] and Section 4.1.2 of [oauth-security-topics] do not have sufficient mitigation strategies. The following sections describe the specific attacks that cannot be mitigated while continuing to use the Implicit flow.¶
If an attacker is able to cause the authorization response to be sent to a URI under their control, they will directly get access to the authorization response including the access token. Several methods of performing this attack are described in detail in [oauth-security-topics].¶
An attacker could obtain the access token from the browser's history. The countermeasures recommended by [RFC6819] are limited to using short expiration times for tokens, and indicating that browsers should not cache the response. Neither of these fully prevent this attack, they only reduce the potential damage.¶
Additionally, many browsers now also sync browser history to cloud services and to multiple devices, providing an even wider attack surface to extract access tokens out of the URL.¶
This is discussed in more detail in Section 4.3.2 of [oauth-security-topics].¶
An attacker could modify the page or inject scripts into the browser through various means, including when the browser's HTTPS connection is being intercepted by, for example, a corporate network. While man-in-the-middle attacks are typically out of scope of basic security recommendations to prevent, in the case of browser-based apps they are much easier to perform. An injected script can enable an attacker to have access to everything on the page.¶
The risk of a malicious script running on the page may be amplified when the application
uses a known standard way of obtaining access tokens, namely that the attacker can
always look at the window.location
variable to find an access token. This threat profile
is different from an attacker specifically targeting an individual application
by knowing where or how an access token obtained via the Authorization Code flow may
end up being stored.¶
It is relatively common to use third-party scripts in browser-based apps, such as analytics tools, crash reporting, and even things like a Facebook or Twitter "like" button. In these situations, the author of the application may not be able to be fully aware of the entirety of the code running in the application. When an access token is returned in the fragment, it is visible to any third-party scripts on the page.¶
In addition to the countermeasures described by [RFC6819] and [oauth-security-topics], using the Authorization Code flow with PKCE extension prevents the attacks described above by avoiding returning the access token in the redirect response at all.¶
When PKCE is used, if an authorization code is stolen in transport, the attacker is unable to do anything with the authorization code.¶
There are several additional reasons the Implicit flow is disadvantageous compared to using the standard Authorization Code flow.¶
In OpenID Connect, the ID Token is sent in a known format (as a JWT), and digitally
signed. Returning an ID token using the Implicit flow (response_type=id_token
) requires the client
validate the JWT signature, as malicious parties could otherwise craft and supply
fraudulent ID tokens. Performing OpenID Connect using the Authorization Code flow provides
the benefit of the client not needing to verify the JWT signature, as the ID token will
have been fetched over an HTTPS connection directly from the authorization server. Additionally,
in many cases an application will request both an ID token and an access token, so it is
simplier and provides fewer attack vectors to obtain both via the Authorization Code flow.¶
Historically, the Implicit flow provided an advantage to browser-based apps since JavaScript could always arbitrarily read and manipulate the fragment portion of the URL without triggering a page reload. This was necessary in order to remove the access token from the URL after it was obtained by the app.¶
Modern browsers now have the Session History API (described in "Session history and navigation" of [HTML]), which provides a mechanism to modify the path and query string component of the URL without triggering a page reload. This means modern browser-based apps can use the unmodified OAuth 2.0 Authorization Code flow, since they have the ability to remove the authorization code from the query string without triggering a page reload thanks to the Session History API.¶
The OWASP Foundation (https://www.owasp.org/) maintains a set of security recommendations and best practices for web applications, and it is RECOMMENDED to follow these best practices when creating an OAuth 2.0 Browser-Based application.¶
This document does not require any IANA actions.¶
OAuth authorization servers that support browser-based apps MUST:¶
[[ To be removed from the final specification ]]¶
-10¶
-09¶
-08¶
-07¶
-06¶
-05¶
-04¶
-03¶
-02¶
-01¶
The authors would like to acknowledge the work of William Denniss and John Bradley, whose recommendation for native apps informed many of the best practices for browser-based applications. The authors would also like to thank Hannes Tschofenig and Torsten Lodderstedt, the attendees of the Internet Identity Workshop 27 session at which this BCP was originally proposed, and the following individuals who contributed ideas, feedback, and wording that shaped and formed the final specification:¶
Annabelle Backman, Brian Campbell, Brock Allen, Christian Mainka, Daniel Fett, George Fletcher, Hannes Tschofenig, Janak Amarasena, John Bradley, Joseph Heenan, Justin Richer, Karl McGuinness, Karsten Meyer zu Selhausen, Leo Tohill, Mike Jones, Tomek Stojecki, Torsten Lodderstedt, Vittorio Bertocci and Yannick Majoros.¶