Movatterモバイル変換


[0]ホーム

URL:


RFC 9700OAuth 2.0 Security BCPJanuary 2025
Lodderstedt, et al.Best Current Practice[Page]
Stream:
Internet Engineering Task Force (IETF)
RFC:
9700
BCP:
240
Updates:
6749,6750,6819
Category:
Best Current Practice
Published:
ISSN:
2070-1721
Authors:
T. Lodderstedt
SPRIND
J. Bradley
Yubico
A. Labunets
Independent Researcher
D. Fett
Authlete

RFC 9700

Best Current Practice for OAuth 2.0 Security

Abstract

This document describes best current security practice for OAuth 2.0. It updatesand extends the threat model and security advice given in RFCs 6749, 6750, and 6819 to incorporate practical experiences gathered sinceOAuth 2.0 was published and covers new threats relevant due to the broaderapplication of OAuth 2.0. Further, it deprecates some modes of operation that aredeemed less secure or even insecure.

Status of This Memo

This memo documents an Internet Best Current Practice.

This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Further information on BCPs is available in Section 2 of RFC 7841.

Information about the current status of this document, any errata, and how to provide feedback on it may be obtained athttps://www.rfc-editor.org/info/rfc9700.

Copyright Notice

Copyright (c) 2025 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.

Table of Contents

1.Introduction

Since its publication in[RFC6749] and[RFC6750], OAuth 2.0 (referred to as simply "OAuth" in this document) has gained massive traction in the marketand became the standard for API protection and the basis for federatedlogin using OpenID Connect[OpenID.Core]. While OAuth is used in avariety of scenarios and different kinds of deployments, the followingchallenges can be observed:

This document provides updated security recommendations to address thesechallenges. It introduces new requirements beyond those defined in existingspecifications such as OAuth 2.0[RFC6749] and OpenID Connect[OpenID.Core]and deprecates some modes of operation that are deemed less secure or eveninsecure. However, this document does not supplant the security advice given in[RFC6749],[RFC6750], and[RFC6819], but complements those documents.

Naturally, not all existing ecosystems and implementations arecompatible with the new requirements, and following the best practices described inthis document may break interoperability. Nonetheless, it isRECOMMENDED thatimplementers upgrade their implementations and ecosystems as soon as feasible.

OAuth 2.1, under development as[OAUTH-V2.1], will incorporatesecurity recommendations from this document.

1.1.Structure

The remainder of this document is organized as follows:Section 2summarizes the most important best practices for every OAuth implementer.Section 3 presents the updated OAuth attacker model.Section 4 is adetailed analysis of the threats and implementation issues that can be found inthe wild (at the time of writing) along with a discussion of potential countermeasures.

1.2.Conventions and Terminology

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 BCP 14[RFC2119][RFC8174] when, and only when, they appear in all capitals, as shown here.

This specification uses the terms "access token", "authorizationendpoint", "authorization grant", "authorization server", "client","client identifier" (client ID), "protected resource", "refreshtoken", "resource owner", "resource server", and "token endpoint"defined by OAuth 2.0[RFC6749].

An "open redirector" is an endpoint on a web server that forwards a user'sbrowser to an arbitrary URI obtained from a query parameter.

2.Best Practices

This section describes the core set of security mechanisms and measures thatare considered to be best practices at the time of writing. Detailsabout these security mechanisms and measures (including detailed attackdescriptions) and requirements for less commonly used options are provided inSection 4.

2.1.Protecting Redirect-Based Flows

When comparing client redirection URIs against pre-registered URIs, authorizationserversMUST utilize exact string matching except for port numbers inlocalhost redirection URIs of native apps (seeSection 4.1.3). Thismeasure contributes to the prevention of leakage of authorization codes andaccess tokens (seeSection 4.1). It can also help to detectmix-up attacks (seeSection 4.4).

Clients and authorization serversMUST NOT expose URLs that forward the user's browser toarbitrary URIs obtained from a query parameter (open redirectors) asdescribed inSection 4.11. Open redirectors can enableexfiltration of authorization codes and access tokens.

ClientsMUST prevent Cross-Site Request Forgery (CSRF). In thiscontext, CSRF refers to requests to the redirection endpoint that donot originate at the authorization server, but at a malicious third party(seeSection 4.4.1.8 of [RFC6819] for details). Clients that haveensured that the authorization server supports Proof Key for Code Exchange (PKCE)[RFC7636]MAYrely on the CSRF protection provided by PKCE. In OpenID Connect flows,thenonce parameter provides CSRF protection. Otherwise, one-timeuse CSRF tokens carried in thestate parameter that are securelybound to the user agentMUST be used for CSRF protection (seeSection 4.7.1).

When an OAuth client can interact with more than one authorization server, adefense against mix-up attacks (seeSection 4.4) isREQUIRED. To this end, clientsSHOULD

  • use theiss parameter as a countermeasure according to[RFC9207], or
  • use an alternative countermeasure based on aniss value in theauthorization response (such as theiss claim in the ID Token in[OpenID.Core] or in[OpenID.JARM] responses), processing that value as described in[RFC9207].

In the absence of these options, clientsMAY instead use distinct redirection URIsto identify authorization endpoints and token endpoints, as described inSection 4.4.2.

An authorization server that redirects a request potentially containing user credentialsMUST avoid forwarding these user credentials accidentally (seeSection 4.12 for details).

2.1.1.Authorization Code Grant

ClientsMUST prevent authorization codeinjection attacks (seeSection 4.5) and misuse of authorization codes using one of the following options:

  • Public clientsMUST use PKCE[RFC7636] to this end, as motivated inSection 4.5.3.1.
  • For confidential clients, the use of PKCE[RFC7636] isRECOMMENDED, as itprovides strong protection against misuse and injection of authorizationcodes as described inSection 4.5.3.1. Also, as a side effect,it prevents CSRF even in the presence of strong attackers as described inSection 4.7.1.
  • With additional precautions, described inSection 4.5.3.2,confidential OpenID Connect[OpenID.Core] clientsMAY use thenonce parameter and therespective Claim in the ID Token instead.

In any case, the PKCE challenge or OpenID ConnectnonceMUST betransaction-specific and securely bound to the client and the user agent inwhich the transaction was started.Authorization servers are encouraged to make a reasonable effort at detecting andpreventing the use of constant values for the PKCE challenge or OpenID Connectnonce.

Note: Although PKCE was designed as a mechanism to protect nativeapps, this advice applies to all kinds of OAuth clients, including webapplications.

When using PKCE, clientsSHOULD use PKCE code challenge methods thatdo not expose the PKCE verifier in the authorization request.Otherwise, attackers that can read the authorization request (cf. Attacker(A4) inSection 3) can break the security providedby PKCE. Currently,S256 is the only such method.

Authorization serversMUST support PKCE[RFC7636].

If a client sends a valid PKCEcode_challenge parameter in theauthorization request, the authorization serverMUST enforce the correct usageofcode_verifier at the token endpoint.

Authorization serversMUST mitigate PKCE downgrade attacks by ensuring that atoken request containing acode_verifier parameter is accepted only if acode_challenge parameter was present in the authorization request; seeSection 4.8.2 for details.

Authorization serversMUST provide a way to detect their support forPKCE. It isRECOMMENDED for authorization servers to publish the elementcode_challenge_methods_supported in their Authorization Server Metadata[RFC8414]containing the supported PKCE challenge methods (which can be used bythe client to detect PKCE support). Authorization serversMAY instead provide adeployment-specific way to ensure or determine PKCE support by the authorization server.

2.1.2.Implicit Grant

The implicit grant (response typetoken) and other response typescausing the authorization server to issue access tokens in theauthorization response are vulnerable to access token leakage andaccess token replay as described in Sections4.1,4.2,4.3, and4.6.

Moreover, no standardized method for sender-constraining exists tobind access tokens to a specific client (as recommended inSection 2.2) when the access tokens are issued in theauthorization response. This means that an attacker can use the leaked or stolenaccess token at a resource endpoint.

In order to avoid these issues, clientsSHOULD NOT use the implicitgrant (response typetoken) or other response types issuingaccess tokens in the authorization response, unless access token injectionin the authorization response is prevented and the aforementioned token leakagevectors are mitigated.

ClientsSHOULD instead use the response typecode (i.e., authorizationcode grant type) as specified inSection 2.1.1 or any other response type thatcauses the authorization server to issue access tokens in the tokenresponse, such as thecode id_token response type. This allows theauthorization server to detect replay attempts by attackers andgenerally reduces the attack surface since access tokens are notexposed in URLs. It also allows the authorization server tosender-constrain the issued tokens (seeSection 2.2).

2.2.Token Replay Prevention

2.2.1.Access Tokens

A sender-constrained access token scopes the applicability of an accesstoken to a certain sender. This sender is obliged to demonstrate knowledgeof a certain secret as a prerequisite for the acceptance of that token atthe recipient (e.g., a resource server).

Authorization and resource serversSHOULD use mechanisms for sender-constrainingaccess tokens, such as mutual TLS for OAuth 2.0[RFC8705] or OAuth 2.0Demonstrating Proof of Possession (DPoP)[RFC9449] (seeSection 4.10.1), to prevent misuse of stolen and leaked access tokens.

2.2.2.Refresh Tokens

Refresh tokens for public clientsMUST be sender-constrained or use refreshtoken rotation as described inSection 4.14.[RFC6749] alreadymandates that refresh tokens for confidential clients can only be used by theclient for which they were issued.

2.3.Access Token Privilege Restriction

The privileges associated with an access tokenSHOULD be restricted tothe minimum required for the particular application or use case. Thisprevents clients from exceeding the privileges authorized by theresource owner. It also prevents users from exceeding their privilegesauthorized by the respective security policy. Privilege restrictionsalso help to reduce the impact of access token leakage.

In particular, access tokensSHOULD be audience-restricted to a specific resourceserver or, if that is not feasible, to a small set of resource servers. To put this into effect, the authorization server associatesthe access token with certain resource servers, and every resourceserver is obliged to verify, for every request, whether the accesstoken sent with that request was meant to be used for that particularresource server. If it was not, the resource serverMUST refuse to serve therespective request. Theaud claim as defined in[RFC9068]MAY beused to audience-restrict access tokens. Clients and authorization serversMAY utilize theparametersscope orresource as specified in[RFC6749] and[RFC8707], respectively, to determine theresource server they want to access.

Additionally, access tokensSHOULD be restricted to certain resourcesand actions on resource servers or resources. To put this into effect,the authorization server associates the access token with therespective resource and actions and every resource server is obligedto verify, for every request, whether the access token sent with thatrequest was meant to be used for that particular action on theparticular resource. If not, the resource server must refuse to servethe respective request. Clients and authorization serversMAY utilizethe parameterscope as specified in[RFC6749] andauthorization_details as specified in[RFC9396] to determine thoseresources and/or actions.

2.4.Resource Owner Password Credentials Grant

The resource owner password credentials grant[RFC6749]MUST NOTbe used. This grant type insecurely exposes the credentials of the resourceowner to the client. Even if the client is benign, usage of this grant results in an increasedattack surface (i.e., credentials can leak in more places than just the authorization server) and in training users to enter their credentials in places other than the authorization server.

Furthermore, the resource owner password credentials grant is not designed towork with two-factor authentication and authentication processes that requiremultiple user interaction steps. Authentication with cryptographic credentials(cf. WebCrypto[W3C.WebCrypto], WebAuthn[W3C.WebAuthn]) may be impossibleto implement with this grant type, as it is usually bound to a specific web origin.

