RFC9101 — Механизм авторизации OAuth 2.0: запрос авторизации, защищённый с помощью JWT (JAR)

The OAuth 2.0 Authorization Framework: JWT-Secured Authorization Request (JAR)

Выжимка

RFC 9101 определяет передачу параметров запроса авторизации OAuth 2.0 в объекте запроса (Request Object), представленном JWT. Объект подписывается с помощью JWS для защиты целостности и аутентификации источника; дополнительное шифрование с помощью JWE обеспечивает конфиденциальность. Объект передаётся непосредственно в параметре request либо по ссылке в request_uri. Сервер авторизации проверяет подпись и совпадение client_id во внешнем запросе и объекте, а для обработки использует только параметры из объекта запроса. Документ также рассматривает предотвращение понижения защиты, риски получения объектов по URI, смешения назначений JWT и раскрытия персональных данных.

Полный перевод

Internet Engineering Task Force (IETF)                       N. Sakimura
Request for Comments: 9101                                NAT.Consulting
Категория: Standards Track                                    J. Bradley
ISSN: 2070-1721                                                   Yubico
                                                                M. Jones
                                                               Microsoft
                                                             Август 2021


Механизм авторизации OAuth 2.0: запрос авторизации, защищённый с помощью JWT
                                 (JAR)

Аннотация

   Запрос авторизации в OAuth 2.0, описанный в RFC 6749, использует
   сериализацию параметров строки запроса: параметры запроса авторизации
   кодируются в URI запроса и передаются через пользовательские агенты,
   такие как веб-браузеры. Хотя это легко реализовать, такой подход
   означает, что a) передача через пользовательские агенты не защищена
   от нарушения целостности, и поэтому параметры могут быть искажены,
   b) источник передаваемых данных не аутентифицируется и c) передачу
   через пользовательские агенты можно отслеживать. Из-за этих слабых
   мест к настоящему времени был предложен ряд атак на протокол.

   Этот документ вводит возможность вместо этого передавать параметры
   запроса в JSON Web Token (JWT), что позволяет подписать запрос с
   помощью JSON Web Signature (JWS) и зашифровать его с помощью JSON Web
   Encryption (JWE), обеспечив целостность запроса авторизации,
   аутентификацию его источника и конфиденциальность. Запрос можно
   передавать по значению или по ссылке.

Статус этого документа

   Этот документ относится к категории Internet Standards Track.

   Этот документ подготовлен Internet Engineering Task Force (IETF).
   Он отражает консенсус сообщества IETF. Он прошёл публичное
   рецензирование и был одобрен для публикации Internet Engineering
   Steering Group (IESG). Дополнительная информация о стандартах
   Интернета приведена в разделе 2 RFC 7841.

   Информацию о текущем статусе этого документа, любых исправлениях
   ошибок и способах предоставления отзывов о нём можно получить по
   адресу https://www.rfc-editor.org/info/rfc9101.

