Open Authentication Protocol A. Parecki
Internet-Draft Okta
Intended status: Best Current Practice D. Waite
Expires: January 9, 2020 Ping Identity
July 08, 2019

OAuth 2.0 for Browser-Based Apps


OAuth 2.0 authorization requests from browser-based apps must be made using the authorization code grant with the PKCE extension, and should not be issued a client secret when registered.

This specification details the security considerations that must be taken into account when developing browser-based applications, as well as best practices for how they can securely implement OAuth 2.0.

Status of This Memo

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

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 January 9, 2020.

Copyright Notice

Copyright (c) 2019 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 ( 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 Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.

Table of Contents

1. Introduction

This specification describes the current best practices for implementing OAuth 2.0 authorization flows in applications running entirely 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.

AppAuth steers developers away from performing user authorization via embedding user agents such as browser controls into native apps, instead insisting that an external agent (such as the system browser) be used. The RFC continues on to promote capabilities and supplemental specifications beyond the base OAuth 2.0 and OpenID Connect specifications to improve baseline security, such as [RFC7636], also known as PKCE.

OAuth 2.0 for Browser-Based Apps addresses the similarities between implementing OAuth for native apps as well as 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.

2. Notational Conventions

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].

3. Terminology

In addition to the terms defined in referenced specifications, this document uses the following terms:

In this document, "OAuth" refers to OAuth 2.0, [RFC6749].
"Browser-based application":
An application that is dynamically downloaded and executed in a web browser, usually written in JavaScript. Also sometimes referred to as a "single-page application", or "SPA".

4. Overview

At the time that OAuth 2.0 RFC 6749 was 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 the principal motivation 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 assures 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.

Applications should:

OAuth 2.0 servers should:

5. First-Party Applications

While OAuth and OpenID Connect were initially created to allow third-party applications to access an API on behalf of a user, they have both proven to be useful in a first-party scenario as well. First-party apps are applications where by the same organization that provides the API being accessed by the application.

For example, 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 the OAuth Authorization Code flow as described later in this document or use the OAuth Password grant.

It is strongly RECOMMENDED that applications use the Authorization Code flow over the Password grant for several reasons. By redirecting 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 Password grant does not provide any built-in mechanism for these, and must be extended with custom code.

6. Application Architecture Patterns

There are three primary architectural patterns available when building browser-based applications.

These three architectures have different use cases and considerations.

6.1. Apps Served from a Common Domain as the Resource Server

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), it is likely a better decision to avoid using OAuth entirely, and just use session authentication to communicate directly with the API.

OAuth and OpenID Connect provide very little benefit in this deployment scenario, so it is recommended to reconsider whether you need OAuth or OpenID Connect at all in this case. Session authentication has the benefit of having fewer moving parts and fewer attack vectors. OAuth and OpenID Connect were created primarily for third-party or federated access to APIs, so may not be the best solution in a same-domain scenario.

6.2. Apps Served from a Dynamic Application Server

|             |
|   Server    |
|             |

   ^     +
   |(A)  |(B)
   |     |
   +     v

+-------------+             +--------------+
|             | +---------> |              |
| Application |   (C)       |   Resource   |
|   Server    |             |    Server    |
|             | <---------+ |              |
+-------------+   (D)       +--------------+

    ^    +
    |    |
    |    | browser
    |    | cookie
    |    |
    +    v

|             |
|   Browser   |
|             |

In this architecture, the JavaScript code is loaded from a dynamic Application Server that also has the ability to execute code itself. This enables the ability to keep all of the steps involved in obtaining an access token outside of the JavaScript application.