2.5.Client Authentication

Authorization serversSHOULD enforce client authentication if it is feasible, inthe particular deployment, to establish a process for issuance/registration ofcredentials for clients and ensuring the confidentiality of those credentials.

It isRECOMMENDED to use asymmetric cryptography forclient authentication, such as mutual TLS for OAuth 2.0[RFC8705] or signed JWTs("Private Key JWT") in accordance with[RFC7521] and[RFC7523]. The latter is defined in[OpenID.Core] as the client authentication methodprivate_key_jwt).When asymmetric cryptography for client authentication is used, authorizationservers do not need to store sensitive symmetric keys, making thesemethods more robust against leakage of keys.

2.6.Other Recommendations

The use of OAuth Authorization Server Metadata[RFC8414] can help to improve the security of OAuthdeployments:

  • It ensures that security features and other new OAuth features can be enabledautomatically by compliant software libraries.
  • It reduces chances for misconfigurations -- for example, misconfigured endpointURLs (that might belong to an attacker) or misconfigured security features.
  • It can help to facilitate rotation of cryptographic keys and to ensurecryptographic agility.

It is thereforeRECOMMENDED that authorization servers publish OAuth Authorization Server Metadata according to[RFC8414] and that clients make use of this Authorization Server Metadata (when available) to configure themselves.

Under the conditions described inSection 4.15.1,authorization serversSHOULD NOT allow clients to influence theirclient_id orany other claim that could cause confusion with a genuine resource owner.

It isRECOMMENDED to use end-to-end TLS according to[BCP195] between the client and the resource server. If TLStraffic needs to be terminated at an intermediary, refer toSection 4.13 for further security advice.

Authorization responsesMUST NOT be transmitted over unencrypted networkconnections. To this end, authorization serversMUST NOT allow redirection URIs that use thehttpscheme except for native clients that use loopback interface redirection asdescribed inSection 7.3 of [RFC8252].

If the authorization response is sent with in-browser communication techniqueslike postMessage[WHATWG.postmessage_api] instead of HTTP redirects, both theinitiator and receiver of the in-browser messageMUST be strictly verified as describedinSection 4.17.

To support browser-based clients, endpoints directly accessed by such clientsincluding the Token Endpoint, Authorization Server Metadata Endpoint,jwks_uriEndpoint, and Dynamic Client Registration EndpointMAY support the use ofCross-Origin Resource Sharing (CORS)[WHATWG.CORS]. However, CORSMUST NOT besupported at the authorization endpoint, as the client does not access thisendpoint directly; instead, the client redirects the user agent to it.

3.The Updated OAuth 2.0 Attacker Model

In[RFC6819], a threat model is laid out that describes the threats againstwhich OAuth deployments must be protected. While doing so,[RFC6819] makescertain assumptions about attackers and their capabilities, i.e., it implicitlyestablishes an attacker model. In the following, this attacker model is madeexplicit and is updated and expanded to account for the potentially dynamicrelationships involving multiple parties (as described inSection 1), toinclude new types of attackers, and to define the attacker model more clearly.

The goal of this document is to ensure that the authorization of a resourceowner (with a user agent) at an authorization server and the subsequent usage ofthe access token at a resource server is protected, as well as practicallypossible, at least against the following attackers.

(A1)

Web attackers that can set up and operate an arbitrary number ofnetwork endpoints (besides the "honest" ones) including browsers andservers. Web attackers may set up websites that are visited by the resourceowner, operate their own user agents, and participate in the protocol.

In particular, web attackers may operate OAuth clients that are registeredat the authorization server, and they may operate their own authorization andresource servers that can be used (in parallel to the "honest" ones) by theresource owner and other resource owners.

It must also be assumed that web attackers can lure the user tonavigate their browser to arbitrary attacker-chosen URIs at any time. In practice, thiscan be achieved in many ways, for example, by injecting maliciousadvertisements into advertisement networks or by sendinglegitimate-looking emails.

Web attackers can use their own user credentials to create newmessages as well as any secrets they learned previously. Forexample, if a web attacker learns an authorization code of a userthrough a misconfigured redirection URI, the web attacker can thentry to redeem that code for an access token.

They cannot, however, read or manipulate messages that are nottargeted towards them (e.g., sent to a URL of an authorization server not under control of an attacker).

(A2)

Network attackers that additionally have full control overthe network over which protocol participants communicate. They caneavesdrop on, manipulate, and spoof messages, except when theseare properly protected by cryptographic methods (e.g., TLS).Network attackers can also block arbitrary messages.

While an example for a web attacker would be a customer of an internetservice provider, network attackers could be the internet serviceprovider itself, an attacker in a public (Wi-Fi) network using ARPspoofing, or a state-sponsored attacker with access to internetexchange points, for instance.

The aforementioned attackers(A1) and(A2) conform to the attacker model that was used in formal analysisefforts for OAuth[arXiv.1601.01229]. This is a minimal attacker model.ImplementersMUST take into account all possible types of attackers in theenvironment of their OAuth implementations. For example, in[arXiv.1901.11520],a very strong attacker model is used that includes attackers that havefull control over the token endpoint. This models effects of apossible misconfiguration of endpoints in the ecosystem, which can be avoidedby using authorization server metadata as described inSection 2.6. Such an attacker is therefore not listed here.

However, previous attacks on OAuth have shown that the following types ofattackers are relevant in particular:

(A3)

Attackers that can read, but not modify, the contents of the authorization response (i.e., the authorization response can leak to an attacker).

Examples of such attacks include open redirector attacks and mix-up attacks (seeSection 4.4), where the client is tricked into sending credentials to an attacker-controlled authorization server.

Also, this includes attacks that take advantage of:

  • insufficient checking of redirect URIs (seeSection 4.1);
  • problems existing on mobile operating systems, where different apps can register themselves on the same URI; and
  • URLs stored/logged by browsers (history), proxy servers, and operating systems.
(A4)

Attackers that can read, but not modify, the contents of theauthorization request (i.e., the authorization request can leak,in the same manner as above, to an attacker).

(A5)

Attackers that can acquire an access token issued by an authorization server. Forexample, a resource server may be compromised by an attacker, anaccess token may be sent to an attacker-controlled resource serverdue to a misconfiguration, or social engineering may be used to get a resource owner touse an attacker-controlled resource server. Also seeSection 4.9.2.

(A3),(A4), and(A5) typically occur together with either(A1) or(A2).Attackers can collaborate to reach a common goal.

Note that an Attacker(A1) or(A2) can be a resource owner oract as one. For example, such an attacker can use their own browser to replaytokens or authorization codes obtained by any of the attacks describedabove at the client or resource server.

This document focuses on threats resulting from Attackers(A1) to(A5).

4.Attacks and Mitigations

This section gives a detailed description of attacks on OAuth implementations,along with potential countermeasures. Attacks and mitigations already covered in[RFC6819] are not listed here, except where new recommendations are made.

This section further defines additional requirements (beyond those defined inSection 2) for certain cases and protocol options.

4.1.Insufficient Redirection URI Validation

Some authorization servers allow clients to register redirection URIpatterns instead of complete redirection URIs. The authorization serversthen match the redirection URI parameter value at the authorizationendpoint against the registered patterns at runtime. This approachallows clients to encode transaction state into additional redirectURI parameters or to register a single pattern for multipleredirection URIs.

This approach turned out to be more complex to implement and moreerror-prone to manage than exact redirection URI matching. Severalsuccessful attacks exploiting flaws in the pattern-matchingimplementation or concrete configurations have been observed in thewild (see, e.g.,[research.rub2]). Insufficient validation of the redirection URI effectively breaksclient identification or authentication (depending on grant and clienttype) and allows the attacker to obtain an authorization code oraccess token, either

  • by directly sending the user agent to a URI under the attacker'scontrol, or
  • by exposing the OAuth credentials to an attacker by utilizing anopen redirector at the client in conjunction with the way useragents handle URL fragments.

These attacks are shown in detail in the following subsections.

4.1.1.Redirect URI Validation Attacks on Authorization Code Grant

For a client using the grant typecode, an attack may work asfollows:

Assume the redirection URL patternhttps://*.somesite.example/* isregistered for the client with the client IDs6BhdRkqt3. Theintention is to allow any subdomain ofsomesite.example to be avalid redirection URI for the client, for example,https://app1.somesite.example/redirect. However, a naive implementation onthe authorization server might interpret the wildcard* as"any character" and not "any character valid for a domain name". Theauthorization server, therefore, might permithttps://attacker.example/.somesite.example as a redirection URI,althoughattacker.example is a different domain potentiallycontrolled by a malicious party.

The attack can then be conducted as follows:

To begin, the attacker needs to trick the user into opening a tamperedURL in their browser that launches a page under the attacker'scontrol, say,https://www.evil.example (see attackerA1 inSection 3).

This URL initiates the following authorization request with the clientID of a legitimate client to the authorization endpoint (line breaksfor display only):

GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=9ad67f13     &redirect_uri=https%3A%2F%2Fattacker.example%2F.somesite.example     HTTP/1.1Host: server.somesite.example

The authorization server validates the redirection URI and compares it tothe registered redirection URL patterns for the clients6BhdRkqt3.The authorization request is processed and presented to the user.

If the user does not see the redirection URI or does not recognize theattack, the code is issued and immediately sent to the attacker'sdomain. If an automatic approval of the authorization is enabled(which is not recommended for public clients according to[RFC6749]), the attack can be performed even without userinteraction.

If the attacker impersonates a public client, the attacker canexchange the code for tokens at the respective token endpoint.

This attack will not work as easily for confidential clients, sincethe code exchange requires authentication with the legitimate client'ssecret. However, the attacker can use the legitimate confidentialclient to redeem the code by performing an authorization codeinjection attack; seeSection 4.5.

It is important to note that redirection URI validation vulnerabilities can also exist if the authorizationserver handles wildcards properly. For example, assume that the clientregisters the redirection URL patternhttps://*.somesite.example/* andthe authorization server interprets this as "allow redirection URIspointing to any host residing in the domainsomesite.example". If anattacker manages to establish a host or subdomain insomesite.example, the attacker can impersonate the legitimate client. For example, thiscould be caused by a subdomain takeover attack[research.udel], where anoutdated CNAME record (say,external-service.somesite.example)points to an external DNS name that no longer exists (say,customer-abc.service.example) and can be taken over by an attacker(e.g., by registering ascustomer-abc with the external service).

4.1.2.Redirect URI Validation Attacks on Implicit Grant

The attack described above works for the implicit grant as well. Ifthe attacker is able to send the authorization response to an attacker-controlled URI, the attacker will directly get access to the fragment carrying theaccess token.

Additionally, implicit grants (and also other grants when usingresponse_mode=fragment as defined in[OAuth.Responses]) can be subject to a further kind ofattack. The attack utilizes the fact that user agents reattach fragments tothe destination URL of a redirect if the location header does notcontain a fragment (seeSection 17.11 of [RFC9110]). The attackdescribed here combines this behavior with the client as an openredirector (seeSection 4.11.1) in order to obtain access tokens. This allowscircumvention even of very narrow redirection URI patterns, but not of strict URLmatching.

Assume the registered URL pattern for clients6BhdRkqt3 ishttps://client.somesite.example/cb?*, i.e., any parameter is allowedfor redirects tohttps://client.somesite.example/cb. Unfortunately,the client exposes an open redirector. This endpoint supports aparameterredirect_to which takes a target URL and will send thebrowser to this URL using an HTTP Location header redirect 303.

The attack can now be conducted as follows:

To begin, as above, the attacker needs to trick the user into openinga tampered URL in their browser that launches a page under theattacker's control, say,https://www.evil.example.

Afterwards, the website initiates an authorization request that isvery similar to the one in the attack on the code flow. Different toabove, it utilizes the open redirector by encodingredirect_to=https://attacker.example into the parameters of theredirection URI, and it uses the response typetoken (line breaks for display only):

GET /authorize?response_type=token&state=9ad67f13    &client_id=s6BhdRkqt3    &redirect_uri=https%3A%2F%2Fclient.somesite.example     %2Fcb%26redirect_to%253Dhttps%253A%252F     %252Fattacker.example%252F HTTP/1.1Host: server.somesite.example

Then, since the redirection URI matches the registered pattern, theauthorization server permits the request and sends the resulting accesstoken in a 303 redirect (some response parameters omitted forreadability):

HTTP/1.1 303 See OtherLocation: https://client.somesite.example/cb?          redirect_to%3Dhttps%3A%2F%2Fattacker.example%2Fcb          #access_token=2YotnFZFEjr1zCsicMWpAA&...

At client.somesite.example, the request arrives at the open redirector. The endpoint willread the redirect parameter and will issue an HTTP 303 Location headerredirect to the URLhttps://attacker.example/.

HTTP/1.1 303 See OtherLocation: https://attacker.example/

Since the redirector at client.somesite.example does not include afragment in the Location header, the user agent will reattach theoriginal fragment#access_token=2YotnFZFEjr1zCsicMWpAA&... tothe URL and will navigate to the following URL:

https://attacker.example/#access_token=2YotnFZFEjr1z...

The attacker's page atattacker.example can then access thefragment and obtain the access token.

4.1.3.Countermeasures

The complexity of implementing and managing pattern matching correctly obviouslycauses security issues. This document therefore advises simplifying the requiredlogic and configuration by using exact redirection URI matching. This means theauthorization serverMUST ensure that the two URIs are equal; seeSection 6.2.1 of [RFC3986], Simple String Comparison, for details. The only exception isnative apps using alocalhost URI: In this case, the authorization serverMUST allow variableport numbers as described inSection 7.3 of [RFC8252].

Additional recommendations:

  • Web servers on which redirection URIs are hostedMUST NOT expose openredirectors (seeSection 4.11).
  • Browsers reattach URL fragments to Location redirection URLs onlyif the URL in the Location header does not already contain a fragment.Therefore, serversMAY prevent browsers from reattaching fragmentsto redirection URLs by attaching an arbitrary fragment identifier,for example#_, to URLs in Location headers.
  • ClientsSHOULD use the authorization code response type instead ofresponse types that cause access token issuance at the authorizationendpoint. This offers countermeasures against the reuse of leakedcredentials through the exchange process with the authorizationserver and against token replay through sender-constraining of the accesstokens.

If the origin and integrity of the authorization request containingthe redirection URI can be verified, for example, when using[RFC9101] or[RFC9126] with clientauthentication, the authorization serverMAY trust the redirection URIwithout further checks.

4.2.Credential Leakage via Referer Headers

The contents of the authorization request URI or the authorizationresponse URI can unintentionally be disclosed to attackers through theReferer HTTP header (seeSection 10.1.3 of [RFC9110]), by leaking from either the authorization server's or the client's website, respectively. Mostimportantly, authorization codes orstate values can be disclosed inthis way. Although specified otherwise inSection 10.1.3 of [RFC9110],the same may happen to access tokens conveyed in URI fragments due tobrowser implementation issues, as illustrated by a (now fixed) issue in the Chromium project[bug.chromium].

4.2.1.Leakage from the OAuth Client

Leakage from the OAuth client requires that the client, as a result ofa successful authorization request, renders a page that

  • contains links to other pages under the attacker's control and auser clicks on such a link, or
  • includes third-party content (advertisements in iframes, images,etc.), for example, if the page contains user-generated content(blog).

As soon as the browser navigates to the attacker's page or loads thethird-party content, the attacker receives the authorization responseURL and can extractcode orstate (and potentiallyaccess_token).

4.2.2.Leakage from the Authorization Server

In a similar way, an attacker can learnstate from the authorizationrequest if the authorization endpoint at the authorization servercontains links or third-party content as above.

4.2.3.Consequences

An attacker that learns a valid code or access token through aReferer header can perform the attacks as described in Sections4.1.1,4.5 and4.6. If the attacker learnsstate, the CSRFprotection achieved by usingstate is lost, resulting in CSRFattacks as described inSection 4.4.1.8 of [RFC6819].

4.2.4.Countermeasures

The page rendered as a result of the OAuth authorization response andthe authorization endpointSHOULD NOT include third-party resources orlinks to external sites.

The following measures further reduce the chances of a successful attack:

  • Suppress the Referer header by applying an appropriate ReferrerPolicy[W3C.webappsec-referrer-policy] to the document (either aspart of the "referrer" meta attribute or by setting aReferrer-Policy header). For example, the headerReferrer-Policy:no-referrer in the response completely suppresses the Refererheader in all requests originating from the resulting document.
  • Use authorization code instead of response types causing accesstoken issuance from the authorization endpoint.
  • Bind the authorization code to a confidential client or PKCEchallenge. In this case, the attacker lacks the secret to requestthe code exchange.
  • As described inSection 4.1.2 of [RFC6749], authorization codesMUST be invalidated by the authorization server after their first use at the tokenendpoint. For example, if an authorization server invalidated the code after thelegitimate client redeemed it, the attacker would fail to exchangethis code later.

    This does not mitigate the attack if the attacker manages toexchange the code for a token before the legitimate client doesso. Therefore,[RFC6749] further recommends that, when anattempt is made to redeem a code twice, the authorization serverSHOULD revoke alltokens issued previously based on that code.

  • Thestate valueSHOULD be invalidated by the client after itsfirst use at the redirection endpoint. If this is implemented, andan attacker receives a token through the Referer header from theclient's website, thestate was already used, invalidated bythe client and cannot be used again by the attacker. (This doesnot help if thestate leaks from theauthorization server's website, since then thestatehas not been used at the redirection endpoint at the client yet.)

  • Use the form post response mode instead of a redirect for theauthorization response (see[OAuth.Post]).

4.3.Credential Leakage via Browser History

Authorization codes and access tokens can end up in the browser'shistory of visited URLs, enabling the attacks described in thefollowing.

4.3.1.Authorization Code in Browser History

When a browser navigates toclient.example/redirection_endpoint?code=abcd as a result of aredirect from a provider's authorization endpoint, the URL includingthe authorization code may end up in the browser's history. Anattacker with access to the device could obtain the code and try toreplay it.

Countermeasures:

4.3.2.Access Token in Browser History

An access token may end up in the browser history if a client or a website that already has a token deliberately navigates to a page likeprovider.com/get_user_profile?access_token=abcdef.[RFC6750]discourages this practice and advises transferring tokens via a header,but in practice websites often pass access tokens in queryparameters.

In the case of implicit grant, a URL likeclient.example/redirection_endpoint#access_token=abcdef may also endup in the browser history as a result of a redirect from a provider'sauthorization endpoint.

Countermeasures:

  • ClientsMUST NOT pass access tokens in a URI query parameter inthe way described inSection 2.3 of [RFC6750]. The authorizationcode grant or alternative OAuth response modes like the form postresponse mode[OAuth.Post] can be used tothis end.

4.4.Mix-Up Attacks

Mix-up attacks can occur in scenarios where an OAuth client interacts withtwo or more authorization servers and at least one authorizationserver is under the control of the attacker. This can be the case,for example, if the attacker uses dynamic registration to register theclient at their own authorization server or if an authorization serverbecomes compromised.

The goal of the attack is to obtain an authorization code or an accesstoken for an uncompromised authorization server. This is achieved bytricking the client into sending those credentials to the compromisedauthorization server (the attacker) instead of using them at therespective endpoint of the uncompromised authorization/resourceserver.

4.4.1.Attack Description

The description here follows[arXiv.1601.01229], withvariants of the attack outlined below.

Preconditions: For this variant of the attack to work, it is assumed that

  • the implicit or authorization code grant is used with multiple authorization serversof which one is considered "honest" (H-AS) and one is operated bythe attacker (A-AS), and
  • the client stores the authorization server chosen by the user in a session bound tothe user's browser and uses the same redirection URI foreach authorization server.

In the following, it is further assumed that the client is registered with H-AS (URI:https://honest.as.example, client ID:7ZGZldHQ) and with A-AS (URI:https://attacker.example, client ID:666RVZJTA). URLs shown in the followingexample are shortened for presentation to include only parameters relevant to theattack.

Attack on the authorization code grant:

  1. The user selects to start the grant using A-AS (e.g., by clicking on a button on theclient's website).
  2. The client stores in the user's session that the user selected"A-AS" and redirects the user to A-AS's authorization endpointwith a Location header containing the URLhttps://attacker.example/authorize?response_type=code&client_id=666RVZJTA.
  3. When the user's browser navigates to the attacker's authorization endpoint,the attacker immediately redirects the browser to the authorization endpointof H-AS. In the authorization request, the attacker replaces the client IDof the client at A-AS with the client's ID at H-AS. Therefore, the browserreceives a redirection (303 See Other) with a Location header pointing tohttps://honest.as.example/authorize?response_type=code&client_id=7ZGZldHQ
  4. The user authorizes the client to access their resources at H-AS. (Note that avigilant user might at this point detect that they intended to use A-ASinstead of H-AS. The first attack variant listed does not have this limitation.) H-ASissues a code and sends it (via the browser) back to the client.

  5. Since the client still assumes that the code was issued by A-AS,it will try to redeem the code at A-AS's token endpoint.

  6. The attacker therefore obtains code and can either exchange thecode for an access token (for public clients) or perform anauthorization code injection attack as described inSection 4.5.

Variants:

  • Mix-Up with Interception: This variant works only if the attacker canintercept and manipulate the first request/response pair from a user'sbrowser to the client (in which the user selects a certain authorization server and is thenredirected by the client to that authorization server), as inAttacker (A2) (seeSection 3). This capabilitycan, for example, be the result of an attacker-in-the-middle attack on the user'sconnection to the client. In the attack, the user starts the flow with H-AS.The attacker intercepts this request and changes the user's selection toA-AS. The rest of the attack proceeds as inStep 2 and following above.
  • Implicit Grant: In the implicit grant, the attacker receives an accesstoken instead of the code inStep 4. The attacker's authorization server receives the access tokenwhen the client makes either a request to the A-AS userinfo endpoint (defined in[OpenID.Core]) or a request to the attacker's resource server (since the client believes it has completed the flow with A-AS).
  • Per-AS Redirect URIs: If clients use different redirection URIs fordifferent authorization servers, clients do not store the selected authorization server in the user's session, and authorization serversdo not check the redirection URIs properly, attackers can mount an attackcalled "Cross Social-Network Request Forgery". These attacks have beenobserved in practice. Refer to[research.jcs_14] for details.
  • OpenID Connect: Some variants can be used to attack OpenIDConnect. In these attacks, the attacker misuses features of the OpenIDConnect Discovery[OpenID.Discovery] mechanism or replays access tokens or IDTokens to conduct a mix-up attack. The attacks are described in detail in Appendix A of[arXiv.1704.08539] and Section 6 of[arXiv.1508.04324v2] ("Malicious Endpoints Attacks").

4.4.2.Countermeasures

When an OAuth client can only interact with one authorization server, a mix-updefense is not required. In scenarios where an OAuth client interacts with twoor more authorization servers, however, clientsMUST prevent mix-up attacks. Twodifferent methods are discussed below.

For both defenses, clientsMUST store, for each authorization request, theissuer they sent the authorization request to and bind this information to theuser agent. The issuer serves, via the associated metadata, as an abstractidentifier for the combination of the authorization endpoint and token endpointthat are to be used in the flow. If an issuer identifier is not available (forexample, if neither OAuth Authorization Server Metadata[RFC8414] nor OpenID Connect Discovery[OpenID.Discovery] isused), a different unique identifier for this tuple or the tuple itself can beused instead. For brevity of presentation, such a deployment-specific identifierwill be subsumed under the issuer (or issuer identifier) in the following.

It is important to note that just storing the authorization server URL is not sufficient to identifymix-up attacks. An attacker might declare an uncompromised authorization server's authorization endpoint URL as"their" authorization server URL, but declare a token endpoint under their own control.

4.4.2.1.Mix-Up Defense via Issuer Identification

This defense requires that the authorization server sends its issuer identifierin the authorization response to the client. When receiving the authorizationresponse, the clientMUST compare the received issuer identifier to the storedissuer identifier. If there is a mismatch, the clientMUST abort theinteraction.

There are different ways this issuer identifier can be transported to the client:

  • The issuer information can be transported, forexample, via a separate response parameteriss, defined in[RFC9207].
  • When OpenID Connect is used and an ID Token is returned in the authorizationresponse, the client can evaluate theiss claim in the ID Token.

In both cases, theiss valueMUST be evaluated according to[RFC9207].

While this defense may require deploying new OAuth features to transport theissuer information, it is a robust and relatively simple defense against mix-up.

4.4.2.2.Mix-Up Defense via Distinct Redirect URIs

For this defense, clientsMUST use a distinct redirection URI for each issuerthey interact with.

ClientsMUST check that the authorization response was received from the correctissuer by comparing the distinct redirection URI for the issuer to the URI wherethe authorization response was received on. If there is a mismatch, the clientMUST abort the flow.

While this defense builds upon existing OAuth functionality, it cannot be usedin scenarios where clients only register once for the use of many differentissuers (as in some open banking schemes) and due to the tight integration withthe client registration, it is harder to deploy automatically.

Furthermore, an attacker might be able to circumvent the protection offered bythis defense by registering a new client with the "honest" authorization server using the redirectURI that the client assigned to the attacker's authorization server. The attacker could then runthe attack as described above, replacing theclient ID with the client ID of their newly created client.

This defenseSHOULD therefore only be used if other options are not available.

4.5.Authorization Code Injection

An attacker who has gained access to an authorization code contained in anauthorization response (seeAttacker (A3) inSection 3) can try to redeem theauthorization code for an access token or otherwise make use of theauthorization code.

In the case that the authorization code was created for a public client, theattacker can send the authorization code to the token endpoint of theauthorization server and thereby get an access token. This attack was describedinSection 4.4.1.1 of [RFC6819].

For confidential clients, or in some special situations, the attacker canexecute an authorization code injection attack, as described in the following.

In an authorization code injection attack, the attacker attempts to inject astolen authorization code into the attacker's own session with the client. Theaim is to associate the attacker's session at the client with the victim'sresources or identity, thereby giving the attacker at least limited access tothe victim's resources.

Besides circumventing the client authentication of confidential clients, otheruse cases for this attack include:

  • The attacker wants to access certain functions in this particularclient. As an example, the attacker wants to impersonate theirvictim in a certain app or on a certain website.
  • The authorization or resource servers are limited to certainnetworks that the attacker is unable to access directly.

Except in these special cases, authorization code injection is usually notinteresting when the code is created for a public client, as sending the codeto the token endpoint is a simpler and more powerful attack, as described above.

4.5.1.Attack Description

The authorization code injection attack works as follows:

  1. The attacker obtains an authorization code (seeAttacker (A3) inSection 3). For the restof the attack, only the capabilities of a web attacker(A1) are required.
  2. From the attacker's device, the attacker starts a regular OAuth authorizationprocess with the legitimate client.
  3. In the response of the authorization server to the legitimate client, theattacker replaces the newly created authorization code with the stolenauthorization code. Since this response is passing through the attacker'sdevice, the attacker can use any tool that can intercept and manipulate theauthorization response to this end. The attacker does not need to controlthe network.
  4. The legitimate client sends the code to the authorization server's tokenendpoint, along with theredirect_uri and the client's client ID andclient secret (or other means of client authentication).
  5. The authorization server checks the client secret, whether thecode was issued to the particular client, and whether the actualredirection URI matches theredirect_uri parameter (see[RFC6749]).
  6. All checks succeed and the authorization server issues access andother tokens to the client. The attacker has now associated theirsession with the legitimate client with the victim's resourcesand/or identity.

4.5.2.Discussion

Obviously, the check-in step (Step 5) will fail if the code was issued toanother client ID, e.g., a client set up by the attacker. The checkwill also fail if the authorization code was already redeemed by thelegitimate user and was one-time use only.

An attempt to inject a code obtained via a manipulated redirection URIshould also be detected if the authorization server stored thecomplete redirection URI used in the authorization request and comparesit with theredirect_uri parameter.

Section 4.1.3 of [RFC6749] requires the authorization server to

ensure that the "redirect_uri" parameter is present if the "redirect_uri" parameter was included in the initial authorization request as described in Section4.1.1, and if included ensure that their values are identical.

In the attack scenario described inSection 4.5.1, the legitimateclient would use the correct redirection URI it always uses forauthorization requests. But this URI would not match the tamperedredirection URI used by the attacker (otherwise, the redirect would notland at the attacker's page). So, the authorization server would detectthe attack and refuse to exchange the code.

This check could also detect attempts to inject an authorizationcode that had been obtained from another instance of the same clienton another device if certain conditions are fulfilled:

  • the redirection URI itself contains a nonce or another kindof one-time use, secret data and
  • the client has bound this data to this particular instance of theclient.

But, this approach conflicts with the idea of enforcing exact redirectURI matching at the authorization endpoint. Moreover, it has beenobserved that providers very often ignore theredirect_uri checkrequirement at this stage, maybe because it doesn't seem to besecurity-critical from reading the specification.

Other providers just pattern match theredirect_uri parameteragainst the registered redirection URI pattern. This saves theauthorization server from storing the link between the actual redirectURI and the respective authorization code for every transaction. However,this kind of check obviously does not fulfill the intent of thespecification, since the tampered redirection URI is not considered. So,any attempt to inject an authorization code obtained using theclient_id of a legitimate client or by utilizing the legitimateclient on another device will not be detected in the respectivedeployments.

It is also assumed that the requirements defined inSection 4.1.3 of [RFC6749] increase client implementation complexity as clientsneed to store or reconstruct the correct redirection URI for the callto the token endpoint.

Asymmetric methods for client authentication do not stop this attack, as thelegitimate client authenticates at the token endpoint.

This document therefore recommends instead binding every authorizationcode to a certain client instance on a certain device (or in a certainuser agent) in the context of a certain transaction using one of themechanisms described next.

4.5.3.Countermeasures

There are two good technical solutions to binding authorization codes to clientinstances, as follows.

4.5.3.1.PKCE

The PKCE mechanism specified in[RFC7636] can be used as a countermeasure(even though it was originally designed to secure native apps). When theattacker attempts to inject an authorization code, the check of thecode_verifier fails: the client uses its correct verifier, but the code isassociated with acode_challenge that does not match this verifier.

PKCE not only protects against the authorization code injection attack butalso protects authorization codes created for public clients: PKCE ensures thatan attacker cannot redeem a stolen authorization code at the token endpoint ofthe authorization server without knowledge of thecode_verifier.

4.5.3.2.Nonce

OpenID Connect's existingnonce parameter can protect against authorizationcode injection attacks. Thenonce value is one-time use and is created by theclient. The client is supposed to bind it to the user agent session and send itwith the initial request to the OpenID Provider (OP). The OP puts the receivednonce value into the ID Token that is issuedas part of the code exchange at the token endpoint. If an attacker injects anauthorization code in the authorization response, the nonce value in the clientsession and thenonce value in the ID Token received from the token endpoint will not match, and the attack isdetected. The assumption is that an attacker cannot get hold of the user agentstate on the victim's device (from which the attacker has stolen the respective authorizationcode).

It is important to note that this countermeasure only works if the clientproperly checks thenonce parameter in the ID Token obtained from the token endpoint and does not use anyissued token until this check has succeeded. More precisely, a client protectingitself against code injection using thenonce parameter

  1. MUST validate thenonce in the ID Token obtained from the token endpoint, even if another ID Token was obtained from the authorization response (e.g.,response_type=code+id_token), and
  2. MUST ensure that, unless and until that check succeeds, all tokens (ID Tokens and the access token) are disregarded and not used for any other purpose.

It is important to note thatnonce does not protect authorization codes ofpublic clients, as an attacker does not need to execute an authorization codeinjection attack. Instead, an attacker can directly call the token endpoint withthe stolen authorization code.

4.5.3.3.Other Solutions

Other solutions like bindingstate to the code, sender-constraining the codeusing cryptographic means, or per-instance client credentials areconceivable, but lack support and bring new security requirements.

PKCE is the most obvious solution for OAuth clients, as it is availableat the time of writing, whilenonce isappropriate for OpenID Connect clients.

4.5.4.Limitations

An attacker can circumvent the countermeasures described above if theycan modify thenonce orcode_challenge values that are used in thevictim's authorization request. The attacker can modify these valuesto be the same ones as those chosen by the client in their own sessioninStep 2 of the attack above. (This requires that the victim'ssession with the client begins after the attacker started their sessionwith the client.) If the attacker is then able to capture theauthorization code from the victim, the attacker will be able toinject the stolen code inStep 3 even if PKCE ornonce are used.

This attack is complex and requires a close interaction between theattacker and the victim's session. Nonetheless, measures to preventattackers from reading the contents of the authorization responsestill need to be taken, as described in Sections4.1,4.2,4.3,4.4, and4.11.

4.6.Access Token Injection

In an access token injection attack, the attacker attempts to inject astolen access token into a legitimate client (that is not under theattacker's control). This will typically happen if the attacker wantsto utilize a leaked access token to impersonate a user in a certainclient.

To conduct the attack, the attacker starts an OAuth flow with theclient using the implicit grant and modifies the authorizationresponse by replacing the access token issued by the authorizationserver or directly making up an authorization server response includingthe leaked access token. Since the response includes thestate valuegenerated by the client for this particular transaction, the clientdoes not treat the response as a CSRF attack and uses the access tokeninjected by the attacker.

4.6.1.Countermeasures

There is no way to detect such an injection attack in pure-OAuthflows since the token is issued without any binding to thetransaction or the particular user agent.

In OpenID Connect, the attack can be mitigated, as the authorization responseadditionally contains an ID Token containing theat_hash claim. The attackertherefore needs to replace both the access token as well as the ID Token in theresponse. The attacker cannot forge the ID Token, as it is signed or encryptedwith authentication. The attacker also cannot inject a leaked ID Token matchingthe stolen access token, as thenonce claim in the leaked ID Token willcontain (with a very high probability) a different value than the one expectedin the authorization response.

Note that further protection, like sender-constrained access tokens, is stillrequired to prevent attackers from using the access token at the resourceendpoint directly.

The recommendations inSection 2.1.2 follow from this.

4.7.Cross-Site Request Forgery

An attacker might attempt to inject a request to the redirection URI ofthe legitimate client on the victim's device, e.g., to cause theclient to access resources under the attacker's control. This is avariant of an attack known as Cross-Site Request Forgery (CSRF).

4.7.1.Countermeasures

The long-established countermeasure is that clients pass a random value, alsoknown as a CSRF Token, in thestate parameter that links the request tothe redirection URI to the user agent session as described. Thiscountermeasure is described in detail inSection 5.3.5 of [RFC6819]. Thesame protection is provided by PKCE or the OpenID Connectnonce value.

When using PKCE instead ofstate ornonce for CSRF protection, it isimportant to note that:

  • ClientsMUST ensure that the authorization server supports PKCE before using PKCE forCSRF protection. If an authorization server does not support PKCE,state ornonceMUST be used for CSRF protection.

  • Ifstate is used for carrying application state, and the integrity ofits contents is a concern, clientsMUST protectstate againsttampering and swapping. This can be achieved by binding thecontents of state to the browser session and/or by signing/encryptingstate values. One example of this is discussed in the expired Internet-Draft[JWT-ENCODED-STATE].

The authorization server thereforeMUST provide a way to detect their support for PKCE. Using Authorization Server Metadata according to[RFC8414] isRECOMMENDED, but authorization serversMAY instead provide adeployment-specific way to ensure or determine PKCE support.

PKCE provides robust protection against CSRF attacks even in the presence of an attacker thatcan read the authorization response (seeAttacker (A3) inSection 3). Whenstate is used or an ID Token is returned in the authorization response (e.g.,response_type=code+id_token), the attacker either learns thestate value andcan replay it into the forged authorization response, or can extract thenoncefrom the ID Token and use it in a new request to the authorization server tomint an ID Token with the samenonce. The new ID Token can then be used forthe CSRF attack.

4.8.PKCE Downgrade Attack

An authorization server that supports PKCE but does not make its use mandatory forall flows can be susceptible to a PKCE downgrade attack.

The first prerequisite for this attack is that there is an attacker-controllableflag in the authorization request that enables or disables PKCE for theparticular flow. The presence or absence of thecode_challenge parameter lendsitself for this purpose, i.e., the authorization server enables and enforces PKCE if thisparameter is present in the authorization request, but it does not enforce PKCE ifthe parameter is missing.

The second prerequisite for this attack is that the client is not usingstateat all (e.g., because the client relies on PKCE for CSRF prevention) or that theclient is not checkingstate correctly.

Roughly speaking, this attack is a variant of a CSRF attack. The attackerachieves the same goal as in the attack described inSection 4.7: The attacker injects anauthorization code (and with that, an access token) that is bound to the attacker'sresources into a session between their victim and the client.

4.8.1.Attack Description

  1. The user has started an OAuth session using some client at an authorization server. In theauthorization request, the client has set the parametercode_challenge=hash(abc) as the PKCE code challenge (with the hash function and parameter encoding as defined in[RFC7636]). The client is nowwaiting to receive the authorization response from the user's browser.
  2. To conduct the attack, the attacker uses their own device to start anauthorization flow with the targeted client. The client now uses anotherPKCE code challenge, say,code_challenge=hash(xyz), in the authorizationrequest. The attacker intercepts the request and removes the entirecode_challenge parameter from the request. Since this step is performed onthe attacker's device, the attacker has full access to the request contents,for example, using browser debug tools.
  3. If the authorization server allows for flows without PKCE, it will create acode that is not bound to any PKCE code challenge.
  4. The attacker now redirects the user's browser to an authorization responseURL that contains the code for the attacker's session with the authorization server.
  5. The user's browser sends the authorization code to the client, which willnow try to redeem the code for an access token at the authorization server. The client willsendcode_verifier=abc as the PKCE code verifier in the token request.
  6. Since the authorization server sees that this code is not bound to any PKCEcode challenge, it will not check the presence or contents of thecode_verifier parameter. It will issue an access token (which belongs to theattacker's resource) to the client under the user's control.

4.8.2.Countermeasures

Usingstate properly would prevent this attack. However, practice has shownthat many OAuth clients do not use or checkstate properly.

Therefore, authorization serversMUST mitigate this attack.

Note that from the view of the authorization server, in the attack described above, acode_verifier parameter is received at the token endpoint although nocode_challenge parameter was present in the authorization request for theOAuth flow in which the authorization code was issued.

This fact can be used to mitigate this attack.[RFC7636] already mandates that

  • an authorization server that supports PKCEMUST check whether a code challenge is contained inthe authorization request and bind this information to the code that isissued; and
  • when a code arrives at the token endpoint, and there was acode_challengein the authorization request for which this code was issued, there must be avalidcode_verifier in the token request.

Beyond this, to prevent PKCE downgrade attacks, the authorization serverMUST ensure thatif there was nocode_challenge in the authorization request, a request tothe token endpoint containing acode_verifier is rejected.

Authorization servers that mandate the use of PKCE (in general or for particular clients)implicitly implement this security measure.

4.9.Access Token Leakage at the Resource Server

Access tokens can leak from a resource server under certaincircumstances.

4.9.1.Access Token Phishing by Counterfeit Resource Server

An attacker may set up their own resource server and trick a client intosending access tokens to it that are valid for other resource servers(see Attackers(A1) and(A5) inSection 3). If the client sends a valid access token tothis counterfeit resource server, the attacker in turn may use thattoken to access other services on behalf of the resource owner.

This attack assumes the client is not bound to one specific resourceserver (and its URL) at development time, but client instances areprovided with the resource server URL at runtime. This kind of latebinding is typical in situations where the client uses a serviceimplementing a standardized API (e.g., for email, calendaring, eHealth,or open banking) and where the client is configured by a user oradministrator.

4.9.2.Compromised Resource Server

An attacker may compromise a resource server to gain access to theresources of the respective deployment. Such a compromise may rangefrom partial access to the system, e.g., its log files, to fullcontrol over the respective server, in which case all controls can becircumvented and all resources can beaccessed. The attacker would also be able to obtain other accesstokens held on the compromised system that would potentially be validto access other resource servers.

Preventing server breaches by hardening and monitoring server systemsis considered a standard operational procedure and, therefore, out ofthe scope of this document.Section 4.9 focuses on the impact ofOAuth-related breaches and the replaying of captured access tokens.

4.9.3.Countermeasures

The following measures should be taken into account by implementers inorder to cope with access token replay by malicious actors:

  • Sender-constrained access tokens, as described inSection 4.10.1,SHOULD be used to prevent the attacker from replaying the accesstokens on other resource servers. If an attacker has only partialaccess to the compromised system, like a read-only access to webserver logs, sender-constrained access tokens may also preventreplay on the compromised system.
  • Audience restriction as described inSection 4.10.2SHOULD beused to prevent replay of captured access tokens on other resourceservers.
  • The resource serverMUST treat access tokens like other sensitive secretsand not store or transfer them in plaintext.

The first and second recommendations also apply to other scenarioswhere access tokens leak (seeAttacker (A5) inSection 3).

4.10.Misuse of Stolen Access Tokens

Access tokens can be stolen by an attacker in various ways, for example,via the attacks described in Sections4.1,4.2,4.3,4.4, and4.9. Some of these attacks can be mitigated byspecific security measures, as described in the respective sections.However, in some cases, these measures are not sufficient or are notimplemented correctly. Authorization servers thereforeSHOULD ensure thataccess tokens are sender-constrained and audience-restricted as describedin the following. Architecture and performance reasons mayprevent the use of these measures in some deployments.

4.10.1.Sender-Constrained Access Tokens

As the name suggests, sender-constrained access tokens scope theapplicability of an access token to a certain sender. This sender isobliged to demonstrate knowledge of a certain secret as a prerequisitefor the acceptance of that token at a resource server.

A typical flow looks like this:

  1. The authorization server associates data with the access tokenthat binds this particular token to a certain client. The bindingcan utilize the client's identity, but in most cases, the authorization server utilizeskey material (or data derived from the key material) known to theclient.
  2. This key material must be distributed somehow. Either the keymaterial already exists before the authorization server creates the binding or theauthorization server creates ephemeral keys. The way preexisting key material isdistributed varies among the different approaches. For example,X.509 certificates can be used, in which case the distributionhappens explicitly during the enrollment process. Or, the keymaterial is created and distributed at the TLS layer, in whichcase it might automatically happen during the setup of a TLSconnection.
  3. The resource server must implement the actual proof-of-possession check. Thisis typically done on the application level, often tied to specificmaterial provided by the transport layer (e.g., TLS). The resource server must alsoensure that a replay of the proof of possession is not possible.

Two methods for sender-constrained access tokens using proof of possession havebeen defined by the OAuth working group and are in use in practice:

  • "OAuth 2.0 Mutual-TLS Client Authentication and Certificate-BoundAccess Tokens"[RFC8705]: The approach specified in this)document allows the use of mutual TLS for both clientauthentication and sender-constrained access tokens. For thepurpose of sender-constrained access tokens, the client isidentified towards the resource server by the fingerprint of itspublic key. During the processing of an access token request, theauthorization server obtains the client's public key from the TLSstack and associates its fingerprint with the respective accesstokens. The resource server in the same way obtains the public keyfrom the TLS stack and compares its fingerprint with thefingerprint associated with the access token.
  • "OAuth 2.0 Demonstrating Proof of Possession (DPoP)"[RFC9449]:DPoP outlines anapplication-level mechanism for sender-constraining access and refreshtokens. It usesproof-of-possession based on a public/private key pair andapplication-level signing. DPoP can be used with public clientsand, in the case of confidential clients, can be combined with anyclient authentication method.

Note that the security of sender-constrained tokens is undermined whenan attacker gets access to the token and the key material. This is, inparticular, the case for corrupted client software and cross-sitescripting attacks (when the client is running in the browser). If thekey material is protected in a hardware or software security module oronly indirectly accessible (like in a TLS stack), sender-constrainedtokens at least protect against the use of the token when the client isoffline, i.e., when the security module or interface is not availableto the attacker. This applies to access tokens as well as to refreshtokens (seeSection 4.14).

4.10.2.Audience-Restricted Access Tokens

Audience restriction essentially restricts access tokens to aparticular resource server. The authorization server associates theaccess token with the particular resource server, and the resourceserver is then supposed to verify the intended audience. If the access token failsthe intended audience validation, the resource server refuses toserve the respective request.

In general, audience restriction limits the impact of token leakage.In the case of a counterfeit resource server, it may (as describedbelow) also prevent abuse of the phished access token at thelegitimate resource server.

The audience can be expressed using logical names orphysical addresses (like URLs). To prevent phishing, it isnecessary to use the actual URL the client will send requests to. Inthe phishing case, this URL will point to the counterfeit resourceserver. If the attacker tries to use the access token at thelegitimate resource server (which has a different URL), the resourceserver will detect the mismatch (wrong audience) and refuse to servethe request.

In deployments where the authorization server knows the URLs of allresource servers, the authorization server may just refuse to issueaccess tokens for unknown resource server URLs.

For this to work, the client needs to tell the authorization server the intendedresource server. The mechanism in[RFC8707] can be used for this or theinformation can be encoded in the scope value (Section 3.3 of [RFC6749]).

Instead of the URL, it is also possible to utilize the fingerprint ofthe resource server's X.509 certificate as the audience value. Thisvariant would also allow detection of an attempt to spoof the legitimateresource server's URL by using a valid TLS certificate obtained from adifferent CA. It might also be considered a privacy benefit to hidethe resource server URL from the authorization server.

Audience restriction may seem easier to use since it does not requireany cryptography on the client side. Still, since every access token isbound to a specific resource server, the client also needs to obtain asingle resource server-specific access token when accessing several resourceservers. (Resource indicators, as specified in[RFC8707], can help to achieve this.)[TOKEN-BINDING] had the same property since differenttoken-binding IDs must be associated with the access token. Usingmutual TLS for OAuth 2.0[RFC8705], on the other hand, allows a client to use theaccess token at multiple resource servers.

It should be noted that audience restrictions -- or, generally speaking, anindication by the client to the authorization server where it wants touse the access token -- have additional benefits beyond the scope oftoken leakage prevention. They allow the authorization server to createa different access token whose format and content are specifically mintedfor the respective server. This has huge functional and privacyadvantages in deployments using structured access tokens.

4.10.3.Discussion: Preventing Leakage via Metadata

An authorization server could provide the client with additionalinformation about the locations where it is safe to use its accesstokens. This approach, and why it is not recommended, is discussed inthe following.

In the simplest form, this would require the authorization server to publish a list ofits known resource servers, illustrated in the following example usinga non-standard Authorization Server Metadata parameterresource_servers:

HTTP/1.1 200 OKContent-Type: application/json{  "issuer":"https://server.somesite.example",  "authorization_endpoint":    "https://server.somesite.example/authorize",  "resource_servers":[    "email.somesite.example",    "storage.somesite.example",    "video.somesite.example"  ]  ...}

The authorization server could also return the URL(s) an access token is good for in thetoken response, illustrated by the example and non-standard returnparameteraccess_token_resource_server:

HTTP/1.1 200 OKContent-Type: application/json;charset=UTF-8Cache-Control: no-storePragma: no-cache{  "access_token":"2YotnFZFEjr1zCsicMWpAA",  "access_token_resource_server":    "https://hostedresource.somesite.example/path1",...}

This mitigation strategy would rely on the client to enforce thesecurity policy and to only send access tokens to legitimatedestinations. Results of OAuth-related security research (see, forexample,[research.ubc] and[research.cmu]) indicate alarge portion of client implementations do not or fail to properlyimplement security controls, likestate checks. So, relying onclients to prevent access token phishing is likely to fail as well. Moreover, given the ratio of clients to authorization and resource servers, it is considered the more viable approach to move as much as possible security-related logic to those servers.Clearly, the clienthas to contribute to the overall security. However, there are alternativecountermeasures, as described in Sections4.10.1 and4.10.2, that provide abetter balance between the involved parties.

4.11.Open Redirection

The following attacks can occur when an authorization server or client has an open redirector. Such endpoints are sometimes implemented,for example, to show a message before a user is then redirected to an externalwebsite, or to redirect users back to a URL they were intending to visit beforebeing interrupted, e.g., by a login prompt.

4.11.1.Client as Open Redirector

ClientsMUST NOT expose open redirectors. Attackers may use openredirectors to produce URLs pointing to the client and utilize them toexfiltrate authorization codes and access tokens, as described inSection 4.1.2. Another abuse case is to produce URLs thatappear to point to the client. This might trick users into trusting the URLand following it in their browser. This can be abused for phishing.

In order to prevent open redirection, clients should only redirect ifthe target URLs are allowed or if the origin and integrity of arequest can be authenticated. Countermeasures against open redirectionare described by OWASP[owasp.redir].

4.11.2.Authorization Server as Open Redirector

Just as with clients, attackers could try to utilize a user's trust inthe authorization server (and its URL in particular) for performingphishing attacks. OAuth authorization servers regularly redirect usersto other websites (the clients), but they must do so safely.

Section 4.1.2.1 of [RFC6749] already prevents open redirects bystating that the authorization serverMUST NOT automatically redirect the user agent in caseof an invalid combination ofclient_id andredirect_uri.

However, an attacker could also utilize a correctly registeredredirection URI to perform phishing attacks. The attacker could, forexample, register a client via dynamic client registration[RFC7591]and execute one of the following attacks:

  1. Intentionally send an erroneous authorization request, e.g., by using aninvalid scope value, thus instructing the authorization server to redirectthe user agent to its phishing site.
  2. Intentionally send a valid authorization request withclient_id andredirect_uri controlled by the attacker. After the user authenticates, theauthorization server prompts the user to provide consent to the request. Ifthe user notices an issue with the request and declines the request, theauthorization server still redirects the user agent to the phishing site. Inthis case, the user agent will be redirected to the phishing site regardlessof the action taken by the user.
  3. Intentionally send a valid silent authentication request (prompt=none)withclient_id andredirect_uri controlled by the attacker. In thiscase, the authorization server will automatically redirect the user agent tothe phishing site.

The authorization serverMUST take precautions to prevent these threats. The authorization serverMUST alwaysauthenticate the user first and, with the exception of the silent authenticationuse case, prompt the user for credentials when needed, before redirecting theuser. Based on its risk assessment, the authorization server needs to decide whether or not it can trustthe redirection URI. It could take into account URI analytics doneinternally or through some external service to evaluate the credibility andtrustworthiness of content behind the URI, and the source of the redirection URI andother client data.

The authorization serverSHOULD only automatically redirect the user agent if it trusts theredirection URI. If the URI is not trusted, the authorization serverMAY inform the user and rely onthe user to make the correct decision.

4.12.307 Redirect

At the authorization endpoint, a typical protocol flow is that the authorization serverprompts the user to enter their credentials in a form that is thensubmitted (using the HTTP POST method) back to the authorizationserver. The authorization server checks the credentials and, if successful, redirectsthe user agent to the client's redirection endpoint.

In[RFC6749], the HTTP status code 302 (Found) is used for this purpose, but"any other method available via the user-agent to accomplish thisredirection is allowed". When the status code 307 is used forredirection instead, the user agent will send the user's credentials viaHTTP POST to the client.

This discloses the sensitive credentials to the client. If the clientis malicious, it can use the credentials to impersonate the userat the authorization server.

The behavior might be unexpected for developers but is defined inSection 15.4.8 of [RFC9110]. This status code (307) does not require the useragent to rewrite the POST request to a GET request and thereby dropthe form data in the POST request body.

In the HTTP standard[RFC9110], only the status code 303unambiguously enforces rewriting the HTTP POST request to an HTTP GETrequest. For all other status codes, including the popular 302, useragents can opt not to rewrite POST to GET requests, therebycausing the user's credentials to be revealed to the client. (In practice, however, mostuser agents will only show this behavior for 307 redirects.)

Authorization servers that redirect a request that potentially contains the user's credentialsthereforeMUST NOT use the HTTP 307 status code for redirection. If anHTTP redirection (and not, for example, JavaScript) is used for such arequest, the authorization serverSHOULD use HTTP status code 303 (See Other).

4.13.TLS Terminating Reverse Proxies

A common deployment architecture for HTTP applications is to hide theapplication server behind a reverse proxy that terminates the TLSconnection and dispatches the incoming requests to the respectiveapplication server nodes.

This section highlights some attack angles of this deploymentarchitecture with relevance to OAuth and gives recommendations forsecurity controls.

In some situations, the reverse proxy needs to pass security-relateddata to the upstream application servers for further processing.Examples include the IP address of the request originator, token-bindingIDs, and authenticated TLS client certificates. This data is usuallypassed in HTTP headers added to the upstream request. While the headersare often custom, application-specific headers, standardized headerfields for client certificates and client certificate chains are definedin[RFC9440].

If the reverse proxy passes through any header sent from theoutside, an attacker could try to directly send the faked headervalues through the proxy to the application server in order tocircumvent security controls that way. For example, it is standardpractice of reverse proxies to acceptX-Forwarded-For headers and justadd the origin of the inbound request (making it a list). Depending onthe logic performed in the application server, the attacker couldsimply add an allowed IP address to the header and render the protection useless.

A reverse proxyMUST therefore sanitize any inbound requests to ensurethe authenticity and integrity of all header values relevant for thesecurity of the application servers.

If an attacker were able to get access to the internal network betweenthe proxy and application server, the attacker could also try tocircumvent security controls in place. Therefore, it is essential toensure the authenticity of the communicating entities. Furthermore,the communication link between the reverse proxy and application serverMUST be protected against eavesdropping, injection, and replay ofmessages.

4.14.Refresh Token Protection

Refresh tokens are a convenient and user-friendly way to obtain new accesstokens. They also addto the security of OAuth, since they allow the authorization server to issueaccess tokens with a short lifetime and reduced scope, thus reducing thepotential impact of access token leakage.

4.14.1.Discussion

Refresh tokens are an attractive target for attackers because they represent the full scope of access granted to a certain client, and they are not further constrained to a specific resource. If an attacker is able to exfiltrate and successfully replay arefresh token, the attacker will be able to mint access tokens and usethem to access resource servers on behalf of the resource owner.

[RFC6749] already provides robust baseline protection by requiring

  • confidentiality of the refresh tokens in transit and storage,
  • the transmission of refresh tokens over TLS-protected connections betweenauthorization server and client,
  • the authorization server to maintain and check the binding of a refresh tokento a certain client and authentication of this client during token refresh,if possible, and
  • that refresh tokens cannot be generated, modified, or guessed.

[RFC6749] also lays the foundation for further(implementation-specific) security measures, such as refresh token expiration andrevocation as well as refresh token rotation by defining respectiveerror codes and response behaviors.

This specification gives recommendations beyond the scope of[RFC6749] and clarifications.

4.14.2.Recommendations

Authorization serversMUST determine, based on a risk assessment,whether to issue refresh tokens to a certain client. If theauthorization server decides not to issue refresh tokens, the clientMAY obtain a new access token by utilizing other grant types, such as theauthorization code grant type. In such a case, the authorizationserver may utilize cookies and persistent grants to optimize the userexperience.

If refresh tokens are issued, those refresh tokensMUST be bound tothe scope and resource servers as consented by the resource owner.This is to prevent privilege escalation by the legitimate client and reducethe impact of refresh token leakage.

For confidential clients,[RFC6749] already requires that refreshtokens can only be used by the client for which they were issued.

Authorization serversMUST utilize one of these methods todetect refresh token replay by malicious actors for public clients:

  • Sender-constrained refresh tokens: the authorization servercryptographically binds the refresh token to a certain clientinstance, e.g., by utilizing[RFC8705] or[RFC9449].
  • Refresh token rotation: the authorization server issues a newrefresh token with every access token refresh response. Theprevious refresh token is invalidated, but information about therelationship is retained by the authorization server. If a refreshtoken is compromised and subsequently used by both the attackerand the legitimate client, one of them will present an invalidatedrefresh token, which will inform the authorization server of thebreach. The authorization server cannot determine which partysubmitted the invalid refresh token, but it will revoke theactive refresh token. This stops the attack at the cost of forcingthe legitimate client to obtain a fresh authorization grant.

    Implementation note: The grant to which a refresh token belongsmay be encoded into the refresh token itself. This can enable anauthorization server to efficiently determine the grant to which arefresh token belongs, and by extension, all refresh tokens thatneed to be revoked. Authorization serversMUST ensure theintegrity of the refresh token value in this case, for example,using signatures.

Authorization serversMAY revoke refresh tokens automatically in caseof a security event, such as:

  • password change or
  • logout at the authorization server.

Refresh tokensSHOULD expire if the client has been inactive for sometime, i.e., the refresh token has not been used to obtain fresh accesstokens for some time. The expiration time is at the discretion of theauthorization server. It might be a global value or determined basedon the client policy or the grant associated with the refresh token(and its sensitivity).

4.15.Client Impersonating Resource Owner

Resource servers may make access control decisions based on the identity of aresource owner for which an access token was issued, or based on the identity ofa client in the client credentials grant. For example,[RFC9068] (JSON WebToken (JWT) Profile for OAuth 2.0 Access Tokens) describes a data structure foraccess tokens containing asub claim defined as follows:

In cases of access tokens obtained through grants where a resource owner is involved, such as the authorization code grant, the value of "sub"SHOULD correspond to the subject identifier of the resource owner. In cases of access tokens obtained through grants where no resource owner is involved, such as the client credentials grant, the value of "sub"SHOULD correspond to an identifier the authorization server uses to indicate the client application.

If both options are possible, a resource server may mistake a client's identityfor the identity of a resource owner. For example, if a client is able to chooseits ownclient_id during registration with the authorization server, amalicious client may set it to a value identifying a resource owner (e.g., asub value if OpenID Connect is used). If the resource server cannot properlydistinguish between access tokens obtained with involvement of the resourceowner and those without, the client may accidentally be able to access resourcesbelonging to the resource owner.

This attack potentially affects not only implementations using[RFC9068], butalso similar, bespoke solutions.

4.15.1.Countermeasures

Authorization serversSHOULD NOT allow clients to influence theirclient_id orany other claim that could cause confusion with a genuine resource owner if a commonnamespace for client IDs and user identifiers exists, such as in thesub claimexample from[RFC9068] shown inSection 4.15 above. Where this cannot be avoided, authorization serversMUST provideother means for the resource server to distinguish between the two types ofaccess tokens.

4.16.Clickjacking

As described inSection 4.4.1.9 of [RFC6819], the authorization request issusceptible to clickjacking attacks, also called user interface redressing. Insuch an attack, an attacker embeds the authorization endpoint user interface inan innocuous context. A user believing to interact with that context, forexample, by clicking on buttons, inadvertently interacts with the authorizationendpoint user interface instead. The opposite can be achieved as well: A userbelieving to interact with the authorization endpoint might inadvertently type apassword into an attacker-provided input field overlaid over the original userinterface. Clickjacking attacks can be designed such that users can hardlynotice the attack, for example, using almost invisible iframes overlaid on top ofother elements.

An attacker can use this vector to obtain the user's authentication credentials,change the scope of access granted to the client, and potentially access theuser's resources.

Authorization serversMUST prevent clickjacking attacks. Multiplecountermeasures are described in[RFC6819], including the use of theX-Frame-Options HTTP response header field and frame-bustingJavaScript. In addition to those, authorization serversSHOULD alsouse Content Security Policy (CSP) level 2[W3C.CSP-2] or greater.

To be effective, CSP must be used on the authorization endpoint and,if applicable, other endpoints used to authenticate the user andauthorize the client (e.g., the device authorization endpoint, loginpages, error pages, etc.). This prevents framing by unauthorizedorigins in user agents that support CSP. The clientMAY permit beingframed by some other origin than the one used in its redirectionendpoint. For this reason, authorization serversSHOULD allowadministrators to configure allowed origins for particular clientsand/or for clients to register these dynamically.

Using CSP allows authorization servers to specify multiple origins ina single response header field and to constrain these using flexiblepatterns (see[W3C.CSP-2] for details). Level 2 of CSP providesa robust mechanism for protecting against clickjacking by usingpolicies that restrict the origin of frames (by usingframe-ancestors)together with those that restrict the sources of scripts allowed toexecute on an HTML page (by usingscript-src). A non-normativeexample of such a policy is shown in the following listing:

HTTP/1.1 200 OKContent-Security-Policy: frame-ancestors https://ext.example.org:8000Content-Security-Policy: script-src 'self'X-Frame-Options: ALLOW-FROM https://ext.example.org:8000...

Because some user agents do not support[W3C.CSP-2], this techniqueSHOULD be combined with others, including those described in[RFC6819], unless such legacy user agents are explicitly unsupportedby the authorization server. Even in such cases, additionalcountermeasuresSHOULD still be employed.

4.17.Attacks on In-Browser Communication Flows

If the authorization response is sent with in-browser communication techniqueslike postMessage[WHATWG.postmessage_api] instead of HTTP redirects, messages mayinadvertently be sent to malicious origins or injected from malicious origins.

4.17.1.Examples

The following non-normative pseudocode examples of attacks using in-browsercommunication are described in[research.rub].

4.17.1.1.Insufficient Limitation of Receiver Origins

When sending the authorization response or token response viapostMessage, the authorization server sends the response to the wildcardorigin "*" instead of the client's origin. When the window to which theresponse is sent is controlled by an attacker, the attacker can read theresponse.

window.opener.postMessage(  {    code: "ABC",    state: "123"  },  "*" // any website in the opener window can receive the message)
4.17.1.2.Insufficient URI Validation

When sending the authorization response or token response viapostMessage, the authorization server may not check thereceiver origin against the redirection URI and instead, for example, may sendthe response to an origin provided by an attacker. This is analogous tothe attack described inSection 4.1.

window.opener.postMessage(  {    code: "ABC",    state: "123"  },  "https://attacker.example" // attacker-provided value)
4.17.1.3.Injection after Insufficient Validation of Sender Origin

A client that expects the authorization response or token response viapostMessage may not validate the sender origin of the message. Thismay allow an attacker to inject an authorization response or token responseinto the client.

In the case of a maliciously injected authorization response, the attackis a variant of the CSRF attacks described inSection 4.7. Thecountermeasures described inSection 4.7 apply to this attack as well.

In the case of a maliciously injected token response, sender-constrainedaccess tokens as described inSection 4.10.1 may prevent the attack undersome circumstances, but additional countermeasures as described inSection 4.17.2 aregenerally required.

4.17.2.Recommendations

When comparing client receiver origins against pre-registered origins,authorization serversMUST utilize exact string matching as described inSection 4.1.3. Authorization serversMUST send postMessages totrusted client receiver origins, as shown in the following, non-normative example:

window.opener.postMessage(  {    code: "ABC",    state: "123"  },  "https://client.example" // use explicit client origin)

Wildcard origins like "*" in postMessageMUST NOT be used, as attackers can use themto leak a victim's in-browser message to malicious origins.Both measures contribute to the prevention of leakage of authorization codes andaccess tokens (seeSection 4.1).

ClientsMUST prevent injection of in-browser messages on the clientreceiver endpoint. ClientsMUST utilize exact string matching to comparethe initiator origin of an in-browser message with the authorizationserver origin, as shown in the following, non-normative example:

window.addEventListener("message", (e) => {  // validate exact authorization server origin  if (e.origin === "https://honest.as.example") {    // process e.data.code and e.data.state  }})

Since in-browser communication flows only apply a different communicationtechnique (i.e., postMessage instead of HTTP redirect), all measures protectingthe authorization response listed inSection 2.1MUST be applied equally.

5.IANA Considerations

This document has no IANA actions.

6.Security Considerations

Security considerations are described in Sections2,3, and4.

7.References

7.1.Normative References

[BCP195]
Best Current Practice 195,<https://www.rfc-editor.org/info/bcp195>.
At the time of writing, this BCP comprises the following:
Moriarty, K. andS. Farrell,"Deprecating TLS 1.0 and TLS 1.1",BCP 195,RFC 8996,DOI 10.17487/RFC8996,,<https://www.rfc-editor.org/info/rfc8996>.
Sheffer, Y.,Saint-Andre, P., andT. Fossati,"Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS)",BCP 195,RFC 9325,DOI 10.17487/RFC9325,,<https://www.rfc-editor.org/info/rfc9325>.
[RFC3986]
Berners-Lee, T.,Fielding, R., andL. Masinter,"Uniform Resource Identifier (URI): Generic Syntax",STD 66,RFC 3986,DOI 10.17487/RFC3986,,<https://www.rfc-editor.org/info/rfc3986>.
[RFC6749]
Hardt, D., Ed.,"The OAuth 2.0 Authorization Framework",RFC 6749,DOI 10.17487/RFC6749,,<https://www.rfc-editor.org/info/rfc6749>.
[RFC6750]
Jones, M. andD. Hardt,"The OAuth 2.0 Authorization Framework: Bearer Token Usage",RFC 6750,DOI 10.17487/RFC6750,,<https://www.rfc-editor.org/info/rfc6750>.
[RFC6819]
Lodderstedt, T., Ed.,McGloin, M., andP. Hunt,"OAuth 2.0 Threat Model and Security Considerations",RFC 6819,DOI 10.17487/RFC6819,,<https://www.rfc-editor.org/info/rfc6819>.
[RFC7521]
Campbell, B.,Mortimore, C.,Jones, M., andY. Goland,"Assertion Framework for OAuth 2.0 Client Authentication and Authorization Grants",RFC 7521,DOI 10.17487/RFC7521,,<https://www.rfc-editor.org/info/rfc7521>.
[RFC7523]
Jones, M.,Campbell, B., andC. Mortimore,"JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants",RFC 7523,DOI 10.17487/RFC7523,,<https://www.rfc-editor.org/info/rfc7523>.
[RFC8252]
Denniss, W. andJ. Bradley,"OAuth 2.0 for Native Apps",BCP 212,RFC 8252,DOI 10.17487/RFC8252,,<https://www.rfc-editor.org/info/rfc8252>.
[RFC8414]
Jones, M.,Sakimura, N., andJ. Bradley,"OAuth 2.0 Authorization Server Metadata",RFC 8414,DOI 10.17487/RFC8414,,<https://www.rfc-editor.org/info/rfc8414>.
[RFC8705]
Campbell, B.,Bradley, J.,Sakimura, N., andT. Lodderstedt,"OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens",RFC 8705,DOI 10.17487/RFC8705,,<https://www.rfc-editor.org/info/rfc8705>.
[RFC9068]
Bertocci, V.,"JSON Web Token (JWT) Profile for OAuth 2.0 Access Tokens",RFC 9068,DOI 10.17487/RFC9068,,<https://www.rfc-editor.org/info/rfc9068>.

7.2.Informative References

[arXiv.1508.04324v2]
Mladenov, V.,Mainka, C., andJ. Schwenk,"On the security of modern Single Sign-On Protocols: Second-Order Vulnerabilities in OpenID Connect",arXiv:1508.04324v2,DOI 10.48550/arXiv.1508.04324,,<https://arxiv.org/abs/1508.04324v2/>.
[arXiv.1601.01229]
Fett, D.,Küsters, R., andG. Schmitz,"A Comprehensive Formal Security Analysis of OAuth 2.0",arXiv:1601.01229,DOI 10.48550/arXiv.1601.01229,,<https://arxiv.org/abs/1601.01229/>.
[arXiv.1704.08539]
Fett, D.,Küsters, R., andG. Schmitz,"The Web SSO Standard OpenID Connect: In-Depth Formal Security Analysis and Security Guidelines",arXiv:1704.08539,DOI 10.48550/arXiv.1704.08539,,<https://arxiv.org/abs/1704.08539/>.
[arXiv.1901.11520]
Fett, D.,Hosseyni, P., andR. Küsters,"An Extensive Formal Security Analysis of the OpenID Financial-grade API",arXiv:1901.11520,DOI 10.48550/arXiv.1901.11520,,<https://arxiv.org/abs/1901.11520/>.
[bug.chromium]
"Referer header includes URL fragment when opening link using New Tab",Chromium Issue Tracker, Issue ID: 40076763,<https://issues.chromium.org/issues/40076763>.
[JWT-ENCODED-STATE]
Bradley, J.,Lodderstedt, T., andH. Zandbelt,"Encoding claims in the OAuth 2 state parameter using a JWT",Work in Progress,Internet-Draft, draft-bradley-oauth-jwt-encoded-state-09,,<https://datatracker.ietf.org/doc/html/draft-bradley-oauth-jwt-encoded-state-09>.
[OAUTH-V2.1]
Hardt, D.,Parecki, A., andT. Lodderstedt,"The OAuth 2.1 Authorization Framework",Work in Progress,Internet-Draft, draft-ietf-oauth-v2-1-12,,<https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12>.
[OAuth.Post]
Jones, M. andB. Campbell,"OAuth 2.0 Form Post Response Mode",The OpenID Foundation,,<https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html>.
[OAuth.Responses]
de Medeiros, B., Ed.,Scurtescu, M.,Tarjan, P., andM. Jones,"OAuth 2.0 Multiple Response Type Encoding Practices",The OpenID Foundation,,<https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html>.
[OpenID.Core]
Sakimura, N.,Bradley, J.,Jones, M.,de Medeiros, B., andC. Mortimore,"OpenID Connect Core 1.0 incorporating errata set 2",The OpenID Foundation,,<https://openid.net/specs/openid-connect-core-1_0.html>.
[OpenID.Discovery]
Sakimura, N.,Bradley, J.,Jones, M., andE. Jay,"OpenID Connect Discovery 1.0 incorporating errata set 2",The OpenID Foundation,,<https://openid.net/specs/openid-connect-discovery-1_0.html>.
[OpenID.JARM]
Lodderstedt, T. andB. Campbell,"Financial-grade API: JWT Secured Authorization Response Mode for OAuth 2.0 (JARM)",The OpenID Foundation,,<https://openid.net/specs/openid-financial-api-jarm.html>.
[owasp.redir]
OWASP Foundation,"Unvalidated Redirects and Forwards Cheat Sheet",OWASP Cheat Sheet Series,<https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html>.
[research.cmu]
Chen, E.,Pei, Y.,Chen, S.,Tian, Y.,Kotcher, R., andP. Tague,"OAuth Demystified for Mobile Application Developers",CCS '14: Proceedings of the 2014 ACM SIGSAC Conference on Computer and Communications Security, pp. 892-903,DOI 10.1145/2660267.2660323,,<https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/OAuthDemystified.pdf>.
[research.jcs_14]
Bansal, C.,Bhargavan, K.,Delignat-Lavaud, A., andS. Maffeis,"Discovering concrete attacks on website authorization by formal analysis",Journal of Computer Security, vol. 22, no. 4, pp. 601-657,DOI 10.3233/JCS-140503,,<https://www.doc.ic.ac.uk/~maffeis/papers/jcs14.pdf>.
[research.rub]
Jannett, L.,Mladenov, V.,Mainka, C., andJ. Schwenk,"DISTINCT: Identity Theft using In-Browser Communications in Dual-Window Single Sign-On",CCS '22: Proceedings of the 2022 ACM SIGSAC Conference on Computer and Communications Security,DOI 10.1145/3548606.3560692,,<https://dl.acm.org/doi/pdf/10.1145/3548606.3560692>.
[research.rub2]
Fries, C.,"Security Analysis of Real-Life OpenID Connect Implementations",Master's thesis, Ruhr-Universität Bochum (RUB),,<https://www.nds.rub.de/media/ei/arbeiten/2021/05/03/masterthesis.pdf>.
[research.ubc]
Sun, S.-T. andK. Beznosov,"The Devil is in the (Implementation) Details: An Empirical Analysis of OAuth SSO Systems",Proceedings of the 2012 ACM conference on Computer and communications security (CCS '12), pp. 378-390,DOI 10.1145/2382196.2382238,,<https://css.csail.mit.edu/6.858/2012/readings/oauth-sso.pdf>.
[research.udel]
Liu, D.,Hao, S., andH. Wang,"All Your DNS Records Point to Us: Understanding the Security Threats of Dangling DNS Records",CCS '16: Proceedings of the 2016 ACM SIGSAC Conference on Computer and Communications Security, pp. 1414-1425,DOI 10.1145/2976749.2978387,,<https://dl.acm.org/doi/pdf/10.1145/2976749.2978387>.
[RFC2119]
Bradner, S.,"Key words for use in RFCs to Indicate Requirement Levels",BCP 14,RFC 2119,DOI 10.17487/RFC2119,,<https://www.rfc-editor.org/info/rfc2119>.
[RFC7591]
Richer, J., Ed.,Jones, M.,Bradley, J.,Machulak, M., andP. Hunt,"OAuth 2.0 Dynamic Client Registration Protocol",RFC 7591,DOI 10.17487/RFC7591,,<https://www.rfc-editor.org/info/rfc7591>.
[RFC7636]
Sakimura, N., Ed.,Bradley, J., andN. Agarwal,"Proof Key for Code Exchange by OAuth Public Clients",RFC 7636,DOI 10.17487/RFC7636,,<https://www.rfc-editor.org/info/rfc7636>.
[RFC8174]
Leiba, B.,"Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words",BCP 14,RFC 8174,DOI 10.17487/RFC8174,,<https://www.rfc-editor.org/info/rfc8174>.
[RFC8707]
Campbell, B.,Bradley, J., andH. Tschofenig,"Resource Indicators for OAuth 2.0",RFC 8707,DOI 10.17487/RFC8707,,<https://www.rfc-editor.org/info/rfc8707>.
[RFC9101]
Sakimura, N.,Bradley, J., andM. Jones,"The OAuth 2.0 Authorization Framework: JWT-Secured Authorization Request (JAR)",RFC 9101,DOI 10.17487/RFC9101,,<https://www.rfc-editor.org/info/rfc9101>.
[RFC9110]
Fielding, R., Ed.,Nottingham, M., Ed., andJ. Reschke, Ed.,"HTTP Semantics",STD 97,RFC 9110,DOI 10.17487/RFC9110,,<https://www.rfc-editor.org/info/rfc9110>.
[RFC9126]
Lodderstedt, T.,Campbell, B.,Sakimura, N.,Tonge, D., andF. Skokan,"OAuth 2.0 Pushed Authorization Requests",RFC 9126,DOI 10.17487/RFC9126,,<https://www.rfc-editor.org/info/rfc9126>.
[RFC9207]
Meyer zu Selhausen, K. andD. Fett,"OAuth 2.0 Authorization Server Issuer Identification",RFC 9207,DOI 10.17487/RFC9207,,<https://www.rfc-editor.org/info/rfc9207>.
[RFC9396]
Lodderstedt, T.,Richer, J., andB. Campbell,"OAuth 2.0 Rich Authorization Requests",RFC 9396,DOI 10.17487/RFC9396,,<https://www.rfc-editor.org/info/rfc9396>.
[RFC9440]
Campbell, B. andM. Bishop,"Client-Cert HTTP Header Field",RFC 9440,DOI 10.17487/RFC9440,,<https://www.rfc-editor.org/info/rfc9440>.
[RFC9449]
Fett, D.,Campbell, B.,Bradley, J.,Lodderstedt, T.,Jones, M., andD. Waite,"OAuth 2.0 Demonstrating Proof of Possession (DPoP)",RFC 9449,DOI 10.17487/RFC9449,,<https://www.rfc-editor.org/info/rfc9449>.
[TOKEN-BINDING]
Jones, M.,Campbell, B.,Bradley, J., andW. Denniss,"OAuth 2.0 Token Binding",Work in Progress,Internet-Draft, draft-ietf-oauth-token-binding-08,,<https://datatracker.ietf.org/doc/html/draft-ietf-oauth-token-binding-08>.
[W3C.CSP-2]
West, M.,Barth, A., andD. Veditz,"Content Security Policy Level 2",W3C Recommendation,,<https://www.w3.org/TR/2016/REC-CSP2-20161215/>.Latest version available at<https://www.w3.org/TR/CSP2/>.
[W3C.webappsec-referrer-policy]
Eisinger, J. andE. Stark,"Referrer Policy",,<https://www.w3.org/TR/2017/CR-referrer-policy-20170126/>.Latest version available at<https://www.w3.org/TR/referrer-policy/>.
[W3C.WebAuthn]
Hodges, J.,Jones, J.C.,Jones, M.B.,Kumar, A., andE. Lundberg,"Web Authentication: An API for accessing Public Key Credentials Level 2",W3C Recommendation,,<https://www.w3.org/TR/2021/REC-webauthn-2-20210408/>.Latest version available at<https://www.w3.org/TR/webauthn-2/>.
[W3C.WebCrypto]
Watson, M., Ed.,"Web Cryptography API",W3C Recommendation,,<https://www.w3.org/TR/2017/REC-WebCryptoAPI-20170126/>.Latest version available at<https://www.w3.org/TR/WebCryptoAPI/>.
[WHATWG.CORS]
WHATWG,"CORS protocol",Fetch: Living Standard, Section 3.2,,<https://fetch.spec.whatwg.org/#http-cors-protocol>.
[WHATWG.postmessage_api]
WHATWG,"Cross-document messaging",HTML: Living Standard, Section 9.3,,<https://html.spec.whatwg.org/multipage/web-messaging.html#web-messaging>.

Acknowledgements

We would like to thankBrock Allen,Annabelle Richard Backman,Dominick Baier,Vittorio Bertocci,Brian Campbell,Bruno Crispo,William Dennis,George Fletcher,Matteo Golinelli,Dick Hardt,Joseph Heenan,Pedram Hosseyni,Phil Hunt,Tommaso Innocenti,Louis Jannett,Jared Jennings,Michael B. Jones,Engin Kirda,Konstantin Lapine,Neil Madden,Christian Mainka,Jim Manico,Nov Matake,Doug McDorman,Karsten Meyer zu Selhausen,Ali Mirheidari,Vladislav Mladenov,Kaan Onarioglu,Aaron Parecki,Michael Peck,Johan Peeters,Nat Sakimura,Guido Schmitz,Jörg Schwenk,Rifaat Shekh-Yusef,Travis Spencer,Petteri Stenius,Tomek Stojecki,David Waite,Tim Würtele, andHans Zandbeltfor their valuable feedback.

Authors' Addresses

Torsten Lodderstedt
SPRIND
Email:torsten@lodderstedt.net
John Bradley
Yubico
Email:ve7jtb@ve7jtb.com
Andrey Labunets
Independent Researcher
Email:isciurus@gmail.com
Daniel Fett
Authlete
Email:mail@danielfett.de

[8]ページ先頭

©2009-2025 Movatter.jp