Уведомление об авторских правах

   Copyright (c) 2021 IETF Trust и лица, указанные в качестве авторов
   документа. Все права защищены.

   На этот документ распространяются BCP 78 и Правовые положения IETF
   Trust в отношении документов IETF (Legal Provisions Relating to IETF
   Documents, https://trustee.ietf.org/license-info), действовавшие на
   дату публикации этого документа. Внимательно ознакомьтесь с этими
   документами, поскольку они описывают ваши права и ограничения в
   отношении этого документа. Компоненты кода, извлечённые из этого
   документа, должны включать текст Simplified BSD License, как описано
   в разделе 4.e Правовых положений IETF Trust, и предоставляются без
   гарантий, как описано в Simplified BSD License.

Содержание

   1.  Введение
     1.1.  Язык требований
   2.  Терминология
     2.1.  Объект запроса
     2.2.  URI объекта запроса
   3.  Обозначения и сокращения
   4.  Объект запроса
   5.  Запрос авторизации
     5.1.  Передача объекта запроса по значению
     5.2.  Передача объекта запроса по ссылке
       5.2.1.  URI, ссылающийся на объект запроса
       5.2.2.  Запрос с использованием параметра запроса "request_uri"
       5.2.3.  Сервер авторизации получает объект запроса
   6.  Проверка запросов на основе JWT
     6.1.  Объект запроса, зашифрованный с помощью JWE
     6.2.  Объект запроса, подписанный с помощью JWS
     6.3.  Сборка и проверка параметров запроса
   7.  Ответ сервера авторизации
   8.  Требования к TLS
   9.  Вопросы IANA
     9.1.  Регистрация параметров OAuth
     9.2.  Реестр метаданных сервера авторизации OAuth
     9.3.  Реестр метаданных динамической регистрации клиентов OAuth
     9.4.  Регистрация типа содержимого
       9.4.1.  Содержимое реестра
   10. Вопросы безопасности
     10.1.  Выбор алгоритмов
     10.2.  Аутентификация источника запроса
     10.3.  Явно заданные конечные точки
     10.4.  Риски, связанные с request_uri
       10.4.1.  DDoS-атака на сервер авторизации
       10.4.2.  Перезапись URI запроса
     10.5.  Атака с понижением уровня защиты
     10.6.  Вопросы безопасности TLS
     10.7.  Несоответствия параметров
     10.8.  Смешение JWT разных типов
   11. Вопросы приватности
     11.1.  Ограничение сбора данных
     11.2.  Ограничение раскрытия данных
       11.2.1.  Раскрытие запроса
       11.2.2.  Отслеживание с использованием URI объекта запроса
   12. Ссылки
     12.1.  Нормативные ссылки
     12.2.  Информационные ссылки
   Благодарности
   Адреса авторов

1.  Введение

   Запрос авторизации в OAuth 2.0 [RFC6749] использует сериализацию
   параметров строки запроса и обычно передаётся через пользовательские
   агенты, такие как веб-браузеры.

   Например, параметры "response_type", "client_id", "state" и
   "redirect_uri" кодируются в URI запроса:

       GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
       &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
       Host: server.example.com

   Хотя это легко реализовать, кодирование в URI не позволяет применять
   средства безопасности прикладного уровня для обеспечения
   конфиденциальности и защиты целостности. Хотя TLS используется для
   обеспечения безопасности связи между клиентом и пользовательским
   агентом, а также между пользовательским агентом и сервером
   авторизации, сеансы TLS завершаются в пользовательском агенте.
   Кроме того, сеансы TLS могут завершаться раньше, на каком-либо
   промежуточном устройстве (например, на балансировщике нагрузки).

   В результате запрос авторизации из [RFC6749] имеет следующие
   недостатки:

   (a)  передача через пользовательские агенты не защищена от нарушения
        целостности, и поэтому параметры могут быть искажены
        (необеспечение защиты целостности);

   (b)  источник передаваемых данных не аутентифицируется
        (необеспечение аутентификации источника);

   (c)  передачу через пользовательские агенты можно отслеживать
        (необеспечение ограничения распространения/конфиденциальности).

   Из-за этих присущих механизму слабых мест был выявлен ряд атак на
   протокол, таких как перезапись URI перенаправления.

   Применение средств безопасности прикладного уровня смягчает эти
   проблемы.

   Применение средств безопасности прикладного уровня позволяет
   доверенной третьей стороне подготавливать запросы так, чтобы
   клиентское приложение не могло запрашивать больше разрешений,
   чем было согласовано ранее.

   Кроме того, передача запроса по ссылке позволяет сократить накладные
   расходы на передачу по сети.

   Кодирование JWT [RFC7519] было выбрано по следующим причинам:

   (1)  тесная связь с JSON, который используется в качестве формата
        ответа OAuth

   (2)  удобство для разработчиков благодаря текстовому представлению

   (3)  относительная компактность по сравнению с XML

   (4)  статус разработки «Предлагаемый стандарт» (Proposed Standard),
        в том числе у связанных методов подписи и шифрования
        [RFC7515] [RFC7516]

   (5)  относительная простота JWS и JWE по сравнению с XML Signature
        и Encryption.

   Параметры "request" и "request_uri" вводятся как дополнительные
   параметры запроса авторизации для потоков OAuth 2.0 [RFC6749].
   Параметр "request" представляет собой JSON Web Token (JWT)
   [RFC7519], набор утверждений JWT (JWT Claims Set) которого содержит
   параметры запроса авторизации OAuth 2.0, закодированные в JSON.
   Обратите внимание, что, в отличие от RFC 7519, элементы набора
   утверждений представляют собой закодированные параметры запроса
   OAuth [IANA.OAuth.Parameters], дополненные лишь несколькими
   утверждениями JSON Web Token, которыми управляет IANA
   [IANA.JWT.Claims], в частности "iss" и "aud". Целостность JWT в
   параметре "request" защищается, а его источник аутентифицируется
   с помощью JWS.

   JWT [RFC7519] можно передать конечной точке авторизации по ссылке;
   в этом случае вместо "request" используется параметр "request_uri".

   Использование JWT [RFC7519] для кодирования запроса вместо параметров
   строки запроса имеет ряд преимуществ:

   (a)  Защита целостности. Запрос можно подписать, чтобы можно было
        проверить его целостность.

   (b)  Аутентификация источника. Запрос можно подписать, чтобы можно
        было аутентифицировать подписавшую его сторону.

   (c)  Защита конфиденциальности. Запрос можно зашифровать, чтобы
        обеспечить сквозную конфиденциальность, даже если соединение
        TLS завершается в той или иной точке (в том числе в
        пользовательских агентах и до них).

   (d)  Минимизация сбора данных. Запрос может быть подписан доверенной
        третьей стороной, удостоверяющей, что запрос авторизации
        соответствует определённой политике. Например, доверенная
        третья сторона может предварительно проверить запрос, чтобы
        подтвердить, что все запрашиваемые персональные данные строго
        необходимы для выполнения процесса, запрошенного конечным
        пользователем; затем эта доверенная третья сторона подпишет
        запрос. После этого сервер авторизации проверяет подпись и
        показывает статус соответствия конечному пользователю,
        который при авторизации запроса получает некоторую
        уверенность в его правомерности. В некоторых случаях при
        таких обстоятельствах может быть даже желательно пропустить
        диалог авторизации.

   Есть несколько случаев, в которых полезна передача запроса по ссылке,
   например:

   1.  когда желательно уменьшить размер передаваемого запроса.
       Применение средств безопасности прикладного уровня увеличивает
       размер запроса, особенно при использовании криптографии с
       открытым ключом.

   2.  когда клиент не хочет выполнять криптографические операции на
       прикладном уровне. Сервер авторизации может предоставить
       конечную точку для приёма запроса авторизации посредством
       прямого взаимодействия с клиентом, при котором клиент
       аутентифицируется, а канал защищён с помощью TLS.

   Эта возможность используется в OpenID Connect [OpenID.Core].

1.1.  Язык требований

   Ключевые слова «ДОЛЖЕН (MUST)», «НЕ ДОЛЖЕН (MUST NOT)», «ДОЛЖЕН
   (REQUIRED)», «ДОЛЖЕН (SHALL)», «НЕ ДОЛЖЕН (SHALL NOT)», «СЛЕДУЕТ
   (SHOULD)», «НЕ СЛЕДУЕТ (SHOULD NOT)», «СЛЕДУЕТ (RECOMMENDED)»,
   «НЕ СЛЕДУЕТ (NOT RECOMMENDED)», «МОЖЕТ (MAY)» и «НЕОБЯЗАТЕЛЬНО
   (OPTIONAL)» в этом документе следует трактовать согласно BCP 14
   [RFC2119] [RFC8174] тогда и только тогда, когда они приведены
   полностью в верхнем регистре, как показано здесь.

2.  Терминология

   Для целей этой спецификации в дополнение к определениям из OAuth 2.0
   Framework [RFC6749], JSON Web Signature [RFC7515] и JSON Web
   Encryption [RFC7516] применяются следующие термины и определения.

2.1.  Объект запроса

   Объект запроса (Request Object) — это JSON Web Token (JWT) [RFC7519],
   набор утверждений JWT которого содержит параметры запроса авторизации
   OAuth 2.0, закодированные в JSON.

2.2.  URI объекта запроса

   URI объекта запроса (Request Object URI) — это абсолютный URI,
   ссылающийся на набор параметров, составляющих запрос авторизации
   OAuth 2.0. Содержимое ресурса, на который ссылается URI, представляет
   собой объект запроса (раздел 2.1), за исключением случая, когда URI
   был предоставлен клиенту тем же сервером авторизации: в этом случае
   содержимое является деталью реализации, определяемой по усмотрению
   сервера авторизации. Представление содержимого в виде объекта
   запроса обеспечивает совместимость в тех случаях, когда поставщик
   "request_uri" и его потребитель являются разными сторонами,
   например когда клиент предоставляет URI, ссылающийся на объект
   запроса, хранящийся в серверной службе клиента, доступ к которой
   предоставлен по HTTPS. В последнем случае, когда сервер авторизации
   является и поставщиком, и потребителем URI, например когда он
   предоставляет конечную точку, выдающую URI в обмен на объект запроса,
   этот вопрос совместимости не возникает.

3.  Обозначения и сокращения

   В этой спецификации используются следующие сокращения.

   JSON:  JavaScript Object Notation

   JWT:  JSON Web Token

   JWS:  JSON Web Signature

   JWE:  JSON Web Encryption

   URI:  Uniform Resource Identifier

   URL:  Uniform Resource Locator

4.  Объект запроса

   Объект запроса (раздел 2.1) используется для предоставления параметров
   запроса авторизации OAuth 2.0. Он ДОЛЖЕН (MUST) содержать все параметры
   (включая параметры расширений), используемые для обработки запроса
   авторизации OAuth 2.0 [RFC6749], за исключением параметров "request"
   и "request_uri", определённых в этом документе. Параметры
   представлены в виде утверждений JWT объекта. Имена параметров и
   строковые значения ДОЛЖНЫ (MUST) включаться в виде строк JSON.
   Поскольку объекты запроса обрабатываются в разных доменах и
   потенциально за пределами замкнутой экосистемы, согласно разделу 8.1
   [RFC8259] эти строки JSON ДОЛЖНЫ (MUST) кодироваться с использованием
   UTF-8 [RFC3629]. Числовые значения ДОЛЖНЫ (MUST) включаться в виде
   чисел JSON. Объект запроса МОЖЕТ (MAY) включать любые параметры
   расширений. Этот объект JSON [RFC8259] образует набор утверждений
   JWT, определённый в JWT [RFC7519]. Затем набор утверждений JWT
   подписывается либо подписывается и шифруется.

   Для подписания используется JSON Web Signature (JWS) [RFC7515].
   Результатом является JWT, подписанный с помощью JWS [RFC7519].
   Если объект запроса авторизации подписан, ему СЛЕДУЕТ (SHOULD)
   содержать утверждения "iss" (издатель) и "aud" (аудитория) в
   качестве членов с той же семантикой, что определена в спецификации
   JWT [RFC7519]. В качестве значения "aud" следует использовать значение
   "issuer" сервера авторизации (AS), определённое в RFC 8414 [RFC8414].

   Для шифрования используется JWE [RFC7516]. Когда применяются и
   подпись, и шифрование, JWT ДОЛЖЕН (MUST) быть сначала подписан,
   а затем зашифрован, как описано в разделе 11.2 [RFC7519].
   Результатом является вложенный JWT (Nested JWT), определённый
   в [RFC7519].
   Клиент определяет алгоритмы, используемые для подписания и шифрования объектов запроса. Выбранные алгоритмы должны поддерживаться и клиентом, и сервером авторизации. Клиент может сообщить серверу авторизации о поддерживаемых им алгоритмах в своих метаданных динамической регистрации клиента [RFC7591], а именно в значениях метаданных "request_object_signing_alg", "request_object_encryption_alg" и "request_object_encryption_enc". Аналогичным образом сервер авторизации может сообщить клиенту о поддерживаемых им алгоритмах в своих метаданных сервера авторизации [RFC8414], а именно в значениях метаданных "request_object_signing_alg_values_supported", "request_object_encryption_alg_values_supported" и "request_object_encryption_enc_values_supported".

   Объект запроса МОЖЕТ (MAY) передаваться по значению, как описано в разделе 5.1, или по ссылке, как описано в разделе 5.2. Параметры "request" и "request_uri" НЕ ДОЛЖНЫ (MUST NOT) включаться в объекты запроса.

   Объект запроса (раздел 2.1) имеет тип содержимого [RFC2046] "application/oauth-authz-req+jwt". Обратите внимание, что в некоторых существующих развёртываниях вместо него может использоваться тип "application/jwt".

   Ниже приведён пример утверждений (Claims) в объекте запроса до кодирования base64url [RFC7515] и подписания. Обратите внимание, что он включает параметры расширения "nonce" и "max_age".

     {
      "iss": "s6BhdRkqt3",
      "aud": "https://server.example.com",
      "response_type": "code id_token",
      "client_id": "s6BhdRkqt3",
      "redirect_uri": "https://client.example.org/cb",
      "scope": "openid",
      "state": "af0ifjsldkj",
      "nonce": "n-0S6_WzA2Mj",
      "max_age": 86400
     }

   Его подписание с использованием алгоритма "RS256" [RFC7518] даёт следующее значение объекта запроса (переносы строк внутри значений добавлены только для отображения):

     eyJhbGciOiJSUzI1NiIsImtpZCI6ImsyYmRjIn0.ewogICAgImlzcyI6ICJzNkJoZF
     JrcXQzIiwKICAgICJhdWQiOiAiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20iLAog
     ICAgInJlc3BvbnNlX3R5cGUiOiAiY29kZSBpZF90b2tlbiIsCiAgICAiY2xpZW50X2
     lkIjogInM2QmhkUmtxdDMiLAogICAgInJlZGlyZWN0X3VyaSI6ICJodHRwczovL2Ns
     aWVudC5leGFtcGxlLm9yZy9jYiIsCiAgICAic2NvcGUiOiAib3BlbmlkIiwKICAgIC
     JzdGF0ZSI6ICJhZjBpZmpzbGRraiIsCiAgICAibm9uY2UiOiAibi0wUzZfV3pBMk1q
     IiwKICAgICJtYXhfYWdlIjogODY0MDAKfQ.Nsxa_18VUElVaPjqW_ToI1yrEJ67BgK
     b5xsuZRVqzGkfKrOIX7BCx0biSxYGmjK9KJPctH1OC0iQJwXu5YVY-vnW0_PLJb1C2
     HG-ztVzcnKZC2gE4i0vgQcpkUOCpW3SEYXnyWnKzuKzqSb1wAZALo5f89B_p6QA6j6
     JwBSRvdVsDPdulW8lKxGTbH82czCaQ50rLAg3EYLYaCb4ik4I1zGXE4fvim9FIMs8O
     CMmzwIB5S-ujFfzwFjoyuPEV4hJnoVUmXR_W9typPf846lGwA8h9G9oNTIuX8Ft2jf
     pnZdFmLg3_wr3Wa5q3a-lfbgF3S9H_8nN3j1i7tLR_5Nz-g

   Следующий открытый ключ RSA, представленный в формате JSON Web Key (JWK), можно использовать для проверки подписи объекта запроса в этом и последующих примерах объектов запроса (переносы строк внутри значений добавлены только для отображения):

     {
      "kty":"RSA",
      "kid":"k2bdc",
      "n":"x5RbkAZkmpRxia65qRQ1wwSMSxQUnS7gcpVTV_cdHmfmG2ltd2yabEO9XadD8
           pJNZubINPpmgHh3J1aD9WRwS05ucmFq3CfFsluLt13_7oX5yDRSKX7poXmT_5
           ko8k4NJZPMAO8fPToDTH7kHYbONSE2FYa5GZ60CUsFhSonI-dcMDJ0Ary9lxI
           w5k2z4TAdARVWcS7sD07VhlMMshrwsPHBQgTatlkxyIHXbYdtak8fqvNAwr7O
           lVEvM_Ipf5OfmdB8Sd-wjzaBsyP4VhJKoi_qdgSzpC694XZeYPq45Sw-q51iF
           UlcOlTCI7z6jltUtnR6ySn6XDGFnzH5Fe5ypw",
      "e":"AQAB"
     }

5.  Запрос авторизации

   Клиент формирует URI запроса авторизации, добавляя следующие параметры в компонент запроса URI конечной точки авторизации с использованием формата "application/x-www-form-urlencoded":

   request
      ДОЛЖЕН (REQUIRED) присутствовать, если не указан "request_uri". Объект запроса (раздел 2.1), содержащий параметры запроса авторизации, указанные в разделе 4 [RFC6749] (OAuth 2.0). Если этот параметр присутствует в запросе авторизации, "request_uri" НЕ ДОЛЖЕН (MUST NOT) присутствовать.

   request_uri
      ДОЛЖЕН (REQUIRED) присутствовать, если не указан "request". Абсолютный URI, как определено в RFC 3986 [RFC3986], являющийся URI объекта запроса (раздел 2.2), который ссылается на параметры запроса авторизации, указанные в разделе 4 [RFC6749] (OAuth 2.0). Если этот параметр присутствует в запросе авторизации, "request" НЕ ДОЛЖЕН (MUST NOT) присутствовать.

   client_id
      ДОЛЖЕН (REQUIRED) присутствовать. Параметр "client_id" OAuth 2.0 [RFC6749]. Значение ДОЛЖНО (MUST) совпадать с "client_id" объекта запроса (раздел 2.1), передаваемого посредством "request" или "request_uri".

   Клиент направляет владельца ресурса по сформированному URI, используя ответ перенаправления HTTP или другие доступные ему средства через пользовательский агент.

   Например, клиент направляет пользовательский агент конечного пользователя для выполнения следующего HTTPS-запроса:

   GET /authz?client_id=s6BhdRkqt3&request=eyJhbG..AlMGzw HTTP/1.1
   Host: server.example.com

   Значение параметра request сокращено для краткости.

   Объект запроса авторизации ДОЛЖЕН (MUST) быть одним из следующих:

   (a)  Подписанным с использованием JWS

   (b)  Подписанным с использованием JWS и зашифрованным с использованием JWE

   Клиент МОЖЕТ (MAY) также дублировать параметры, включённые в объект запроса, в параметрах строки запроса для обеспечения обратной совместимости и т. п. Однако сервер авторизации, поддерживающий эту спецификацию, ДОЛЖЕН (MUST) использовать только параметры, включённые в объект запроса.

5.1.  Передача объекта запроса по значению

   Клиент отправляет запрос авторизации в виде объекта запроса в конечную точку авторизации как значение параметра "request".

   Ниже приведён пример запроса авторизации с использованием параметра "request" (переносы строк внутри значений добавлены только для отображения):

     https://server.example.com/authorize?client_id=s6BhdRkqt3&
       request=eyJhbGciOiJSUzI1NiIsImtpZCI6ImsyYmRjIn0.ewogICAgImlzcyI6
       ICJzNkJoZFJrcXQzIiwKICAgICJhdWQiOiAiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBs
       ZS5jb20iLAogICAgInJlc3BvbnNlX3R5cGUiOiAiY29kZSBpZF90b2tlbiIsCiAg
       ICAiY2xpZW50X2lkIjogInM2QmhkUmtxdDMiLAogICAgInJlZGlyZWN0X3VyaSI6
       ICJodHRwczovL2NsaWVudC5leGFtcGxlLm9yZy9jYiIsCiAgICAic2NvcGUiOiAi
       b3BlbmlkIiwKICAgICJzdGF0ZSI6ICJhZjBpZmpzbGRraiIsCiAgICAibm9uY2Ui
       OiAibi0wUzZfV3pBMk1qIiwKICAgICJtYXhfYWdlIjogODY0MDAKfQ.Nsxa_18VU
       ElVaPjqW_ToI1yrEJ67BgKb5xsuZRVqzGkfKrOIX7BCx0biSxYGmjK9KJPctH1OC
       0iQJwXu5YVY-vnW0_PLJb1C2HG-ztVzcnKZC2gE4i0vgQcpkUOCpW3SEYXnyWnKz
       uKzqSb1wAZALo5f89B_p6QA6j6JwBSRvdVsDPdulW8lKxGTbH82czCaQ50rLAg3E
       YLYaCb4ik4I1zGXE4fvim9FIMs8OCMmzwIB5S-ujFfzwFjoyuPEV4hJnoVUmXR_W
       9typPf846lGwA8h9G9oNTIuX8Ft2jfpnZdFmLg3_wr3Wa5q3a-lfbgF3S9H_8nN3
       j1i7tLR_5Nz-g

5.2.  Передача объекта запроса по ссылке

   Параметр запроса авторизации "request_uri" позволяет передавать запросы авторизации OAuth по ссылке вместо передачи по значению. Этот параметр используется так же, как параметр "request", за исключением того, что значение объекта запроса извлекается из ресурса, идентифицируемого указанным URI, вместо передачи по значению.

   Полной длине URI запроса НЕ СЛЕДУЕТ (SHOULD NOT) превышать 512 символов ASCII. Это ограничение обусловлено двумя причинами:

   1.  Многие телефоны, представленные на рынке на момент написания этого документа, по-прежнему не принимают большие объёмы полезной нагрузки. Обычно ограничение составляет 512 или 1024 символа ASCII.

   2.  При медленном соединении, например мобильном соединении 2G, большой URL привёл бы к медленному отклику; поэтому его использование нецелесообразно с точки зрения удобства пользователя.

   Содержимое ресурса, на который ссылается "request_uri", ДОЛЖНО (MUST) быть объектом запроса и ДОЛЖНО (MUST) быть доступно серверу авторизации, если только URI не был предоставлен клиенту сервером авторизации. В первом случае "request_uri" ДОЛЖЕН (MUST) быть URI со схемой "https", как указано в разделе 2.7.2 [RFC7230]. Во втором случае он ДОЛЖЕН (MUST) быть URN, как указано в [RFC8141].

   Ниже приведён пример содержимого ресурса объекта запроса, на который может ссылаться "request_uri" (переносы строк внутри значений добавлены только для отображения):

     eyJhbGciOiJSUzI1NiIsImtpZCI6ImsyYmRjIn0.ewogICAgImlzcyI6ICJzNkJoZF
     JrcXQzIiwKICAgICJhdWQiOiAiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20iLAog
     ICAgInJlc3BvbnNlX3R5cGUiOiAiY29kZSBpZF90b2tlbiIsCiAgICAiY2xpZW50X2
     lkIjogInM2QmhkUmtxdDMiLAogICAgInJlZGlyZWN0X3VyaSI6ICJodHRwczovL2Ns
     aWVudC5leGFtcGxlLm9yZy9jYiIsCiAgICAic2NvcGUiOiAib3BlbmlkIiwKICAgIC
     JzdGF0ZSI6ICJhZjBpZmpzbGRraiIsCiAgICAibm9uY2UiOiAibi0wUzZfV3pBMk1q
     IiwKICAgICJtYXhfYWdlIjogODY0MDAKfQ.Nsxa_18VUElVaPjqW_ToI1yrEJ67BgK
     b5xsuZRVqzGkfKrOIX7BCx0biSxYGmjK9KJPctH1OC0iQJwXu5YVY-vnW0_PLJb1C2
     HG-ztVzcnKZC2gE4i0vgQcpkUOCpW3SEYXnyWnKzuKzqSb1wAZALo5f89B_p6QA6j6
     JwBSRvdVsDPdulW8lKxGTbH82czCaQ50rLAg3EYLYaCb4ik4I1zGXE4fvim9FIMs8O
     CMmzwIB5S-ujFfzwFjoyuPEV4hJnoVUmXR_W9typPf846lGwA8h9G9oNTIuX8Ft2jf
     pnZdFmLg3_wr3Wa5q3a-lfbgF3S9H_8nN3j1i7tLR_5Nz-g

5.2.1.  URI, ссылающийся на объект запроса

   Клиент сохраняет ресурс объекта запроса локально или удалённо по URI, доступному серверу авторизации. Такая возможность может предоставляться сервером авторизации или доверенной третьей стороной. Например, сервер авторизации может предоставлять URL, по которому клиент отправляет объект запроса методом POST и получает URI запроса. Этот URI является URI объекта запроса — "request_uri".

   Объект запроса может включать значения, которые должны раскрываться только серверу авторизации. Поэтому "request_uri" ДОЛЖЕН (MUST) обладать энтропией, соответствующей сроку его действия, чтобы URI нельзя было угадать, если ресурс доступен для общедоступного получения. Рекомендации приведены в разделе 5.1.4.2.2 [RFC6819] и в "Good Practices for Capability URLs" [CapURLs]. СЛЕДУЕТ (RECOMMENDED) удалять "request_uri" по истечении разумного срока, если не приняты меры контроля доступа.

   Ниже приведён пример значения URI объекта запроса (переносы строк внутри значений добавлены только для отображения). В этом примере объект запроса размещается в доверенном стороннем сервисе.

     https://tfp.example.org/request.jwt/
       GkurKxf5T0Y-mnPFCHqWOMiZi4VS138cQO_V7PZHAdM

5.2.2.  Запрос с использованием параметра запроса "request_uri"

   Клиент отправляет запрос авторизации в конечную точку авторизации.

   Ниже приведён пример запроса авторизации с использованием параметра "request_uri" (переносы строк внутри значений добавлены только для отображения):

     https://server.example.com/authorize?
       client_id=s6BhdRkqt3
       &request_uri=https%3A%2F%2Ftfp.example.org%2Frequest.jwt
       %2FGkurKxf5T0Y-mnPFCHqWOMiZi4VS138cQO_V7PZHAdM

5.2.3.  Получение объекта запроса сервером авторизации

   При получении запроса сервер авторизации ДОЛЖЕН (MUST) отправить HTTP-запрос "GET" по "request_uri", чтобы получить объект запроса, на который тот ссылается, если только объект запроса не хранится таким образом, что сервер может безопасно получить его с помощью других механизмов и разобрать для восстановления параметров запроса авторизации.

   Ниже приведён пример этого процесса получения. В этом примере объект запроса размещается в доверенном стороннем сервисе.

   GET /request.jwt/GkurKxf5T0Y-mnPFCHqWOMiZi4VS138cQO_V7PZHAdM HTTP/1.1
   Host: tfp.example.org

   Ниже приведён пример ответа на запрос получения:

     HTTP/1.1 200 OK
     Date: Thu, 20 Aug 2020 23:52:39 GMT
     Server: Apache/2.4.43 (tfp.example.org)
     Content-type: application/oauth-authz-req+jwt
     Content-Length: 797
     Last-Modified: Wed, 19 Aug 2020 23:52:32 GMT

     eyJhbGciOiJSUzI1NiIsImtpZCI6ImsyYmRjIn0.ewogICAgImlzcyI6ICJzNkJoZF
     JrcXQzIiwKICAgICJhdWQiOiAiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20iLAog
     ICAgInJlc3BvbnNlX3R5cGUiOiAiY29kZSBpZF90b2tlbiIsCiAgICAiY2xpZW50X2
     lkIjogInM2QmhkUmtxdDMiLAogICAgInJlZGlyZWN0X3VyaSI6ICJodHRwczovL2Ns
     aWVudC5leGFtcGxlLm9yZy9jYiIsCiAgICAic2NvcGUiOiAib3BlbmlkIiwKICAgIC
     JzdGF0ZSI6ICJhZjBpZmpzbGRraiIsCiAgICAibm9uY2UiOiAibi0wUzZfV3pBMk1q
     IiwKICAgICJtYXhfYWdlIjogODY0MDAKfQ.Nsxa_18VUElVaPjqW_ToI1yrEJ67BgK
     b5xsuZRVqzGkfKrOIX7BCx0biSxYGmjK9KJPctH1OC0iQJwXu5YVY-vnW0_PLJb1C2
     HG-ztVzcnKZC2gE4i0vgQcpkUOCpW3SEYXnyWnKzuKzqSb1wAZALo5f89B_p6QA6j6
     JwBSRvdVsDPdulW8lKxGTbH82czCaQ50rLAg3EYLYaCb4ik4I1zGXE4fvim9FIMs8O
     CMmzwIB5S-ujFfzwFjoyuPEV4hJnoVUmXR_W9typPf846lGwA8h9G9oNTIuX8Ft2jf
     pnZdFmLg3_wr3Wa5q3a-lfbgF3S9H_8nN3j1i7tLR_5Nz-g

6.  Проверка запросов на основе JWT

6.1.  Объект запроса, зашифрованный с использованием JWE

   Если объект запроса зашифрован, сервер авторизации ДОЛЖЕН (MUST) расшифровать JWT в соответствии со спецификацией JSON Web Encryption [RFC7516].

   Результатом является подписанный объект запроса.

   Если расшифрование завершается неудачей, сервер авторизации ДОЛЖЕН (MUST) вернуть клиенту ошибку "invalid_request_object" в ответ на запрос авторизации.

6.2.  Объект запроса, подписанный с использованием JWS

   Сервер авторизации ДОЛЖЕН (MUST) проверить подпись объекта запроса, подписанного с использованием JWS [RFC7515]. Если присутствует параметр заголовка "kid", ДОЛЖЕН (MUST) использоваться ключ, идентифицируемый этим параметром, и этот ключ ДОЛЖЕН (MUST) быть связан с клиентом. Подпись ДОЛЖНА (MUST) проверяться с использованием ключа, связанного с клиентом, и алгоритма, указанного в параметре заголовка "alg". Проверка алгоритма ДОЛЖНА (MUST) выполняться, как указано в разделах 3.1 и 3.2 [RFC8725].

   Если ключ не связан с клиентом или проверка подписи завершается неудачей, сервер авторизации ДОЛЖЕН (MUST) вернуть клиенту ошибку "invalid_request_object" в ответ на запрос авторизации.

6.3.  Формирование и проверка набора параметров запроса
   Сервер авторизации ДОЛЖЕН (MUST) извлечь набор параметров запроса авторизации из значения объекта запроса (Request Object). Сервер авторизации ДОЛЖЕН (MUST) использовать только параметры из объекта запроса, даже если тот же параметр передан в параметре строки запроса. Значения идентификатора клиента в параметре запроса "client_id" и в утверждении "client_id" объекта запроса ДОЛЖНЫ (MUST) быть идентичными. Затем сервер авторизации проверяет запрос, как указано в OAuth 2.0 [RFC6749].

   Если проверка идентификатора клиента или проверка запроса завершается неудачно, сервер авторизации ДОЛЖЕН (MUST) вернуть клиенту ошибку в ответ на запрос авторизации, как указано в разделе 5.2 [RFC6749] (OAuth 2.0).

7.  Ответ сервера авторизации

   Ответ сервера авторизации создаётся и отправляется клиенту согласно разделу 4 [RFC6749] (OAuth 2.0).

   Кроме того, в этом документе используются следующие дополнительные значения ошибок:

   invalid_request_uri
      "request_uri" в запросе авторизации возвращает ошибку или содержит недопустимые данные.

   invalid_request_object
      Параметр запроса содержит недопустимый объект запроса.

   request_not_supported
      Сервер авторизации не поддерживает использование параметра "request".

   request_uri_not_supported
      Сервер авторизации не поддерживает использование параметра "request_uri".

8.  Требования к TLS

   Реализации клиентов, поддерживающие метод URI объекта запроса, ДОЛЖНЫ (MUST) поддерживать TLS, следуя "Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS)" [RFC7525].

   Для защиты от раскрытия информации и несанкционированного изменения ДОЛЖНА (MUST) применяться защита конфиденциальности с использованием TLS с набором шифров, обеспечивающим защиту конфиденциальности и целостности.

   HTTP-клиенты также ДОЛЖНЫ (MUST) проверять сертификат TLS-сервера с использованием DNS-ID [RFC6125], чтобы избежать атак посредника. Здесь применяются правила и рекомендации, определённые в [RFC6125], со следующими оговорками:

   *  Поддержка типа идентификатора DNS-ID (то есть идентификатора dNSName в расширении subjectAltName) ДОЛЖНА (REQUIRED) обеспечиваться. Центры сертификации, выдающие серверные сертификаты, ДОЛЖНЫ (MUST) поддерживать тип идентификатора DNS-ID, и идентификатор типа DNS-ID ДОЛЖЕН (MUST) присутствовать в серверных сертификатах.

   *  DNS-имена в серверных сертификатах МОГУТ (MAY) содержать подстановочный символ "*".

   *  Клиенты НЕ ДОЛЖНЫ (MUST NOT) использовать идентификаторы CN-ID; поле Common Name (поле CN) может присутствовать в имени субъекта серверного сертификата, но НЕ ДОЛЖНО (MUST NOT) использоваться для аутентификации в рамках правил, описанных в [RFC7525].

   *  SRV-ID и URI-ID, описанные в разделе 6.5 [RFC6125], НЕ ДОЛЖНЫ (MUST NOT) использоваться для сравнения.

9.  Вопросы IANA

9.1.  Регистрация параметров OAuth

   Поскольку объект запроса является JWT, основные утверждения JWT нельзя использовать в объекте запроса ни для каких целей, кроме предписанных JWT. Поэтому они зарегистрированы как параметры запроса авторизации OAuth, чтобы будущие расширения OAuth не использовали их с другими значениями.

   Эта спецификация добавляет следующие значения в реестр "OAuth Parameters" [IANA.OAuth.Parameters], учреждённый [RFC6749].

   Имя:  "iss"
   Место использования параметра:  запрос авторизации
   Ответственный за изменения:  IETF
   Документы спецификации:  Этот документ и раздел 4.1.1 [RFC7519].

   Имя:  "sub"
   Место использования параметра:  запрос авторизации
   Ответственный за изменения:  IETF
   Документы спецификации:  Этот документ и раздел 4.1.2 [RFC7519].

   Имя:  "aud"
   Место использования параметра:  запрос авторизации
   Ответственный за изменения:  IETF
   Документы спецификации:  Этот документ и раздел 4.1.3 [RFC7519].

   Имя:  "exp"
   Место использования параметра:  запрос авторизации
   Ответственный за изменения:  IETF
   Документы спецификации:  Этот документ и раздел 4.1.4 [RFC7519].

   Имя:  "nbf"
   Место использования параметра:  запрос авторизации
   Ответственный за изменения:  IETF
   Документы спецификации:  Этот документ и раздел 4.1.5 [RFC7519].

   Имя:  "iat"
   Место использования параметра:  запрос авторизации
   Ответственный за изменения:  IETF
   Документы спецификации:  Этот документ и раздел 4.1.6 [RFC7519].

   Имя:  "jti"
   Место использования параметра:  запрос авторизации
   Ответственный за изменения:  IETF
   Документы спецификации:  Этот документ и раздел 4.1.7 [RFC7519].

9.2.  Реестр метаданных сервера авторизации OAuth

   Эта спецификация добавляет следующее значение в реестр "OAuth Authorization Server Metadata" [IANA.OAuth.Parameters], учреждённый [RFC8414].

   Имя метаданных:  "require_signed_request_object"
   Описание метаданных:  Указывает, где запрос авторизации необходимо защитить в виде объекта запроса и передать через "request" или "request_uri parameter".
   Ответственный за изменения:  IETF
   Документы спецификации:  Раздел 10.5 этого документа.

9.3.  Реестр метаданных динамической регистрации клиентов OAuth

   Эта спецификация добавляет следующее значение в реестр "OAuth Dynamic Client Registration Metadata" [IANA.OAuth.Parameters], учреждённый [RFC7591].

   Имя метаданных:  "require_signed_request_object"
   Описание метаданных:  Указывает, где запрос авторизации необходимо защитить в виде объекта запроса и передать через "request" или "request_uri parameter".
   Ответственный за изменения:  IETF
   Документы спецификации:  Раздел 10.5 этого документа.

9.4.  Регистрация типа мультимедиа

9.4.1.  Содержимое реестра

   Этот раздел регистрирует тип мультимедиа "application/oauth-authz-req+jwt" [RFC2046] в реестре "Media Types" [IANA.MediaTypes] способом, описанным в [RFC6838]. Его можно использовать для указания того, что содержимое является JWT, содержащим утверждения объекта запроса.

   Имя типа:  application
   Имя подтипа:  oauth-authz-req+jwt
   Обязательные параметры:  N/A
   Необязательные параметры:  N/A
   Вопросы кодирования:  binary; объект запроса является JWT; значения JWT кодируются как последовательность значений, закодированных с помощью base64url (некоторые из них могут быть пустой строкой), разделённых символами точки (".").
   Вопросы безопасности:  См. раздел 10 RFC 9101
   Вопросы совместимости:  N/A
   Опубликованная спецификация:  Раздел 4 RFC 9101
   Приложения, использующие этот тип мультимедиа:  Приложения, использующие объекты запроса для выполнения запроса авторизации OAuth 2.0
   Вопросы идентификаторов фрагментов:  N/A
   Дополнительная информация:
      Устаревшие альтернативные имена этого типа:  N/A
      Магические числа:  N/A
      Расширения файлов:  N/A
      Коды типов файлов Macintosh:  N/A
   Контактное лицо и адрес электронной почты для получения дополнительной информации:
      Nat Sakimura <nat@nat.consulting>
   Предполагаемое использование:  COMMON
   Ограничения использования:  none
   Автор:  Nat Sakimura <nat@nat.consulting>
   Ответственный за изменения:  IETF
   Предварительная регистрация?  No

10.  Вопросы безопасности

   Помимо всех вопросов безопасности, рассмотренных в OAuth 2.0 [RFC6819], необходимо учитывать вопросы безопасности, изложенные в [RFC7515], [RFC7516], [RFC7518] и [RFC8725]. Кроме того, существует ряд научных работ, таких как [BASIN], которые дают полезное представление о свойствах безопасности протоколов, подобных OAuth.

   С учётом вышеизложенного этот документ рекомендует принимать во внимание следующие соображения безопасности.

10.1.  Выбор алгоритмов

   При отправке объекта запроса авторизации через параметр "request" он ДОЛЖЕН (MUST) быть либо подписан с использованием JWS [RFC7515], либо подписан, а затем зашифрован с использованием соответственно JWS [RFC7515] и JWE [RFC7516], с применением алгоритмов, считающихся подходящими на тот момент.

10.2.  Аутентификация источника запроса

   Источник запроса авторизации ДОЛЖЕН (MUST) всегда проверяться. Это можно сделать несколькими способами:

   (a)  Проверка подписи JWS объекта запроса.

   (b)  Проверка правильности симметричного ключа для шифрования JWE, если JWE использует симметричное шифрование. Однако обратите внимание: при использовании шифрования с открытым ключом шифрование не обеспечивает аутентификацию источника, поскольку любая сторона может выполнить шифрование с помощью открытого ключа.

   (c)  Проверка идентификационных данных TLS-сервера для URI объекта запроса. В этом случае сервер авторизации ДОЛЖЕН (MUST) знать по внеполосному каналу, что клиент использует URI объекта запроса и что TLS-сертификат распространяется только на этого клиента. В общем случае этот метод ненадёжен.

   (d)  Когда сервер авторизации реализует службу, возвращающую URI объекта запроса в обмен на объект запроса, сервер авторизации ДОЛЖЕН (MUST) выполнять аутентификацию клиента, чтобы принять объект запроса и связать идентификатор клиента с предоставляемым URI объекта запроса. Он ДОЛЖЕН (MUST) проверять подпись согласно пункту (a). Поскольку URI объекта запроса может быть использован повторно, срок действия URI объекта запроса ДОЛЖЕН (MUST) быть коротким, и предпочтительно, чтобы этот URI использовался однократно. Энтропия URI объекта запроса ДОЛЖНА (MUST) быть достаточно большой. То, насколько коротким должен быть срок действия и какой должна быть энтропия URI объекта запроса, зависит от расчёта риска на основе ценности защищаемого ресурса. Общей рекомендацией для срока действия было бы значение менее минуты, а URI объекта запроса должен включать криптографически случайное значение длиной 128 бит или более на момент написания этой спецификации.

   (e)  Когда доверенная сторонняя служба возвращает URI объекта запроса в обмен на объект запроса, она ДОЛЖНА (MUST) проверять подпись согласно пункту (a). Кроме того, сервер авторизации ДОЛЖЕН (MUST) пользоваться доверием сторонней службы и ДОЛЖЕН (MUST) знать по внеполосному каналу, что клиент также пользуется её доверием.

10.3.  Явное указание конечных точек

   Хотя эта спецификация этого не требует, исследования, такие как [BASIN], указывают, что хорошей практикой является явное указание предполагаемых конечных точек взаимодействия и позиции сообщения в последовательности способом, позволяющим обнаружить несанкционированное изменение, чтобы намерение инициатора было однозначным. Согласно этой спецификации СЛЕДУЕТ (RECOMMENDED) использовать эту практику для следующих конечных точек, определённых в [RFC6749], [RFC6750] и [RFC8414]:

   (a)  Защищённые ресурсы ("protected_resources")

   (b)  Конечная точка авторизации ("authorization_endpoint")

   (c)  URI перенаправления ("redirect_uri")

   (d)  Конечная точка токенов ("token_endpoint")

   Кроме того, если используется динамическое обнаружение, эта практика также применяется к конечным точкам, связанным с обнаружением.

   В [RFC6749] URI перенаправления включён в запрос авторизации, а остальные конечные точки — нет. В результате то же самое относится к объекту запроса авторизации.

10.4.  Риски, связанные с request_uri

   Введение "request_uri" создаёт несколько возможностей для атак. Дополнительную информацию о рисках, связанных с URI, см. в соображениях безопасности в разделе 7 [RFC3986].

10.4.1.  DDoS-атака на сервер авторизации

   Группа злонамеренных клиентов может осуществить DoS-атаку на сервер авторизации, указав в "request_uri" URI, который возвращает чрезвычайно большое содержимое или отвечает чрезвычайно медленно. При такой атаке сервер может исчерпать свои ресурсы и начать давать сбои.

   Аналогично, злонамеренный клиент может указать значение "request_uri", которое само указывает на URI запроса авторизации, использующего "request_uri", чтобы вызвать рекурсивное обращение.

   Чтобы предотвратить успех такой атаки, серверу следует a) проверять, что значение параметра "request_uri" не указывает на неожиданное местоположение, b) проверять, что тип мультимедиа ответа — "application/oauth-authz-req+jwt", c) реализовать ограничение времени ожидания при получении содержимого "request_uri" и d) не выполнять рекурсивные запросы GET по "request_uri".