(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 to initiate a request request for an access token. Upon handling the redirect from the Authorization Server, the Application Server will request an access token using the authorization code returned (A), which will be returned to the Application Server (B). The Application Server utilizes its own session with the browser to store the access token.

When the JavaScript application in the browser wants to make a request to the Resource Server, it MUST instead make the request to the Application Server, and the Application Server will make the request with the access token to the Resource Server (C), and forward the response (D) back to the browser.

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 at the OWASP Foundation (, such as setting an HTTP-only and Secure cookie to authenticate the session between the browser and Application Server.

In this scenario, the session between the browser and Application Server MAY be either a session cookie provided by the Application Server, OR the access token itself. Note that if the access token is used as the session identifier, this exposes the access token to the end user even if it is not available to the JavaScript application, so some authorization servers may wish to limit the capabilities of these clients to mitigate risk.

6.3. Apps Served from a Static Web 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). The application then runs in the browser, and is considered a public client since it has no ability to be issued a client secret.

The code in the browser then 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 JavaScript app is then responsible for storing the access token securely using appropriate browser APIs.

When the JavaScript application in the browser wants to make a request to the Resource Server, it can include the access token in the request (D) and make the request directly.

In this scenario, the Authorization Server and Resource Server MUST support the necessary CORS headers to enable the JavaScript code to make this POST request from the domain on which the script is executing. (See Section 9.6 for additional details.)

7. Authorization Code Flow

Public browser-based apps needing user authorization create an authorization request URI with the authorization code grant type per Section 4.1 of OAuth 2.0 [RFC6749], using a redirect URI capable of being received by the app.

7.1. Initiating the Authorization Request from a Browser-Based Application

Public browser-based apps MUST implement the Proof Key for Code Exchange (PKCE [RFC7636]) extension to OAuth, and authorization servers MUST support PKCE for such clients.

The PKCE extension prevents an attack where the authorization code is intercepted and exchanged for an access token by a malicious client, by providing the authorization server with a way to verify the same client instance that exchanges the authorization code is the same one that initiated the flow.

Browser-based apps MUST use the OAuth 2.0 "state" parameter to protect themselves against Cross-Site Request Forgery and authorization code swap attacks and MUST use a unique value for each authorization request, and MUST verify the returned state in the authorization response matches the original state the app created.

7.2. Handling the Authorization Code Redirect

Authorization servers MUST require an exact match of a registered redirect URI.

8. Refresh Tokens

Refresh tokens provide a way for applications to obtain a new access token when the initial access token expires. [oauth-security-topics] describes some additional requirements around refresh tokens on top of the recommendations of [RFC6749].

For public clients, the risk of a leaked refresh token is much greater than leaked access tokens, since an attacker can potentially continue using the stoken refresh token to obtain new access without being detectable by the authorization server. Additionally, browser-based applications provide many attack vectors by which a refresh token can be leaked. As such, these applications are considered a higher risk for handling refresh tokens.

Authorization servers SHOULD NOT issue refresh tokens to browser-based applications.

If an authorization server does choose to issue refresh tokens to browser-based applications, then it MUST issue a new refresh token with every access token refresh response. Doing this mitigates the risk of a leaked refresh token, as a leaked refresh token can be detected if both the attacker and the legitimate client attempt to use the same refresh token. Authorization servers MUST follow the additional refresh token replay mitigation techniques described in [oauth-security-topics].

9. Security Considerations

9.1. Registration of Browser-Based Apps

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.

9.2. Client Authentication

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).

9.3. Client Impersonation

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. Even when the user has previously approved an authorization request for a given client_id, the request SHOULD be processed as if no previous request had been approved, unless the identity of the client can be proven.

If authorization servers restrict redirect URIs to a fixed set of absolute HTTPS URIs without wildcard domains, paths, or 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.

9.4. Cross-Site Request Forgery Protections

Section 5.3.5 of [RFC6819] recommends using the "state" parameter to link client requests and responses to prevent CSRF (Cross-Site Request Forgery) attacks. To conform to this best practice, use of the "state" parameter is REQUIRED, as described in Section 7.1.

9.5. Authorization Server Mix-Up Mitigation

The security considerations around the authorization server mix-up that are referenced in Section 8.10 of [RFC8252] also apply to browser-based apps.

Clients MUST use a unique redirect URI for each authorization server used by the application. The client MUST store the redirect URI along with the session data (e.g. along with "state") and MUST verify that the URI on which the authorization response was received exactly matches.

9.6. Cross-Domain Requests

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. If POSTs in particular from unsupported single-page applications are to be rejected as errors per authorization server security policy, such rejection is typically done based on the Origin request header.

9.7. Content-Security Policy

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.

9.8. OAuth Implicit Grant Authorization Flow

The OAuth 2.0 Implicit grant authorization flow (defined in Section 4.2 of OAuth 2.0 [RFC6749]) works by receiving an access token in the HTTP redirect (front-channel) immediately 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. Several attacks on the implicit flow are described by [RFC6819] and [oauth-security-topics], not all of which have sufficient mitigation strategies.