10.4.2.  Перезапись URI запроса

   Значение "request_uri" не подписано; поэтому злоумышленник, осуществляющий атаку man-in-the-browser, может его изменить. Из-за этого возникает несколько возможностей для атак. Например, a) злоумышленник может создать другой файл, на который указывает переписанный URI, что позволяет запросить дополнительную область доступа, или b) злоумышленник может осуществить DoS-атаку на сайт жертвы, установив в качестве значения "request_uri" URI жертвы.

   Чтобы предотвратить успех такой атаки, серверу следует a) проверять, что значение параметра "request_uri" не указывает на неожиданное местоположение, b) проверять, что тип мультимедиа ответа — "application/oauth-authz-req+jwt", и c) реализовать ограничение времени ожидания при получении содержимого "request_uri".

10.5.  Атака с понижением уровня защиты

   Если протокол, используемый клиентом и сервером, не ограничен исключительно использованием OAuth JWT-Secured Authorization Request (JAR), злоумышленник может использовать запросы RFC 6749, чтобы обойти всю защиту, предоставляемую этой спецификацией.

   Чтобы предотвратить атаки такого рода, эта спецификация определяет новые значения метаданных клиента и метаданных сервера с одинаковым именем "require_signed_request_object"; оба значения имеют логический тип.

   Когда это значение в метаданных клиента равно "true", сервер ДОЛЖЕН (MUST) отклонять запрос авторизации от клиента, который не соответствует этой спецификации. Он также ДОЛЖЕН (MUST) отклонять запрос, если объект запроса использует значение "alg", равное "none", когда это значение метаданных сервера равно "true". Если значение не указано, по умолчанию используется "false".
   Когда его значение в метаданных сервера равно "true", сервер ДОЛЖЕН (MUST) отклонять запрос авторизации от любого клиента, который не соответствует этой спецификации. Он также ДОЛЖЕН (MUST) отклонять запрос, если объект запроса использует значение "none" для "alg". Если значение не указано, по умолчанию используется "false".

   Обратите внимание: даже если значения метаданных "require_signed_request_object" отсутствуют, клиент МОЖЕТ (MAY) использовать подписанные объекты запроса при условии, что существуют алгоритмы подписи, поддерживаемые и клиентом, и сервером. Использование метаданных алгоритмов подписи описано в разделе 4.

10.6.  Соображения безопасности TLS

   Актуальные соображения безопасности приведены в "Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS)" [RFC7525]. Они заменяют рекомендации по версии TLS в OAuth 2.0 [RFC6749].

10.7.  Несовпадения параметров

   Поскольку значения параметров OAuth передаются в двух разных местах — как обычные параметры OAuth и как утверждения объекта запроса, — реализации должны защищаться от атак, которые могут использовать несовпадающие значения параметров для получения непредусмотренных результатов. Именно поэтому два значения идентификатора клиента ДОЛЖНЫ (MUST) совпадать, должны использоваться только значения параметров из объекта запроса, а ни "request", ни "request_uri" не могут присутствовать в объекте запроса.

10.8.  Смешение JWT разных назначений

   Как описано в разделе 2.8 [RFC8725], злоумышленники могут попытаться использовать JWT, выпущенный для одной цели, в контексте, для которого он не предназначался. Описанные меры противодействия этим атакам могут применяться к объектам запроса.

   Один из способов, которым злоумышленник может попытаться использовать объект запроса не по назначению, — попытаться применить его как JWT для аутентификации клиента, как описано в разделе 2.2 [RFC7523]. Простой способ предотвратить это — никогда не использовать идентификатор клиента в качестве значения "sub" в объекте запроса.

   Другой способ предотвратить смешение JWT разных назначений — использовать явное указание типа, как описано в разделе 3.11 [RFC8725]. Чтобы явно указать тип объекта запроса, в него включают параметр заголовка "typ" со значением "oauth-authz-req+jwt" (зарегистрированным в разделе 9.4.1). Однако обратите внимание: требование явно указывать тип объектов запроса на существующих серверах авторизации нарушит работу большинства существующих развёртываний, поскольку существующие клиенты уже широко используют объекты запроса без указания типа, особенно с OpenID Connect [OpenID.Core]. Тем не менее требование явно указывать тип было бы хорошей идеей для новых профилей развёртывания OAuth, в которых совместимость с существующими развёртываниями не учитывается.

   Наконец, ещё один способ предотвратить смешение JWT разных назначений — использовать такой порядок управления ключами, при котором ключи, используемые для подписи объектов запроса, можно отличить от ключей, используемых для других целей. Тогда, если противник попытается использовать объект запроса не по назначению в другом контексте, возникнет несовпадение ключей, которое сорвёт атаку.

11.  Соображения неприкосновенности частной жизни

   Когда клиенту предоставляется доступ к защищённому ресурсу, содержащему персональные данные, и клиенту, и серверу авторизации необходимо соблюдать принципы неприкосновенности частной жизни. В "Privacy Considerations for Internet Protocols" [RFC6973] даны отличные рекомендации по улучшению проектирования и реализации протоколов. Перечисленные в нём положения следует соблюдать.

   Большинство положений применимы к "The OAuth 2.0 Authorization Framework" [RFC6749] и "The OAuth 2.0 Authorization Framework: Bearer Token Usage" [RFC6750] и не являются специфичными для этой спецификации. Далее отмечаются только положения, специфичные для этой спецификации.

11.1.  Ограничение сбора

   Когда клиенту предоставляется доступ к защищённому ресурсу, содержащему персональные данные, клиенту СЛЕДУЕТ (SHOULD) ограничивать сбор персональных данных теми данными, сбор которых допускается применимым законодательством и строго необходим для указанной цели или целей.

   Пользователю часто трудно выяснить, действительно ли запрашиваемые персональные данные строго необходимы. Доверенная сторонняя служба может помочь пользователю, изучив запрос клиента, сопоставив его с предполагаемой обработкой данных клиентом и сертифицировав запрос. После сертификации клиент при выполнении запроса авторизации может отправить запрос авторизации доверенной сторонней службе, чтобы получить URI объекта запроса. Этот процесс состоит из двух шагов:

   (1)  (Процесс сертификации) Доверенная сторонняя служба изучает бизнес-процесс клиента и определяет, какие утверждения ему нужны; это и есть процесс сертификации. После сертификации клиенту выдаются учётные данные клиента для аутентификации при отправке объектов запроса доверенной сторонней службе с целью получения "request_uri".

   (2)  (Процесс преобразования) Клиент использует полученные им учётные данные клиента для отправки объекта запроса доверенной сторонней службе с целью получения "request_uri". Доверенная сторонняя служба также проверяет, что объект запроса соответствует утверждениям, на получение которых клиент имеет право согласно предыдущему шагу.

   Получив такой URI объекта запроса в запросе авторизации, сервер авторизации сначала проверяет, что компонент authority URI объекта запроса является допустимым для доверенной сторонней службы. Затем сервер авторизации отправляет HTTP-запрос GET по URI объекта запроса. При установлении соединения сервер авторизации ДОЛЖЕН (MUST) проверить, что идентификационные данные сервера, представленные в сертификате TLS, действительны для URI объекта запроса. Затем сервер авторизации может получить объект запроса, содержащий "client_id", который представляет клиента.

   Экран согласия ДОЛЖЕН (MUST) указывать клиента, и ему СЛЕДУЕТ (SHOULD) указывать, что запрос проверен доверенной сторонней службой на соответствие принципу ограничения сбора.

11.2.  Ограничение раскрытия

11.2.1.  Раскрытие запроса

   Эта спецификация допускает параметры расширения. Они могут включать потенциально конфиденциальную информацию. Поскольку параметры строки запроса URI могут утекать различными путями, прежде всего через referrer и историю браузера, если запрос авторизации содержит потенциально конфиденциальный параметр, клиенту СЛЕДУЕТ (SHOULD) зашифровать объект запроса с помощью JWE [RFC7516].

   При использовании метода URI объекта запроса, если объект запроса содержит информацию, позволяющую идентифицировать личность, или конфиденциальную информацию, "request_uri" СЛЕДУЕТ (SHOULD) использовать только один раз и назначать ему короткий срок действия, и он ДОЛЖЕН (MUST) обладать достаточной энтропией для применимых политик безопасности, если только сам объект запроса не зашифрован с помощью JWE [RFC7516]. То, насколько коротким должен быть срок действия и какой должна быть энтропия URI объекта запроса, зависит от расчёта риска, основанного на ценности защищаемого ресурса. Общая рекомендация по сроку действия — менее одной минуты; на момент написания этой спецификации URI объекта запроса должен включать криптографически случайное значение длиной не менее 128 бит.

11.2.2.  Отслеживание с использованием URI объекта запроса

   Даже если защищённый ресурс не содержит информации, позволяющей идентифицировать личность, иногда пользователя можно идентифицировать через URI объекта запроса, если используются постоянные статические URI объектов запроса, закреплённые за отдельными пользователями. Третья сторона может обнаружить такой URI через историю браузера и т. п. и начать сопоставлять действия пользователя с его помощью. В некотором смысле это тоже раскрытие данных, и его следует избегать.

   Поэтому следует избегать постоянных URI объектов запроса, закреплённых за отдельными пользователями. Одна из альтернатив — одноразовые URI объектов запроса.

12.  Ссылки

12.1.  Нормативные ссылки

   [RFC2119]  Bradner, S., "Key words for use in RFCs to Indicate
              Requirement Levels", BCP 14, RFC 2119,
              DOI 10.17487/RFC2119, March 1997,
              <https://www.rfc-editor.org/info/rfc2119>.

   [RFC3629]  Yergeau, F., "UTF-8, a transformation format of ISO
              10646", STD 63, RFC 3629, DOI 10.17487/RFC3629, November
              2003, <https://www.rfc-editor.org/info/rfc3629>.

   [RFC3986]  Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform
              Resource Identifier (URI): Generic Syntax", STD 66,
              RFC 3986, DOI 10.17487/RFC3986, January 2005,
              <https://www.rfc-editor.org/info/rfc3986>.

   [RFC6125]  Saint-Andre, P. and J. Hodges, "Representation and
              Verification of Domain-Based Application Service Identity
              within Internet Public Key Infrastructure Using X.509
              (PKIX) Certificates in the Context of Transport Layer
              Security (TLS)", RFC 6125, DOI 10.17487/RFC6125, March
              2011, <https://www.rfc-editor.org/info/rfc6125>.

   [RFC6749]  Hardt, D., Ed., "The OAuth 2.0 Authorization Framework",
              RFC 6749, DOI 10.17487/RFC6749, October 2012,
              <https://www.rfc-editor.org/info/rfc6749>.

   [RFC6750]  Jones, M. and D. Hardt, "The OAuth 2.0 Authorization
              Framework: Bearer Token Usage", RFC 6750,
              DOI 10.17487/RFC6750, October 2012,
              <https://www.rfc-editor.org/info/rfc6750>.

   [RFC7230]  Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer
              Protocol (HTTP/1.1): Message Syntax and Routing",
              RFC 7230, DOI 10.17487/RFC7230, June 2014,
              <https://www.rfc-editor.org/info/rfc7230>.

   [RFC7515]  Jones, M., Bradley, J., and N. Sakimura, "JSON Web
              Signature (JWS)", RFC 7515, DOI 10.17487/RFC7515, May
              2015, <https://www.rfc-editor.org/info/rfc7515>.

   [RFC7516]  Jones, M. and J. Hildebrand, "JSON Web Encryption (JWE)",
              RFC 7516, DOI 10.17487/RFC7516, May 2015,
              <https://www.rfc-editor.org/info/rfc7516>.

   [RFC7518]  Jones, M., "JSON Web Algorithms (JWA)", RFC 7518,
              DOI 10.17487/RFC7518, May 2015,
              <https://www.rfc-editor.org/info/rfc7518>.

   [RFC7519]  Jones, M., Bradley, J., and N. Sakimura, "JSON Web Token
              (JWT)", RFC 7519, DOI 10.17487/RFC7519, May 2015,
              <https://www.rfc-editor.org/info/rfc7519>.

   [RFC7525]  Sheffer, Y., Holz, R., and P. Saint-Andre,
              "Recommendations for Secure Use of Transport Layer
              Security (TLS) and Datagram Transport Layer Security
              (DTLS)", BCP 195, RFC 7525, DOI 10.17487/RFC7525, May
              2015, <https://www.rfc-editor.org/info/rfc7525>.

   [RFC8141]  Saint-Andre, P. and J. Klensin, "Uniform Resource Names
              (URNs)", RFC 8141, DOI 10.17487/RFC8141, April 2017,
              <https://www.rfc-editor.org/info/rfc8141>.

   [RFC8174]  Leiba, B., "Ambiguity of Uppercase vs Lowercase in RFC
              2119 Key Words", BCP 14, RFC 8174, DOI 10.17487/RFC8174,
              May 2017, <https://www.rfc-editor.org/info/rfc8174>.

   [RFC8259]  Bray, T., Ed., "The JavaScript Object Notation (JSON) Data
              Interchange Format", STD 90, RFC 8259,
              DOI 10.17487/RFC8259, December 2017,
              <https://www.rfc-editor.org/info/rfc8259>.

   [RFC8414]  Jones, M., Sakimura, N., and J. Bradley, "OAuth 2.0
              Authorization Server Metadata", RFC 8414,
              DOI 10.17487/RFC8414, June 2018,
              <https://www.rfc-editor.org/info/rfc8414>.

12.2.  Информационные ссылки

   [BASIN]    Basin, D., Cremers, C., and S. Meier, "Provably Repairing
              the ISO/IEC 9798 Standard for Entity Authentication",
              Journal of Computer Security - Security and Trust
              Principles, Volume 21, Issue 6, pp. 817-846, November
              2013,
              <https://www.cs.ox.ac.uk/people/cas.cremers/downloads/
              papers/BCM2012-iso9798.pdf>.

   [CapURLs]  Tennison, J., Ed., "Good Practices for Capability URLs",
              W3C First Public Working Draft, 18 February 2014,
              <https://www.w3.org/TR/capability-urls/>.

   [IANA.JWT.Claims]
              IANA, "JSON Web Token (JWT)",
              <https://www.iana.org/assignments/jwt>.

   [IANA.MediaTypes]
              IANA, "Media Types",
              <https://www.iana.org/assignments/media-types>.

   [IANA.OAuth.Parameters]
              IANA, "OAuth Parameters",
              <https://www.iana.org/assignments/oauth-parameters>.

   [OpenID.Core]
              Sakimura, N., Bradley, J., Jones, M.B., de Medeiros, B.,
              and C. Mortimore, "OpenID Connect Core 1.0 incorporating
              errata set 1", OpenID Foundation Standards, 8 November
              2014,
              <http://openid.net/specs/openid-connect-core-1_0.html>.

   [RFC2046]  Freed, N. and N. Borenstein, "Multipurpose Internet Mail
              Extensions (MIME) Part Two: Media Types", RFC 2046,
              DOI 10.17487/RFC2046, November 1996,
              <https://www.rfc-editor.org/info/rfc2046>.

   [RFC6819]  Lodderstedt, T., Ed., McGloin, M., and P. Hunt, "OAuth 2.0
              Threat Model and Security Considerations", RFC 6819,
              DOI 10.17487/RFC6819, January 2013,
              <https://www.rfc-editor.org/info/rfc6819>.

   [RFC6838]  Freed, N., Klensin, J., and T. Hansen, "Media Type
              Specifications and Registration Procedures", BCP 13,
              RFC 6838, DOI 10.17487/RFC6838, January 2013,
              <https://www.rfc-editor.org/info/rfc6838>.

   [RFC6973]  Cooper, A., Tschofenig, H., Aboba, B., Peterson, J.,
              Morris, J., Hansen, M., and R. Smith, "Privacy
              Considerations for Internet Protocols", RFC 6973,
              DOI 10.17487/RFC6973, July 2013,
              <https://www.rfc-editor.org/info/rfc6973>.
   [RFC7523]  Jones, M., Campbell, B., and C. Mortimore, "JSON Web Token
              (JWT) Profile for OAuth 2.0 Client Authentication and
              Authorization Grants", RFC 7523, DOI 10.17487/RFC7523, May
              2015, <https://www.rfc-editor.org/info/rfc7523>.

   [RFC7591]  Richer, J., Ed., Jones, M., Bradley, J., Machulak, M., and
              P. Hunt, "OAuth 2.0 Dynamic Client Registration Protocol",
              RFC 7591, DOI 10.17487/RFC7591, July 2015,
              <https://www.rfc-editor.org/info/rfc7591>.

   [RFC8725]  Sheffer, Y., Hardt, D., and M. Jones, "JSON Web Token Best
              Current Practices", BCP 225, RFC 8725,
              DOI 10.17487/RFC8725, February 2020,
              <https://www.rfc-editor.org/info/rfc8725>.

Благодарности

   Следующие люди внесли вклад в создание этого документа в рамках
   рабочей группы OAuth и в других ролях в IETF. (Указана принадлежность
   к организациям на момент внесения вклада.)

   Annabelle Backman (Amazon), Dirk Balfanz (Google), Sergey Beryozkin,
   Ben Campbell (в качестве AD), Brian Campbell (Ping Identity), Roman
   Danyliw (в качестве AD), Martin Duke (в качестве AD), Vladimir
   Dzhuvinov (Connect2id), Lars Eggert (в качестве AD), Joel Halpern
   (в качестве GENART), Benjamin Kaduk (в качестве AD), Stephen Kent
   (в качестве SECDIR), Murray Kucherawy (в качестве AD), Warren Kumari
   (в качестве OPSDIR), Watson Ladd (в качестве SECDIR), Torsten
   Lodderstedt (yes.com), Jim Manico, James H. Manger (Telstra), Kathleen
   Moriarty (в качестве AD), Axel Nennker (Deutsche Telecom), John Panzer
   (Google), Francesca Palombini (в качестве AD), David Recordon
   (Facebook), Marius Scurtescu (Google), Luke Shepard (Facebook), Filip
   Skokan (Auth0), Hannes Tschofenig (ARM), Éric Vyncke (в качестве AD)
   и Robert Wilton (в качестве AD).

   Следующие люди внесли вклад в создание этого документа посредством
   работы над OpenID Connect Core 1.0 [OpenID.Core].

   Brian Campbell (Ping Identity), George Fletcher (AOL), Ryo Itou
   (Mixi), Edmund Jay (Illumila), Breno de Medeiros (Google), Hideki
   Nara (TACT) и Justin Richer (MITRE).

Адреса авторов

   Nat Sakimura
   NAT.Consulting
   2-22-17 Naka
   Kunitachi, Tokyo 186-0004
   Japan

   Phone: +81-42-580-7401
   Email: nat@nat.consulting
   URI:   https://nat.sakimura.org/


   John Bradley
   Yubico
   Sucursal Talagante
   Casilla 177
   Talagante
   RM
   Chile

   Phone: +1.202.630.5272
   Email: rfc9101@ve7jtb.com
   URI:   http://www.thread-safe.com/


   Michael B. Jones
   Microsoft
   One Microsoft Way
   Redmond, Washington 98052
   United States of America

   Email: mbj@microsoft.com
   URI:   https://self-issued.info/
Оригинал (EN)



Internet Engineering Task Force (IETF)                       N. Sakimura
Request for Comments: 9101                                NAT.Consulting
Category: Standards Track                                     J. Bradley
ISSN: 2070-1721                                                   Yubico
                                                                M. Jones
                                                               Microsoft
                                                             August 2021


The OAuth 2.0 Authorization Framework: JWT-Secured Authorization Request
                                 (JAR)

Abstract

   The authorization request in OAuth 2.0 described in RFC 6749 utilizes
   query parameter serialization, which means that authorization request
   parameters are encoded in the URI of the request and sent through
   user agents such as web browsers.  While it is easy to implement, it
   means that a) the communication through the user agents is not
   integrity protected and thus, the parameters can be tainted, b) the
   source of the communication is not authenticated, and c) the
   communication through the user agents can be monitored.  Because of
   these weaknesses, several attacks to the protocol have now been put
   forward.

   This document introduces the ability to send request parameters in a
   JSON Web Token (JWT) instead, which allows the request to be signed
   with JSON Web Signature (JWS) and encrypted with JSON Web Encryption
   (JWE) so that the integrity, source authentication, and
   confidentiality properties of the authorization request are attained.
   The request can be sent by value or by reference.

Status of This Memo

   This is an Internet Standards Track document.

   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
   Internet Standards 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 at
   https://www.rfc-editor.org/info/rfc9101.

Copyright Notice

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

Table of Contents

   1.  Introduction
     1.1.  Requirements Language
   2.  Terminology
     2.1.  Request Object
     2.2.  Request Object URI
   3.  Symbols and Abbreviated Terms
   4.  Request Object
   5.  Authorization Request
     5.1.  Passing a Request Object by Value
     5.2.  Passing a Request Object by Reference
       5.2.1.  URI Referencing the Request Object
       5.2.2.  Request Using the "request_uri" Request Parameter
       5.2.3.  Authorization Server Fetches Request Object
   6.  Validating JWT-Based Requests
     6.1.  JWE Encrypted Request Object
     6.2.  JWS-Signed Request Object
     6.3.  Request Parameter Assembly and Validation
   7.  Authorization Server Response
   8.  TLS Requirements
   9.  IANA Considerations
     9.1.  OAuth Parameters Registration
     9.2.  OAuth Authorization Server Metadata Registry
     9.3.  OAuth Dynamic Client Registration Metadata Registry
     9.4.  Media Type Registration
       9.4.1.  Registry Contents
   10. Security Considerations
     10.1.  Choice of Algorithms
     10.2.  Request Source Authentication
     10.3.  Explicit Endpoints
     10.4.  Risks Associated with request_uri
       10.4.1.  DDoS Attack on the Authorization Server
       10.4.2.  Request URI Rewrite
     10.5.  Downgrade Attack
     10.6.  TLS Security Considerations
     10.7.  Parameter Mismatches
     10.8.  Cross-JWT Confusion
   11. Privacy Considerations
     11.1.  Collection Limitation
     11.2.  Disclosure Limitation
       11.2.1.  Request Disclosure
       11.2.2.  Tracking Using Request Object URI
   12. References
     12.1.  Normative References
     12.2.  Informative References
   Acknowledgements
   Authors' Addresses

1.  Introduction

   The authorization request in OAuth 2.0 [RFC6749] utilizes query
   parameter serialization and is typically sent through user agents
   such as web browsers.

   For example, the parameters "response_type", "client_id", "state",
   and "redirect_uri" are encoded in the URI of the request:

       GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
       &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
       Host: server.example.com

   While it is easy to implement, the encoding in the URI does not allow
   application-layer security to be used to provide confidentiality and
   integrity protection.  While TLS is used to offer communication
   security between the client and the user agent as well as the user
   agent and the authorization server, TLS sessions are terminated in
   the user agent.  In addition, TLS sessions may be terminated
   prematurely at some middlebox (such as a load balancer).

   As a result, the authorization request of [RFC6749] has shortcomings
   in that:

   (a)  the communication through the user agents is not integrity
        protected, and thus, the parameters can be tainted (integrity
        protection failure);

   (b)  the source of the communication is not authenticated (source
        authentication failure);

   (c)  the communication through the user agents can be monitored
        (containment/confidentiality failure).

   Due to these inherent weaknesses, several attacks against the
   protocol, such as redirection URI rewriting, have been identified.

   The use of application-layer security mitigates these issues.

   The use of application-layer security allows requests to be prepared
   by a trusted third party so that a client application cannot request
   more permissions than previously agreed upon.

   Furthermore, passing the request by reference allows the reduction of
   over-the-wire overhead.

   The JWT [RFC7519] encoding has been chosen because of:

   (1)  its close relationship with JSON, which is used as OAuth's
        response format

   (2)  its developer friendliness due to its textual nature

   (3)  its relative compactness compared to XML

   (4)  its development status as a Proposed Standard, along with the
        associated signing and encryption methods [RFC7515] [RFC7516]

   (5)  the relative ease of JWS and JWE compared to XML Signature and
        Encryption.

   The parameters "request" and "request_uri" are introduced as
   additional authorization request parameters for the OAuth 2.0
   [RFC6749] flows.  The "request" parameter is a JSON Web Token (JWT)
   [RFC7519] whose JWT Claims Set holds the JSON-encoded OAuth 2.0
   authorization request parameters.  Note that, in contrast to RFC
   7519, the elements of the Claims Set are encoded OAuth request
   parameters [IANA.OAuth.Parameters], supplemented with only a few of
   the IANA-managed JSON Web Token Claims [IANA.JWT.Claims], in
   particular, "iss" and "aud".  The JWT in the "request" parameter is
   integrity protected and source authenticated using JWS.

   The JWT [RFC7519] can be passed to the authorization endpoint by
   reference, in which case the parameter "request_uri" is used instead
   of "request".

   Using JWT [RFC7519] as the request encoding instead of query
   parameters has several advantages:

   (a)  Integrity protection.  The request can be signed so that the
        integrity of the request can be checked.

   (b)  Source authentication.  The request can be signed so that the
        signer can be authenticated.

   (c)  Confidentiality protection.  The request can be encrypted so
        that end-to-end confidentiality can be provided even if the TLS
        connection is terminated at one point or another (including at
        and before user agents).

   (d)  Collection minimization.  The request can be signed by a trusted
        third party attesting that the authorization request is
        compliant with a certain policy.  For example, a request can be
        pre-examined by a trusted third party to confirm that all the
        personal data requested is strictly necessary to perform the
        process that the end user asked for; the request would then be
        signed by that trusted third party.  The authorization server
        then examines the signature and shows the conformance status to
        the end user who would have some assurance as to the legitimacy
        of the request when authorizing it.  In some cases, it may even
        be desirable to skip the authorization dialogue under such
        circumstances.

   There are a few cases where request by reference is useful, such as:

   1.  when it is desirable to reduce the size of a transmitted request.
       The use of application-layer security increases the size of the
       request particularly when public-key cryptography is used.

   2.  when the client does not want to do the application-level
       cryptography.  The authorization server may provide an endpoint
       to accept the authorization request through direct communication
       with the client, so that the client is authenticated and the
       channel is TLS protected.

   This capability is in use by OpenID Connect [OpenID.Core].

1.1.  Requirements Language

   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.

2.  Terminology

   For the purposes of this specification, the following terms and
   definitions apply in addition to what is defined in OAuth 2.0
   Framework [RFC6749], JSON Web Signature [RFC7515], and JSON Web
   Encryption [RFC7516].

2.1.  Request Object

   A Request Object is a JSON Web Token (JWT) [RFC7519] whose JWT Claims
   Set holds the JSON-encoded OAuth 2.0 authorization request
   parameters.

2.2.  Request Object URI

   A Request Object URI is an absolute URI that references the set of
   parameters comprising an OAuth 2.0 authorization request.  The
   content of the resource referenced by the URI is a Request Object
   (Section 2.1), unless the URI was provided to the client by the same
   authorization server, in which case the content is an implementation
   detail at the discretion of the authorization server.  The content
   being a Request Object is to ensure interoperability in cases where
   the provider of the "request_uri" is a separate entity from the
   consumer, such as when a client provides a URI referencing a Request
   Object stored on the client's backend service that is made accessible
   via HTTPS.  In the latter case, where the authorization server is
   both provider and consumer of the URI, such as when it offers an
   endpoint that provides a URI in exchange for a Request Object, this
   interoperability concern does not apply.

3.  Symbols and Abbreviated Terms

   The following abbreviations are common to this specification.

   JSON:  JavaScript Object Notation

   JWT:  JSON Web Token

   JWS:  JSON Web Signature

   JWE:  JSON Web Encryption

   URI:  Uniform Resource Identifier

   URL:  Uniform Resource Locator

4.  Request Object

   A Request Object (Section 2.1) is used to provide authorization
   request parameters for an OAuth 2.0 authorization request.  It MUST
   contain all the parameters (including extension parameters) used to
   process the OAuth 2.0 [RFC6749] authorization request except the
   "request" and "request_uri" parameters that are defined in this
   document.  The parameters are represented as the JWT Claims of the
   object.  Parameter names and string values MUST be included as JSON
   strings.  Since Request Objects are handled across domains and
   potentially outside of a closed ecosystem, per Section 8.1 of
   [RFC8259], these JSON strings MUST be encoded using UTF-8 [RFC3629].
   Numerical values MUST be included as JSON numbers.  The Request
   Object MAY include any extension parameters.  This JSON [RFC8259]
   object constitutes the JWT Claims Set defined in JWT [RFC7519].  The
   JWT Claims Set is then signed or signed and encrypted.

   To sign, JSON Web Signature (JWS) [RFC7515] is used.  The result is a
   JWS-signed JWT [RFC7519].  If signed, the Authorization Request
   Object SHOULD contain the Claims "iss" (issuer) and "aud" (audience)
   as members with their semantics being the same as defined in the JWT
   [RFC7519] specification.  The value of "aud" should be the value of
   the authorization server (AS) "issuer", as defined in RFC 8414
   [RFC8414].

   To encrypt, JWE [RFC7516] is used.  When both signature and
   encryption are being applied, the JWT MUST be signed, then encrypted,
   as described in Section 11.2 of [RFC7519].  The result is a Nested
   JWT, as defined in [RFC7519].

   The client determines the algorithms used to sign and encrypt Request
   Objects.  The algorithms chosen need to be supported by both the
   client and the authorization server.  The client can inform the
   authorization server of the algorithms that it supports in its
   dynamic client registration metadata [RFC7591], specifically, the
   metadata values "request_object_signing_alg",
   "request_object_encryption_alg", and "request_object_encryption_enc".
   Likewise, the authorization server can inform the client of the
   algorithms that it supports in its authorization server metadata
   [RFC8414], specifically, the metadata values
   "request_object_signing_alg_values_supported",
   "request_object_encryption_alg_values_supported", and
   "request_object_encryption_enc_values_supported".

   The Request Object MAY be sent by value, as described in Section 5.1,
   or by reference, as described in Section 5.2.  "request" and
   "request_uri" parameters MUST NOT be included in Request Objects.

   A Request Object (Section 2.1) has the media type [RFC2046]
   "application/oauth-authz-req+jwt".  Note that some existing
   deployments may alternatively be using the type "application/jwt".

   The following is an example of the Claims in a Request Object before
   base64url [RFC7515] encoding and signing.  Note that it includes the
   extension parameters "nonce" and "max_age".

     {
      "iss": "s6BhdRkqt3",
      "aud": "https://server.example.com",
      "response_type": "code id_token",
      "client_id": "s6BhdRkqt3",
      "redirect_uri": "https://client.example.org/cb",
      "scope": "openid",
      "state": "af0ifjsldkj",
      "nonce": "n-0S6_WzA2Mj",
      "max_age": 86400
     }

   Signing it with the "RS256" algorithm [RFC7518] results in this
   Request Object value (with line wraps within values for display
   purposes only):

     eyJhbGciOiJSUzI1NiIsImtpZCI6ImsyYmRjIn0.ewogICAgImlzcyI6ICJzNkJoZF
     JrcXQzIiwKICAgICJhdWQiOiAiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20iLAog
     ICAgInJlc3BvbnNlX3R5cGUiOiAiY29kZSBpZF90b2tlbiIsCiAgICAiY2xpZW50X2
     lkIjogInM2QmhkUmtxdDMiLAogICAgInJlZGlyZWN0X3VyaSI6ICJodHRwczovL2Ns
     aWVudC5leGFtcGxlLm9yZy9jYiIsCiAgICAic2NvcGUiOiAib3BlbmlkIiwKICAgIC
     JzdGF0ZSI6ICJhZjBpZmpzbGRraiIsCiAgICAibm9uY2UiOiAibi0wUzZfV3pBMk1q
     IiwKICAgICJtYXhfYWdlIjogODY0MDAKfQ.Nsxa_18VUElVaPjqW_ToI1yrEJ67BgK
     b5xsuZRVqzGkfKrOIX7BCx0biSxYGmjK9KJPctH1OC0iQJwXu5YVY-vnW0_PLJb1C2
     HG-ztVzcnKZC2gE4i0vgQcpkUOCpW3SEYXnyWnKzuKzqSb1wAZALo5f89B_p6QA6j6
     JwBSRvdVsDPdulW8lKxGTbH82czCaQ50rLAg3EYLYaCb4ik4I1zGXE4fvim9FIMs8O
     CMmzwIB5S-ujFfzwFjoyuPEV4hJnoVUmXR_W9typPf846lGwA8h9G9oNTIuX8Ft2jf
     pnZdFmLg3_wr3Wa5q3a-lfbgF3S9H_8nN3j1i7tLR_5Nz-g

   The following RSA public key, represented in JSON Web Key (JWK)
   format, can be used to validate the Request Object signature in this
   and subsequent Request Object examples (with line wraps within values
   for display purposes only):

     {
      "kty":"RSA",
      "kid":"k2bdc",
      "n":"x5RbkAZkmpRxia65qRQ1wwSMSxQUnS7gcpVTV_cdHmfmG2ltd2yabEO9XadD8
           pJNZubINPpmgHh3J1aD9WRwS05ucmFq3CfFsluLt13_7oX5yDRSKX7poXmT_5
           ko8k4NJZPMAO8fPToDTH7kHYbONSE2FYa5GZ60CUsFhSonI-dcMDJ0Ary9lxI
           w5k2z4TAdARVWcS7sD07VhlMMshrwsPHBQgTatlkxyIHXbYdtak8fqvNAwr7O
           lVEvM_Ipf5OfmdB8Sd-wjzaBsyP4VhJKoi_qdgSzpC694XZeYPq45Sw-q51iF
           UlcOlTCI7z6jltUtnR6ySn6XDGFnzH5Fe5ypw",
      "e":"AQAB"
     }

5.  Authorization Request

   The client constructs the authorization request URI by adding the
   following parameters to the query component of the authorization
   endpoint URI using the "application/x-www-form-urlencoded" format:

   request
      REQUIRED unless "request_uri" is specified.  The Request Object
      (Section 2.1) that holds authorization request parameters stated
      in Section 4 of [RFC6749] (OAuth 2.0).  If this parameter is
      present in the authorization request, "request_uri" MUST NOT be
      present.

   request_uri
      REQUIRED unless "request" is specified.  The absolute URI, as
      defined by RFC 3986 [RFC3986], that is the Request Object URI
      (Section 2.2) referencing the authorization request parameters
      stated in Section 4 of [RFC6749] (OAuth 2.0).  If this parameter
      is present in the authorization request, "request" MUST NOT be
      present.

   client_id
      REQUIRED.  OAuth 2.0 [RFC6749] "client_id".  The value MUST match
      the "request" or "request_uri" Request Object's (Section 2.1)
      "client_id".

   The client directs the resource owner to the constructed URI using an
   HTTP redirection response or by other means available to it via the
   user agent.

   For example, the client directs the end user's user agent to make the
   following HTTPS request:

   GET /authz?client_id=s6BhdRkqt3&request=eyJhbG..AlMGzw HTTP/1.1
   Host: server.example.com

   The value for the request parameter is abbreviated for brevity.

   The Authorization Request Object MUST be one of the following:

   (a)  JWS signed

   (b)  JWS signed and JWE encrypted

   The client MAY send the parameters included in the Request Object
   duplicated in the query parameters as well for backward
   compatibility, etc.  However, the authorization server supporting
   this specification MUST only use the parameters included in the
   Request Object.

5.1.  Passing a Request Object by Value

   The client sends the authorization request as a Request Object to the
   authorization endpoint as the "request" parameter value.

   The following is an example of an authorization request using the
   "request" parameter (with line wraps within values for display
   purposes only):

     https://server.example.com/authorize?client_id=s6BhdRkqt3&
       request=eyJhbGciOiJSUzI1NiIsImtpZCI6ImsyYmRjIn0.ewogICAgImlzcyI6
       ICJzNkJoZFJrcXQzIiwKICAgICJhdWQiOiAiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBs
       ZS5jb20iLAogICAgInJlc3BvbnNlX3R5cGUiOiAiY29kZSBpZF90b2tlbiIsCiAg
       ICAiY2xpZW50X2lkIjogInM2QmhkUmtxdDMiLAogICAgInJlZGlyZWN0X3VyaSI6
       ICJodHRwczovL2NsaWVudC5leGFtcGxlLm9yZy9jYiIsCiAgICAic2NvcGUiOiAi
       b3BlbmlkIiwKICAgICJzdGF0ZSI6ICJhZjBpZmpzbGRraiIsCiAgICAibm9uY2Ui
       OiAibi0wUzZfV3pBMk1qIiwKICAgICJtYXhfYWdlIjogODY0MDAKfQ.Nsxa_18VU
       ElVaPjqW_ToI1yrEJ67BgKb5xsuZRVqzGkfKrOIX7BCx0biSxYGmjK9KJPctH1OC
       0iQJwXu5YVY-vnW0_PLJb1C2HG-ztVzcnKZC2gE4i0vgQcpkUOCpW3SEYXnyWnKz
       uKzqSb1wAZALo5f89B_p6QA6j6JwBSRvdVsDPdulW8lKxGTbH82czCaQ50rLAg3E
       YLYaCb4ik4I1zGXE4fvim9FIMs8OCMmzwIB5S-ujFfzwFjoyuPEV4hJnoVUmXR_W
       9typPf846lGwA8h9G9oNTIuX8Ft2jfpnZdFmLg3_wr3Wa5q3a-lfbgF3S9H_8nN3
       j1i7tLR_5Nz-g

5.2.  Passing a Request Object by Reference

   The "request_uri" authorization request parameter enables OAuth
   authorization requests to be passed by reference rather than by
   value.  This parameter is used identically to the "request"
   parameter, except that the Request Object value is retrieved from the
   resource identified by the specified URI rather than passed by value.

   The entire Request URI SHOULD NOT exceed 512 ASCII characters.  There
   are two reasons for this restriction:

   1.  Many phones on the market as of this writing still do not accept
       large payloads.  The restriction is typically either 512 or 1024
       ASCII characters.

   2.  On a slow connection such as a 2G mobile connection, a large URL
       would cause a slow response; therefore, the use of such is not
       advisable from the user-experience point of view.

   The contents of the resource referenced by the "request_uri" MUST be
   a Request Object and MUST be reachable by the authorization server
   unless the URI was provided to the client by the authorization
   server.  In the first case, the "request_uri" MUST be an "https" URI,
   as specified in Section 2.7.2 of [RFC7230].  In the second case, it
   MUST be a URN, as specified in [RFC8141].

   The following is an example of the contents of a Request Object
   resource that can be referenced by a "request_uri" (with line wraps
   within values for display purposes only):

     eyJhbGciOiJSUzI1NiIsImtpZCI6ImsyYmRjIn0.ewogICAgImlzcyI6ICJzNkJoZF
     JrcXQzIiwKICAgICJhdWQiOiAiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20iLAog
     ICAgInJlc3BvbnNlX3R5cGUiOiAiY29kZSBpZF90b2tlbiIsCiAgICAiY2xpZW50X2
     lkIjogInM2QmhkUmtxdDMiLAogICAgInJlZGlyZWN0X3VyaSI6ICJodHRwczovL2Ns
     aWVudC5leGFtcGxlLm9yZy9jYiIsCiAgICAic2NvcGUiOiAib3BlbmlkIiwKICAgIC
     JzdGF0ZSI6ICJhZjBpZmpzbGRraiIsCiAgICAibm9uY2UiOiAibi0wUzZfV3pBMk1q
     IiwKICAgICJtYXhfYWdlIjogODY0MDAKfQ.Nsxa_18VUElVaPjqW_ToI1yrEJ67BgK
     b5xsuZRVqzGkfKrOIX7BCx0biSxYGmjK9KJPctH1OC0iQJwXu5YVY-vnW0_PLJb1C2
     HG-ztVzcnKZC2gE4i0vgQcpkUOCpW3SEYXnyWnKzuKzqSb1wAZALo5f89B_p6QA6j6
     JwBSRvdVsDPdulW8lKxGTbH82czCaQ50rLAg3EYLYaCb4ik4I1zGXE4fvim9FIMs8O
     CMmzwIB5S-ujFfzwFjoyuPEV4hJnoVUmXR_W9typPf846lGwA8h9G9oNTIuX8Ft2jf
     pnZdFmLg3_wr3Wa5q3a-lfbgF3S9H_8nN3j1i7tLR_5Nz-g

5.2.1.  URI Referencing the Request Object

   The client stores the Request Object resource either locally or
   remotely at a URI the authorization server can access.  Such a
   facility may be provided by the authorization server or a trusted
   third party.  For example, the authorization server may provide a URL
   to which the client POSTs the Request Object and obtains the Request
   URI.  This URI is the Request Object URI, "request_uri".

   It is possible for the Request Object to include values that are to
   be revealed only to the authorization server.  As such, the
   "request_uri" MUST have appropriate entropy for its lifetime so that
   the URI is not guessable if publicly retrievable.  For the guidance,
   refer to Section 5.1.4.2.2 of [RFC6819] and "Good Practices for
   Capability URLs" [CapURLs].  It is RECOMMENDED that the "request_uri"
   be removed after a reasonable timeout unless access control measures
   are taken.

   The following is an example of a Request Object URI value (with line
   wraps within values for display purposes only).  In this example, a
   trusted third-party service hosts the Request Object.

     https://tfp.example.org/request.jwt/
       GkurKxf5T0Y-mnPFCHqWOMiZi4VS138cQO_V7PZHAdM

5.2.2.  Request Using the "request_uri" Request Parameter

   The client sends the authorization request to the authorization
   endpoint.

   The following is an example of an authorization request using the
   "request_uri" parameter (with line wraps within values for display
   purposes only):

     https://server.example.com/authorize?
       client_id=s6BhdRkqt3
       &request_uri=https%3A%2F%2Ftfp.example.org%2Frequest.jwt
       %2FGkurKxf5T0Y-mnPFCHqWOMiZi4VS138cQO_V7PZHAdM

5.2.3.  Authorization Server Fetches Request Object

   Upon receipt of the Request, the authorization server MUST send an
   HTTP "GET" request to the "request_uri" to retrieve the referenced
   Request Object unless the Request Object is stored in a way so that
   the server can retrieve it through other mechanisms securely and
   parse it to recreate the authorization request parameters.

   The following is an example of this fetch process.  In this example,
   a trusted third-party service hosts the Request Object.

   GET /request.jwt/GkurKxf5T0Y-mnPFCHqWOMiZi4VS138cQO_V7PZHAdM HTTP/1.1
   Host: tfp.example.org

   The following is an example of the fetch response:

     HTTP/1.1 200 OK
     Date: Thu, 20 Aug 2020 23:52:39 GMT
     Server: Apache/2.4.43 (tfp.example.org)
     Content-type: application/oauth-authz-req+jwt
     Content-Length: 797
     Last-Modified: Wed, 19 Aug 2020 23:52:32 GMT

     eyJhbGciOiJSUzI1NiIsImtpZCI6ImsyYmRjIn0.ewogICAgImlzcyI6ICJzNkJoZF
     JrcXQzIiwKICAgICJhdWQiOiAiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20iLAog
     ICAgInJlc3BvbnNlX3R5cGUiOiAiY29kZSBpZF90b2tlbiIsCiAgICAiY2xpZW50X2
     lkIjogInM2QmhkUmtxdDMiLAogICAgInJlZGlyZWN0X3VyaSI6ICJodHRwczovL2Ns
     aWVudC5leGFtcGxlLm9yZy9jYiIsCiAgICAic2NvcGUiOiAib3BlbmlkIiwKICAgIC
     JzdGF0ZSI6ICJhZjBpZmpzbGRraiIsCiAgICAibm9uY2UiOiAibi0wUzZfV3pBMk1q
     IiwKICAgICJtYXhfYWdlIjogODY0MDAKfQ.Nsxa_18VUElVaPjqW_ToI1yrEJ67BgK
     b5xsuZRVqzGkfKrOIX7BCx0biSxYGmjK9KJPctH1OC0iQJwXu5YVY-vnW0_PLJb1C2
     HG-ztVzcnKZC2gE4i0vgQcpkUOCpW3SEYXnyWnKzuKzqSb1wAZALo5f89B_p6QA6j6
     JwBSRvdVsDPdulW8lKxGTbH82czCaQ50rLAg3EYLYaCb4ik4I1zGXE4fvim9FIMs8O
     CMmzwIB5S-ujFfzwFjoyuPEV4hJnoVUmXR_W9typPf846lGwA8h9G9oNTIuX8Ft2jf
     pnZdFmLg3_wr3Wa5q3a-lfbgF3S9H_8nN3j1i7tLR_5Nz-g

6.  Validating JWT-Based Requests

6.1.  JWE Encrypted Request Object

   If the Request Object is encrypted, the authorization server MUST
   decrypt the JWT in accordance with the JSON Web Encryption [RFC7516]
   specification.

   The result is a signed Request Object.

   If decryption fails, the authorization server MUST return an
   "invalid_request_object" error to the client in response to the
   authorization request.

6.2.  JWS-Signed Request Object

   The authorization server MUST validate the signature of the JWS-
   signed [RFC7515] Request Object.  If a "kid" Header Parameter is
   present, the key identified MUST be the key used and MUST be a key
   associated with the client.  The signature MUST be validated using a
   key associated with the client and the algorithm specified in the
   "alg" Header Parameter.  Algorithm verification MUST be performed, as
   specified in Sections 3.1 and 3.2 of [RFC8725].

   If the key is not associated with the client or if signature
   validation fails, the authorization server MUST return an
   "invalid_request_object" error to the client in response to the
   authorization request.

6.3.  Request Parameter Assembly and Validation

   The authorization server MUST extract the set of authorization
   request parameters from the Request Object value.  The authorization
   server MUST only use the parameters in the Request Object, even if
   the same parameter is provided in the query parameter.  The client ID
   values in the "client_id" request parameter and in the Request Object
   "client_id" claim MUST be identical.  The authorization server then
   validates the request, as specified in OAuth 2.0 [RFC6749].

   If the Client ID check or the request validation fails, then the
   authorization server MUST return an error to the client in response
   to the authorization request, as specified in Section 5.2 of
   [RFC6749] (OAuth 2.0).

7.  Authorization Server Response

   The authorization server response is created and sent to the client
   as in Section 4 of [RFC6749] (OAuth 2.0).

   In addition, this document uses these additional error values:

   invalid_request_uri
      The "request_uri" in the authorization request returns an error or
      contains invalid data.

   invalid_request_object
      The request parameter contains an invalid Request Object.

   request_not_supported
      The authorization server does not support the use of the "request"
      parameter.

   request_uri_not_supported
      The authorization server does not support the use of the
      "request_uri" parameter.

8.  TLS Requirements

   Client implementations supporting the Request Object URI method MUST
   support TLS, following "Recommendations for Secure Use of Transport
   Layer Security (TLS) and Datagram Transport Layer Security (DTLS)"
   [RFC7525].

   To protect against information disclosure and tampering,
   confidentiality protection MUST be applied using TLS with a cipher
   suite that provides confidentiality and integrity protection.

   HTTP clients MUST also verify the TLS server certificate, using DNS-
   ID [RFC6125], to avoid man-in-the-middle attacks.  The rules and
   guidelines defined in [RFC6125] apply here, with the following
   considerations:

   *  Support for DNS-ID identifier type (that is, the dNSName identity
      in the subjectAltName extension) is REQUIRED.  Certification
      authorities that issue server certificates MUST support the DNS-ID
      identifier type, and the DNS-ID identifier type MUST be present in
      server certificates.

   *  DNS names in server certificates MAY contain the wildcard
      character "*".

   *  Clients MUST NOT use CN-ID identifiers; a Common Name field (CN
      field) may be present in the server certificate's subject name but
      MUST NOT be used for authentication within the rules described in
      [RFC7525].

   *  SRV-ID and URI-ID as described in Section 6.5 of [RFC6125] MUST
      NOT be used for comparison.

9.  IANA Considerations

9.1.  OAuth Parameters Registration

   Since the Request Object is a JWT, the core JWT claims cannot be used
   for any purpose in the Request Object other than for what JWT
   dictates.  Thus, they have been registered as OAuth authorization
   request parameters to avoid future OAuth extensions using them with
   different meanings.

   This specification adds the following values to the "OAuth
   Parameters" registry [IANA.OAuth.Parameters] established by
   [RFC6749].

   Name:  "iss"
   Parameter Usage Location:  authorization request
   Change Controller:  IETF
   Specification Document(s):  This document and Section 4.1.1 of
      [RFC7519].

   Name:  "sub"
   Parameter Usage Location:  authorization request
   Change Controller:  IETF
   Specification Document(s):  This document and Section 4.1.2 of
      [RFC7519].

   Name:  "aud"
   Parameter Usage Location:  authorization request
   Change Controller:  IETF
   Specification Document(s):  This document and Section 4.1.3 of
      [RFC7519].

   Name:  "exp"
   Parameter Usage Location:  authorization request
   Change Controller:  IETF
   Specification Document(s):  This document and Section 4.1.4 of
      [RFC7519].

   Name:  "nbf"
   Parameter Usage Location:  authorization request
   Change Controller:  IETF
   Specification Document(s):  This document and Section 4.1.5 of
      [RFC7519].

   Name:  "iat"
   Parameter Usage Location:  authorization request
   Change Controller:  IETF
   Specification Document(s):  This document and Section 4.1.6 of
      [RFC7519].

   Name:  "jti"
   Parameter Usage Location:  authorization request
   Change Controller:  IETF
   Specification Document(s):  This document and Section 4.1.7 of
      [RFC7519].

9.2.  OAuth Authorization Server Metadata Registry

   This specification adds the following value to the "OAuth
   Authorization Server Metadata" registry [IANA.OAuth.Parameters]
   established by [RFC8414].

   Metadata Name:  "require_signed_request_object"
   Metadata Description:  Indicates where authorization request needs to
      be protected as Request Object and provided through either
      "request" or "request_uri parameter".
   Change Controller:  IETF
   Specification Document(s):  Section 10.5 of this document.

9.3.  OAuth Dynamic Client Registration Metadata Registry

   This specification adds the following value to the "OAuth Dynamic
   Client Registration Metadata" registry [IANA.OAuth.Parameters]
   established by [RFC7591].

   Metadata Name:  "require_signed_request_object"
   Metadata Description:  Indicates where authorization request needs to
      be protected as Request Object and provided through either
      "request" or "request_uri parameter".
   Change Controller:  IETF
   Specification Document(s):  Section 10.5 of this document.

9.4.  Media Type Registration

9.4.1.  Registry Contents

   This section registers the "application/oauth-authz-req+jwt" media
   type [RFC2046] in the "Media Types" registry [IANA.MediaTypes] in the
   manner described in [RFC6838].  It can be used to indicate that the
   content is a JWT containing Request Object claims.

   Type name:  application
   Subtype name:  oauth-authz-req+jwt
   Required parameters:  N/A
   Optional parameters:  N/A
   Encoding considerations:  binary; a Request Object is a JWT; JWT
      values are encoded as a series of base64url-encoded values (some
      of which may be the empty string) separated by period (".")
      characters.
   Security considerations:  See Section 10 of RFC 9101
   Interoperability considerations:  N/A
   Published specification:  Section 4 of RFC 9101
   Applications that use this media type:  Applications that use Request
      Objects to make an OAuth 2.0 authorization request
   Fragment identifier considerations:  N/A
   Additional information:
      Deprecated alias names for this type:  N/A
      Magic number(s):  N/A
      File extension(s):  N/A
      Macintosh file type code(s):  N/A
   Person & email address to contact for further information:
      Nat Sakimura <nat@nat.consulting>
   Intended usage:  COMMON
   Restrictions on usage:  none
   Author:  Nat Sakimura <nat@nat.consulting>
   Change controller:  IETF
   Provisional registration?  No

10.  Security Considerations

   In addition to all the security considerations discussed in OAuth 2.0
   [RFC6819], the security considerations in [RFC7515], [RFC7516],
   [RFC7518], and [RFC8725] need to be considered.  Also, there are
   several academic papers such as [BASIN] that provide useful insight
   into the security properties of protocols like OAuth.

   In consideration of the above, this document advises taking the
   following security considerations into account.

10.1.  Choice of Algorithms

   When sending the Authorization Request Object through the "request"
   parameter, it MUST be either signed using JWS [RFC7515] or signed and
   then encrypted using JWS [RFC7515] and JWE [RFC7516], respectively,
   with algorithms considered appropriate at the time.

10.2.  Request Source Authentication

   The source of the authorization request MUST always be verified.
   There are several ways to do it:

   (a)  Verifying the JWS Signature of the Request Object.

   (b)  Verifying that the symmetric key for the JWE encryption is the
        correct one if the JWE is using symmetric encryption.  Note,
        however, that if public key encryption is used, no source
        authentication is enabled by the encryption, as any party can
        encrypt to the public key.

   (c)  Verifying the TLS Server Identity of the Request Object URI.  In
        this case, the authorization server MUST know out-of-band that
        the client uses the Request Object URI and only the client is
        covered by the TLS certificate.  In general, this is not a
        reliable method.

   (d)  When an authorization server implements a service that returns a
        Request Object URI in exchange for a Request Object, the
        authorization server MUST perform client authentication to
        accept the Request Object and bind the client identifier to the
        Request Object URI it is providing.  It MUST validate the
        signature, per (a).  Since the Request Object URI can be
        replayed, the lifetime of the Request Object URI MUST be short
        and preferably one-time use.  The entropy of the Request Object
        URI MUST be sufficiently large.  The adequate shortness of the
        validity and the entropy of the Request Object URI depends on
        the risk calculation based on the value of the resource being
        protected.  A general guidance for the validity time would be
        less than a minute, and the Request Object URI is to include a
        cryptographic random value of 128 bits or more at the time of
        the writing of this specification.

   (e)  When a trusted third-party service returns a Request Object URI
        in exchange for a Request Object, it MUST validate the
        signature, per (a).  In addition, the authorization server MUST
        be trusted by the third-party service and MUST know out-of-band
        that the client is also trusted by it.

10.3.  Explicit Endpoints

   Although this specification does not require them, research such as
   [BASIN] points out that it is a good practice to explicitly state the
   intended interaction endpoints and the message position in the
   sequence in a tamper-evident manner so that the intent of the
   initiator is unambiguous.  It is RECOMMENDED by this specification to
   use this practice for the following endpoints defined in [RFC6749],
   [RFC6750], and [RFC8414]:

   (a)  Protected resources ("protected_resources")

   (b)  Authorization endpoint ("authorization_endpoint")

   (c)  Redirection URI ("redirect_uri")

   (d)  Token endpoint ("token_endpoint")

   Further, if dynamic discovery is used, then this practice also
   applies to the discovery-related endpoints.

   In [RFC6749], while the redirection URI is included in the
   authorization request, others are not.  As a result, the same applies
   to the Authorization Request Object.

10.4.  Risks Associated with request_uri

   The introduction of "request_uri" introduces several attack
   possibilities.  Consult the security considerations in Section 7 of
   [RFC3986] for more information regarding risks associated with URIs.

10.4.1.  DDoS Attack on the Authorization Server

   A set of malicious clients can launch a DoS attack to the
   authorization server by pointing the "request_uri" to a URI that
   returns extremely large content or is extremely slow to respond.
   Under such an attack, the server may use up its resource and start
   failing.

   Similarly, a malicious client can specify a "request_uri" value that
   itself points to an authorization request URI that uses "request_uri"
   to cause the recursive lookup.

   To prevent such an attack from succeeding, the server should a) check
   that the value of the "request_uri" parameter does not point to an
   unexpected location, b) check that the media type of the response is
   "application/oauth-authz-req+jwt", c) implement a timeout for
   obtaining the content of "request_uri", and d) not perform recursive
   GET on the "request_uri".

10.4.2.  Request URI Rewrite

   The value of "request_uri" is not signed; thus, it can be tampered
   with by a man-in-the-browser attacker.  Several attack possibilities
   arise because of this.  For example, a) an attacker may create
   another file that the rewritten URI points to, making it possible to
   request extra scope, or b) an attacker may launch a DoS attack on a
   victim site by setting the value of "request_uri" to be that of the
   victim.

   To prevent such an attack from succeeding, the server should a) check
   that the value of the "request_uri" parameter does not point to an
   unexpected location, b) check that the media type of the response is
   "application/oauth-authz-req+jwt", and c) implement a timeout for
   obtaining the content of "request_uri".

10.5.  Downgrade Attack

   Unless the protocol used by the client and the server is locked down
   to use an OAuth JWT-Secured Authorization Request (JAR), it is
   possible for an attacker to use RFC 6749 requests to bypass all the
   protection provided by this specification.

   To prevent this kind of attack, this specification defines new client
   metadata and server metadata values, both named
   "require_signed_request_object", whose values are both booleans.

   When the value of it as client metadata is "true", then the server
   MUST reject the authorization request from the client that does not
   conform to this specification.  It MUST also reject the request if
   the Request Object uses an "alg" value of "none" when this server
   metadata value is "true".  If omitted, the default value is "false".

   When the value of it as server metadata is "true", then the server
   MUST reject the authorization request from any client that does not
   conform to this specification.  It MUST also reject the request if
   the Request Object uses an "alg" value of "none".  If omitted, the
   default value is "false".

   Note that even if "require_signed_request_object" metadata values are
   not present, the client MAY use signed Request Objects, provided that
   there are signing algorithms mutually supported by the client and the
   server.  Use of signing algorithm metadata is described in Section 4.

10.6.  TLS Security Considerations

   Current security considerations can be found in "Recommendations for
   Secure Use of Transport Layer Security (TLS) and Datagram Transport
   Layer Security (DTLS)" [RFC7525].  This supersedes the TLS version
   recommendations in OAuth 2.0 [RFC6749].

10.7.  Parameter Mismatches

   Given that OAuth parameter values are being sent in two different
   places, as normal OAuth parameters and as Request Object claims,
   implementations must guard against attacks that could use mismatching
   parameter values to obtain unintended outcomes.  That is the reason
   that the two client ID values MUST match, the reason that only the
   parameter values from the Request Object are to be used, and the
   reason that neither "request" nor "request_uri" can appear in a
   Request Object.

10.8.  Cross-JWT Confusion

   As described in Section 2.8 of [RFC8725], attackers may attempt to
   use a JWT issued for one purpose in a context that it was not
   intended for.  The mitigations described for these attacks can be
   applied to Request Objects.

   One way that an attacker might attempt to repurpose a Request Object
   is to try to use it as a client authentication JWT, as described in
   Section 2.2 of [RFC7523].  A simple way to prevent this is to never
   use the client ID as the "sub" value in a Request Object.

   Another way to prevent cross-JWT confusion is to use explicit typing,
   as described in Section 3.11 of [RFC8725].  One would explicitly type
   a Request Object by including a "typ" Header Parameter with the value
   "oauth-authz-req+jwt" (which is registered in Section 9.4.1).  Note,
   however, that requiring explicitly typed Request Objects at existing
   authorization servers will break most existing deployments, as
   existing clients are already commonly using untyped Request Objects,
   especially with OpenID Connect [OpenID.Core].  However, requiring
   explicit typing would be a good idea for new OAuth deployment
   profiles where compatibility with existing deployments is not a
   consideration.

   Finally, yet another way to prevent cross-JWT confusion is to use a
   key management regime in which keys used to sign Request Objects are
   identifiably distinct from those used for other purposes.  Then, if
   an adversary attempts to repurpose the Request Object in another
   context, a key mismatch will occur, thwarting the attack.

11.  Privacy Considerations

   When the client is being granted access to a protected resource
   containing personal data, both the client and the authorization
   server need to adhere to Privacy Principles.  "Privacy Considerations
   for Internet Protocols" [RFC6973] gives excellent guidance on the
   enhancement of protocol design and implementation.  The provisions
   listed in it should be followed.

   Most of the provisions would apply to "The OAuth 2.0 Authorization
   Framework" [RFC6749] and "The OAuth 2.0 Authorization Framework:
   Bearer Token Usage" [RFC6750] and are not specific to this
   specification.  In what follows, only the provisions specific to this
   specification are noted.

11.1.  Collection Limitation

   When the client is being granted access to a protected resource
   containing personal data, the client SHOULD limit the collection of
   personal data to that which is within the bounds of applicable law
   and strictly necessary for the specified purpose(s).

   It is often hard for the user to find out if the personal data asked
   for is strictly necessary.  A trusted third-party service can help
   the user by examining the client request, comparing it to the
   proposed processing by the client, and certifying the request.  After
   the certification, the client, when making an authorization request,
   can submit an authorization request to the trusted third-party
   service to obtain the Request Object URI.  This process has two
   steps:

   (1)  (Certification Process) The trusted third-party service examines
        the business process of the client and determines what claims
        they need; this is the certification process.  Once the client
        is certified, they are issued a client credential to
        authenticate against to push Request Objects to the trusted
        third-party service to get the "request_uri".

   (2)  (Translation Process) The client uses the client credential that
        it got to push the Request Object to the trusted third-party
        service to get the "request_uri".  The trusted third-party
        service also verifies that the Request Object is consistent with
        the claims that the client is eligible for, per the prior step.

   Upon receiving such a Request Object URI in the authorization
   request, the authorization server first verifies that the authority
   portion of the Request Object URI is a legitimate one for the trusted
   third-party service.  Then, the authorization server issues an HTTP
   GET request to the Request Object URI.  Upon connecting, the
   authorization server MUST verify that the server identity represented
   in the TLS certificate is legitimate for the Request Object URI.
   Then, the authorization server can obtain the Request Object, which
   includes the "client_id" representing the client.

   The Consent screen MUST indicate the client and SHOULD indicate that
   the request has been vetted by the trusted third-party service for
   the adherence to the collection limitation principle.

11.2.  Disclosure Limitation

11.2.1.  Request Disclosure

   This specification allows extension parameters.  These may include
   potentially sensitive information.  Since URI query parameters may
   leak through various means but most notably through referrer and
   browser history, if the authorization request contains a potentially
   sensitive parameter, the client SHOULD encrypt the Request Object
   using JWE [RFC7516].

   Where the Request Object URI method is being used, if the Request
   Object contains personally identifiable or sensitive information, the
   "request_uri" SHOULD be used only once and have a short validity
   period, and it MUST have sufficient entropy for the applicable
   security policies unless the Request Object itself is encrypted using
   JWE [RFC7516].  The adequate shortness of the validity and the
   entropy of the Request Object URI depends on the risk calculation
   based on the value of the resource being protected.  A general
   guidance for the validity time would be less than a minute, and the
   Request Object URI is to include a cryptographic random value of 128
   bits or more at the time of the writing of this specification.

11.2.2.  Tracking Using Request Object URI

   Even if the protected resource does not include personally
   identifiable information, it is sometimes possible to identify the
   user through the Request Object URI if persistent static per-user
   Request Object URIs are used.  A third party may observe it through
   browser history, etc. and start correlating the user's activity using
   it.  In a way, it is a data disclosure as well and should be avoided.

   Therefore, per-user persistent Request Object URIs should be avoided.
   Single-use Request Object URIs are one alternative.

12.  References

12.1.  Normative References

   [RFC2119]  Bradner, S., "Key words for use in RFCs to Indicate
              Requirement Levels", BCP 14, RFC 2119,
              DOI 10.17487/RFC2119, March 1997,
              <https://www.rfc-editor.org/info/rfc2119>.

   [RFC3629]  Yergeau, F., "UTF-8, a transformation format of ISO
              10646", STD 63, RFC 3629, DOI 10.17487/RFC3629, November
              2003, <https://www.rfc-editor.org/info/rfc3629>.

   [RFC3986]  Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform
              Resource Identifier (URI): Generic Syntax", STD 66,
              RFC 3986, DOI 10.17487/RFC3986, January 2005,
              <https://www.rfc-editor.org/info/rfc3986>.

   [RFC6125]  Saint-Andre, P. and J. Hodges, "Representation and
              Verification of Domain-Based Application Service Identity
              within Internet Public Key Infrastructure Using X.509
              (PKIX) Certificates in the Context of Transport Layer
              Security (TLS)", RFC 6125, DOI 10.17487/RFC6125, March
              2011, <https://www.rfc-editor.org/info/rfc6125>.

   [RFC6749]  Hardt, D., Ed., "The OAuth 2.0 Authorization Framework",
              RFC 6749, DOI 10.17487/RFC6749, October 2012,
              <https://www.rfc-editor.org/info/rfc6749>.

   [RFC6750]  Jones, M. and D. Hardt, "The OAuth 2.0 Authorization
              Framework: Bearer Token Usage", RFC 6750,
              DOI 10.17487/RFC6750, October 2012,
              <https://www.rfc-editor.org/info/rfc6750>.

   [RFC7230]  Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer
              Protocol (HTTP/1.1): Message Syntax and Routing",
              RFC 7230, DOI 10.17487/RFC7230, June 2014,
              <https://www.rfc-editor.org/info/rfc7230>.

   [RFC7515]  Jones, M., Bradley, J., and N. Sakimura, "JSON Web
              Signature (JWS)", RFC 7515, DOI 10.17487/RFC7515, May
              2015, <https://www.rfc-editor.org/info/rfc7515>.

   [RFC7516]  Jones, M. and J. Hildebrand, "JSON Web Encryption (JWE)",
              RFC 7516, DOI 10.17487/RFC7516, May 2015,
              <https://www.rfc-editor.org/info/rfc7516>.

   [RFC7518]  Jones, M., "JSON Web Algorithms (JWA)", RFC 7518,
              DOI 10.17487/RFC7518, May 2015,
              <https://www.rfc-editor.org/info/rfc7518>.

   [RFC7519]  Jones, M., Bradley, J., and N. Sakimura, "JSON Web Token
              (JWT)", RFC 7519, DOI 10.17487/RFC7519, May 2015,
              <https://www.rfc-editor.org/info/rfc7519>.

   [RFC7525]  Sheffer, Y., Holz, R., and P. Saint-Andre,
              "Recommendations for Secure Use of Transport Layer
              Security (TLS) and Datagram Transport Layer Security
              (DTLS)", BCP 195, RFC 7525, DOI 10.17487/RFC7525, May
              2015, <https://www.rfc-editor.org/info/rfc7525>.

   [RFC8141]  Saint-Andre, P. and J. Klensin, "Uniform Resource Names
              (URNs)", RFC 8141, DOI 10.17487/RFC8141, April 2017,
              <https://www.rfc-editor.org/info/rfc8141>.

   [RFC8174]  Leiba, B., "Ambiguity of Uppercase vs Lowercase in RFC
              2119 Key Words", BCP 14, RFC 8174, DOI 10.17487/RFC8174,
              May 2017, <https://www.rfc-editor.org/info/rfc8174>.

   [RFC8259]  Bray, T., Ed., "The JavaScript Object Notation (JSON) Data
              Interchange Format", STD 90, RFC 8259,
              DOI 10.17487/RFC8259, December 2017,
              <https://www.rfc-editor.org/info/rfc8259>.

   [RFC8414]  Jones, M., Sakimura, N., and J. Bradley, "OAuth 2.0
              Authorization Server Metadata", RFC 8414,
              DOI 10.17487/RFC8414, June 2018,
              <https://www.rfc-editor.org/info/rfc8414>.

12.2.  Informative References

   [BASIN]    Basin, D., Cremers, C., and S. Meier, "Provably Repairing
              the ISO/IEC 9798 Standard for Entity Authentication",
              Journal of Computer Security - Security and Trust
              Principles, Volume 21, Issue 6, pp. 817-846, November
              2013,
              <https://www.cs.ox.ac.uk/people/cas.cremers/downloads/
              papers/BCM2012-iso9798.pdf>.

   [CapURLs]  Tennison, J., Ed., "Good Practices for Capability URLs",
              W3C First Public Working Draft, 18 February 2014,
              <https://www.w3.org/TR/capability-urls/>.

   [IANA.JWT.Claims]
              IANA, "JSON Web Token (JWT)",
              <https://www.iana.org/assignments/jwt>.

   [IANA.MediaTypes]
              IANA, "Media Types",
              <https://www.iana.org/assignments/media-types>.

   [IANA.OAuth.Parameters]
              IANA, "OAuth Parameters",
              <https://www.iana.org/assignments/oauth-parameters>.

   [OpenID.Core]
              Sakimura, N., Bradley, J., Jones, M.B., de Medeiros, B.,
              and C. Mortimore, "OpenID Connect Core 1.0 incorporating
              errata set 1", OpenID Foundation Standards, 8 November
              2014,
              <http://openid.net/specs/openid-connect-core-1_0.html>.

   [RFC2046]  Freed, N. and N. Borenstein, "Multipurpose Internet Mail
              Extensions (MIME) Part Two: Media Types", RFC 2046,
              DOI 10.17487/RFC2046, November 1996,
              <https://www.rfc-editor.org/info/rfc2046>.

   [RFC6819]  Lodderstedt, T., Ed., McGloin, M., and P. Hunt, "OAuth 2.0
              Threat Model and Security Considerations", RFC 6819,
              DOI 10.17487/RFC6819, January 2013,
              <https://www.rfc-editor.org/info/rfc6819>.

   [RFC6838]  Freed, N., Klensin, J., and T. Hansen, "Media Type
              Specifications and Registration Procedures", BCP 13,
              RFC 6838, DOI 10.17487/RFC6838, January 2013,
              <https://www.rfc-editor.org/info/rfc6838>.

   [RFC6973]  Cooper, A., Tschofenig, H., Aboba, B., Peterson, J.,
              Morris, J., Hansen, M., and R. Smith, "Privacy
              Considerations for Internet Protocols", RFC 6973,
              DOI 10.17487/RFC6973, July 2013,
              <https://www.rfc-editor.org/info/rfc6973>.

   [RFC7523]  Jones, M., Campbell, B., and C. Mortimore, "JSON Web Token
              (JWT) Profile for OAuth 2.0 Client Authentication and
              Authorization Grants", RFC 7523, DOI 10.17487/RFC7523, May
              2015, <https://www.rfc-editor.org/info/rfc7523>.

   [RFC7591]  Richer, J., Ed., Jones, M., Bradley, J., Machulak, M., and
              P. Hunt, "OAuth 2.0 Dynamic Client Registration Protocol",
              RFC 7591, DOI 10.17487/RFC7591, July 2015,
              <https://www.rfc-editor.org/info/rfc7591>.

   [RFC8725]  Sheffer, Y., Hardt, D., and M. Jones, "JSON Web Token Best
              Current Practices", BCP 225, RFC 8725,
              DOI 10.17487/RFC8725, February 2020,
              <https://www.rfc-editor.org/info/rfc8725>.

Acknowledgements

   The following people contributed to the creation of this document in
   the OAuth Working Group and other IETF roles.  (Affiliations at the
   time of the contribution are used.)

   Annabelle Backman (Amazon), Dirk Balfanz (Google), Sergey Beryozkin,
   Ben Campbell (as AD), Brian Campbell (Ping Identity), Roman Danyliw
   (as AD), Martin Duke (as AD), Vladimir Dzhuvinov (Connect2id), Lars
   Eggert (as AD), Joel Halpern (as GENART), Benjamin Kaduk (as AD),
   Stephen Kent (as SECDIR), Murray Kucherawy (as AD), Warren Kumari (as
   OPSDIR), Watson Ladd (as SECDIR), Torsten Lodderstedt (yes.com), Jim
   Manico, James H. Manger (Telstra), Kathleen Moriarty (as AD), Axel
   Nennker (Deutsche Telecom), John Panzer (Google), Francesca Palombini
   (as AD), David Recordon (Facebook), Marius Scurtescu (Google), Luke
   Shepard (Facebook), Filip Skokan (Auth0), Hannes Tschofenig (ARM),
   Éric Vyncke (as AD), and Robert Wilton (as AD).

   The following people contributed to creating this document through
   the OpenID Connect Core 1.0 [OpenID.Core].

   Brian Campbell (Ping Identity), George Fletcher (AOL), Ryo Itou
   (Mixi), Edmund Jay (Illumila), Breno de Medeiros (Google), Hideki
   Nara (TACT), and Justin Richer (MITRE).

Authors' Addresses

   Nat Sakimura
   NAT.Consulting
   2-22-17 Naka
   Kunitachi, Tokyo 186-0004
   Japan

   Phone: +81-42-580-7401
   Email: nat@nat.consulting
   URI:   https://nat.sakimura.org/


   John Bradley
   Yubico
   Sucursal Talagante
   Casilla 177
   Talagante
   RM
   Chile

   Phone: +1.202.630.5272
   Email: rfc9101@ve7jtb.com
   URI:   http://www.thread-safe.com/


   Michael B. Jones
   Microsoft
   One Microsoft Way
   Redmond, Washington 98052
   United States of America

   Email: mbj@microsoft.com
   URI:   https://self-issued.info/