9.8.1. Threat: Interception of the Redirect URI

If an attacker is able to cause the authorization response to be sent to a URI under his control, he will directly get access to the fragment carrying the access token. A method of performing this attack is described in detail in [oauth-security-topics].

9.8.2. Threat: Access Token Leak in Browser History

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.

9.8.3. Threat: Manipulation of Scripts

An attacker could modify the page or inject scripts into the browser via various means, including when the browser's HTTPS connection is being man-in-the-middled by for example a corporate network. While this type of attack is typically out of scope of basic security recommendations to prevent, in the case of browser-based apps it is much easier to perform this kind of attack, where an injected script can suddenly have access to everything on the page.

The risk of a malicious script running on the page is far greater when the application uses a known standard way of obtaining access tokens, namely that the attacker can always look at the window.location to find an access token. This threat profile is very different compared to 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.

9.8.4. Threat: Access Token Leak to Third Party Scripts

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.

9.8.5. Countermeasures

In addition to the countermeasures described by [RFC6819] and [oauth-security-topics], using the authorization code with PKCE avoids these attacks.

When PKCE is used, if an authorization code is stolen in transport, the attacker is unable to do anything with the authorization code.

9.8.6. Disadvantages of the Implicit Flow

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. Performing OpenID Connect using the authorization code flow also provides the additional benefit of the client not needing to verify the JWT signature, as the token will have been fetched over an HTTPS connection directly from the authorization server. However, returning an id_token using the Implicit flow requires the client validate the JWT signature, as malicious parties could otherwise craft and supply fraudulent id_tokens.

9.8.7. Historic Note

Historically, the Implicit flow provided an advantage to single-page apps since JavaScript could always arbitrarily read and manipulate the fragment portion of the URL without triggering a page reload. Now with the Session History API (described in "Session history and navigation" of [HTML]), browsers have a mechanism to modify the path component of the URL without triggering a page reload, so this overloaded use of the fragment portion is no longer needed.

9.9. Additional Security Considerations

The OWASP Foundation ( 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.

10. IANA Considerations

This document does not require any IANA actions.

11. References

11.1. Normative References

[CSP2] West, M., Barth, A. and D. Veditz, "Content Security Policy", December 2016.
[Fetch] whatwg, "Fetch", 2018.
[oauth-security-topics] Lodderstedt, T., Bradley, J., Labunets, A. and D. Fett, "OAuth 2.0 Security Best Current Practice", November 2018.
[RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, DOI 10.17487/RFC2119, March 1997.
[RFC6749] Hardt, D., "The OAuth 2.0 Authorization Framework", RFC 6749, DOI 10.17487/RFC6749, October 2012.
[RFC6819] Lodderstedt, T., McGloin, M. and P. Hunt, "OAuth 2.0 Threat Model and Security Considerations", RFC 6819, DOI 10.17487/RFC6819, January 2013.
[RFC7636] Sakimura, N., Bradley, J. and N. Agarwal, "Proof Key for Code Exchange by OAuth Public Clients", RFC 7636, DOI 10.17487/RFC7636, September 2015.
[RFC8252] Denniss, W. and J. Bradley, "OAuth 2.0 for Native Apps", BCP 212, RFC 8252, DOI 10.17487/RFC8252, October 2017.

11.2. Informative References

[HTML] whatwg, "HTML", 2018.

Appendix A. Server Support Checklist

OAuth servers that support browser-based apps MUST:

  1. Require "https" scheme redirect URIs.
  2. Require exact matching of registered redirect URIs.
  3. Support PKCE [RFC7636]. Required to protect authorization code grants sent to public clients. See Section 7.1
  4. Support cross-domain requests at the token endpoint in order to allow browsers to make the authorization code exchange request. See Section 9.6
  5. Not assume that browser-based clients can keep a secret, and SHOULD NOT issue secrets to applications of this type.

Appendix B. Document History

[[ To be removed from the final specification ]]



Appendix C. Acknowledgements

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, John Bradley, Joseph Heenan, Justin Richer, Karl McGuinness, Leo Tohill, Tomek Stojecki, Torsten Lodderstedt, and Vittorio Bertocci.

Authors' Addresses

Aaron Parecki Okta EMail: URI:
David Waite Ping Identity EMail: