<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sagara Gunathunga on Medium]]></title>
        <description><![CDATA[Stories by Sagara Gunathunga on Medium]]></description>
        <link>https://medium.com/@sagarag?source=rss-fe43db0e480e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y_Few21GWcaxv_XvOwETcw.png</url>
            <title>Stories by Sagara Gunathunga on Medium</title>
            <link>https://medium.com/@sagarag?source=rss-fe43db0e480e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 03:31:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sagarag/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MCP Removed Sessions. Did It Actually Remove State?]]></title>
            <link>https://sagarag.medium.com/mcp-removed-sessions-did-it-actually-remove-state-99d3b36d60f9?source=rss-fe43db0e480e------2</link>
            <guid isPermaLink="false">https://medium.com/p/99d3b36d60f9</guid>
            <dc:creator><![CDATA[Sagara Gunathunga]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 10:41:16 GMT</pubDate>
            <atom:updated>2026-09-27T10:41:16.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4Cxhq9xooQyTAli5158Zg.png" /></figure><p>When I first read the MCP specification, one thing stood out immediately: it was a stateful protocol. A client and server ran through an initialize handshake, the server handed back a session ID, and every request after that had to carry the same header to stay attached to that one server instance.</p><p>If you’ve run anything stateful behind a load balancer, you already know where this goes. Once a session is pinned to an instance, a normal round robin balancer stops being enough, losing that instance means losing the conversation, and your reverse proxy or gateway has to understand sessions just to route a request. Teams end up building an extra pub/sub layer just to get messages back to the right server. None of that is new, WebSocket-based services have carried this cost for years, but MCP was heading the same way the moment it added a handshake.</p><p>The latest MCP revision as of writing this post (2026–07–28) changes that. It removes the <strong>initialize handshake</strong> and the <strong>session ID</strong> header entirely, there is no protocol session left for a server to lose. In its place:</p><p>The handshake is gone. No initialize request, no notifications/initialized, nothing for a dropped connection to rebuild.</p><p><strong>server/discover</strong> takes its place, and it’s optional for clients. A client can skip it entirely and just call the method it needs, falling back to the error the server sends if it picked an unsupported version.</p><p>Every request now carries its own capabilities. With no session to remember what was agreed earlier, the client repeats its protocol version and capabilities in _meta on every call, not just once at the start.</p><p>Removing the session doesn’t remove the need for state, though, and this is the part worth sitting with. A shopping cart still needs a cart. A tool that has to pause mid-operation and ask the user something still needs to resume correctly. MCP’s answer is to make that state explicit: an ordinary value like a basket_id passed back on every call, or, for a single operation that gets interrupted, a defined request and retry pattern the spec calls <strong>Multi Round-Trip Requests</strong>.</p><p>I go through both patterns, the actual header mechanics that make this stateless design work with ordinary gateways, and where I think the <strong><em>“you just moved the problem”</em></strong> criticism holds up and where it doesn’t, in the full post.<strong> You can read it from here: </strong><a href="https://sagarag.dev/posts/mcp-stateless-migration-cost"><strong>https://sagarag.dev/posts/mcp-stateless-migration-cost</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99d3b36d60f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unwrapping MCP Security: A Walkthrough with the Paypal MCP Server]]></title>
            <link>https://sagarag.medium.com/unwrapping-mcp-security-a-walkthrough-with-the-paypal-mcp-server-90077baa6436?source=rss-fe43db0e480e------2</link>
            <guid isPermaLink="false">https://medium.com/p/90077baa6436</guid>
            <dc:creator><![CDATA[Sagara Gunathunga]]></dc:creator>
            <pubDate>Mon, 12 May 2025 06:36:20 GMT</pubDate>
            <atom:updated>2025-05-13T02:22:33.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxUduA6lwJCKeXVwTea_Tw.png" /><figcaption>(Generated image using Gemini)</figcaption></figure><p>As leading financial platforms like PayPal, Stripe, and Visa roll out AI-driven features, it’s becoming increasingly clear that the AI wave is steadily reshaping a wide range of industries. At the core of this transformation lies the need for seamless integration between large language models (LLMs) and real-world business systems — a challenge the <a href="https://modelcontextprotocol.io/specification/2025-03-26">Model Context Protocol</a> (MCP) is designed to address.</p><p>In the previous post, I covered the basics of MCP through a hands-on example using the GitHub MCP server. The server was run locally and connected to VS Code — configured as the MCP host. For simplicity, communication between the server and client used STDIO as the transport layer, which relies on interprocess communication and doesn’t require explicit security handling.</p><p>In this post, I’ll extend that setup by connecting <a href="https://claude.ai/download">Claude Desktop</a> to the <strong>remote</strong> MCP server hosted by <a href="https://developer.paypal.com/tools/mcp-server/">PayPal</a>. Since this setup uses HTTP for transport, it introduces the need to handle authentication using the MCP authrization specification. Unlike the previous developer-centric use case, this example reflects a more generalized scenario — one that could apply to any client interfacing with a financial service like PayPal over MCP. If you are not familiar about the basics of MCP, I would recommend to go through my previous post or refer any other basic article.</p><p><a href="https://sagarag.medium.com/unwrapping-mcp-a-walkthrough-with-the-github-mcp-server-293608deaec8">Unwrapping MCP : A Walkthrough with the GitHub MCP Server</a></p><blockquote><strong>NOTE</strong><em> —</em> this blog post is based on <strong>2025–03–26</strong> revision of the MCP protocol and changes introduced to the auth spec on 2025–04–26.</blockquote><p>This post focuses specifically on PayPal’s <strong>remote</strong> MCP server, which is hosted on PayPal’s infrastructure and communicates with clients using HTTP/SSE transports. For context, PayPal also offers a <strong>local</strong> MCP server that behaves similarly to the GitHub MCP server used in the previous post.</p><p>Continuing with the layered approach used in the previous post, this walkthrough begins with the user experience and gradually transitions into the underlying authentication mechanics of the MCP protocol.</p><h3>The Experience</h3><p>To start, I added the configuration snippet provided in PayPal’s MCP documentation into Claude Desktop’s settings file and restarted the application. On launch, Claude Desktop automatically opened a browser window, which redirected me to PayPal’s login page. After completing the login flow, I was redirected back to Claude Desktop, where a new interface element appeared — indicating a successful connection to the PayPal MCP server. By clicking this new button, I could view the tools exposed by the PayPal MCP server, confirming that Claude Desktop had established a session tied to my PayPal user account and loaded the available tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-8QA_h4M5v6G57F3HXzyg.png" /><figcaption>Claude Desktop with Paypal MCP server tools</figcaption></figure><p>With the setup complete, I initiated a simple query by instructing Claude Desktop to compare my PayPal expenses.</p><pre>How do you compare my expenses during last Feb and this Feb using Paypal? </pre><p>Claude Desktop, with the help of LLM, identified the appropriate tool — listTransaction—from the PayPal MCP server and prompted me for consent before executing it, similar to how VS Code requested confirmation in the earlier setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJsP1mDQazkZFYjXXjWmwg.png" /><figcaption>Claude Desktop prompts for conset</figcaption></figure><p>After I granted consent, the tool was executed multiple times, and the results were returned as a well-structured natural language summary comparing my expenses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q02eqk5FTFVNpODjWeYz9A.png" /><figcaption>Claude Desktop showing comparison of my Paypal transactions</figcaption></figure><p>This section demonstrated how a remote MCP server like PayPal’s can operate independently or in combination with other MCP servers to complete multi-step, real-world tasks using natural language input.</p><h3>The Security Flow</h3><p>To start this section, first let’s look at how each component is integrated with the others during the above demonstration. As the following diagram illustrates, we have locally installed Claude Desktop. Then, Claude Desktop is configured to connect to the Paypal remote MCP server hosted within Paypal infrastructure, and the Paypal MCP server in turn connects with Paypal backend APIs. Claude Desktop communicates with the Paypal remote MCP server using the HTTP protocol over the internet. This also means that, in addition to using the encrypted transport mechanism provided by TLS (HTTPS), the HTTP endpoint of the Paypal remote MCP server must use some sort of application-level security mechanism. This requirement is fundamentally not different from the endpoint security concepts we’ve been using with APIs for some time now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-m13Uprw8S_tUDIyzWSVwg.png" /><figcaption>How Claude Desktop integrated with Paypal MCP server</figcaption></figure><p>The MCP host application—Claude Desktop, in our case—hides most of the complexities related to security and only prompt when an interaction from a end user is required. In this section, we are going to unwrap MCP security and use Postman so we can clearly observe how security has been implemented.</p><p>As the first exercise of this section, let’s assume there is no security requirement and make a call to the HTTP endpoint exposed by the Paypal MCP server which is technically known as the MCP server endpoint. As shown below, you can find the MCP endpoint of the Paypal MCP server in the Claude Desktop configuration file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEbmMXY_znZLgj-te0gnoA.png" /><figcaption>Paypal MCP server configuration</figcaption></figure><p>Then, you can send an HTTP request to the above MCP endpoint using Postman or a tool like cURL as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M11fcjOcGV3iDq7ogp4cng.png" /><figcaption>Accessing MCP server endpoint without any token</figcaption></figure><p>If you use Postman, you will likely get a response similar to the screenshot shown above — with an HTTP 401 Unauthorized error. It also states that either no access token was provided, or the one provided is invalid. In our case, we know that no token was provided with the request.</p><p>From this, it’s clear that we first need to get an access token from Paypal before sending any messages to the Paypal MCP server. But here’s the catch: how do we know the details of getting an access token from Paypal?</p><p>And yet, we know from the previous section that Claude Desktop somehow figured this out and obtained a valid access token, as we saw the results.</p><p><strong><em>This brings us to a critical question, how did Claude Desktop manage to figure out the details of gettting an access token from Paypal</em></strong><em>?</em></p><h4>Metadata Discovery (2025–03–26 revision/2025–04–26 auth changes)</h4><blockquote>Note: This section is based on the 2025–03–26 revision of the MCP protocol and changes introduced to the auth spec on 2025–04–26. Details may change in future revisions of the MCP protocol. (Date — 12/05/2025)</blockquote><p><a href="https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#2-3-3-fallbacks-for-servers-without-metadata-discovery">Section 2.3.2 of the MCP</a> Authorization specification explains how an MCP client can determine the endpoint URL of the server metadata that describe everything required to obtain an access token. In our case, Claude Desktop uses the following procedure to construct the server metadata endpoint :</p><ul><li>Derive the base URL by discarding any existing path components from the MCP server URL.</li><li>Construct the metadata endpoint by appending /.well-known/oauth-authorization-server to the base URL, as described in the OAuth 2.0 Authorization Server Metadata specification.</li></ul><p>This process is illustrated in the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75pjJJ6RhtMx_NwlGIFSfQ.png" /><figcaption>Construction of the metadata endpoint</figcaption></figure><p>Now, we have the server metadata endpoint in our hand, so the next step is to simply send a request to this endpoint and check whether it would return any server metadata document for us to proceed. As shown below, you can use Postman or cURL to make this call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSx1eVzxXFRJA0JKsyauYA.png" /><figcaption>Authrization Server metadata</figcaption></figure><p>Once we receive the server metadata document, we can easily figure out the details required for the next steps such as:</p><ul><li><strong>Client registration endpoint</strong> — OAuth2 requires prior registration of the client and for the client to have credentials in order to obtain access tokens.</li><li><strong>Authorization endpoint</strong> — As per OAuth2 spec, this is where the client (in our case, Claude Desktop) has to send the end user for authentication and to obtain any required consent.</li><li><strong>Token endpoint</strong> — This is used by OAuth2 clients (such as Claude Desktop in the previous section) to obtain an access token.</li></ul><p>In addition to that, the server metadata document contains details such as supported grant types, supported client types, supported client authentication methods.</p><p>As per the MCP specification, <strong>MCP servers should</strong> and <strong>MCP clients must</strong> support the <a href="https://datatracker.ietf.org/doc/html/rfc8414"><strong>OAuth 2.0 Authorization Server Metadata</strong></a><strong> </strong>specification. To learn more about this specification, you can read the<a href="https://sagarag.medium.com/how-do-you-discover-the-oauth2-server-configuration-d42d30ad5b9d"> this blog post</a> that I wrote sometime back.</p><p><a href="https://sagarag.medium.com/how-do-you-discover-the-oauth2-server-configuration-d42d30ad5b9d">How do you discover the OAuth2 server configuration?</a></p><p>When a server doesn’t support the OAuth2 Authorization Server Metadata specification, the MCP specification defines a <a href="https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#2-3-3-fallbacks-for-servers-without-metadata-discovery">fallback mechanism</a> to determine the required endpoints such as registration, authorization, and token endpoints.</p><h4>Metadata Discovery (in future revisions)</h4><p>Soon after the release of the 2025–03–26 revision of the MCP protocol, there were a lot of discussions initiated around the authorization specification of the MCP protocol. As per the current revision, the authorization capabilities — such as returning the authorization server metadata, dynamic client registration endpoints, and authorization and token endpoints — are all defined as part of the MCP server role. In simple terms, authorization is tightly coupled with the MCP server role.</p><p>In contrast, OAuth2 — which is now widely adopted — defines two separate roles: <strong>Authorization Server (AS) and Resource Server (RS)</strong>, offering a great degree of flexibility for implementers. Even in OAuth2, the spec highlights that it’s possible for an implementer to build both the Authorization Server and Resource Server together, where a single entity plays both roles. However, from the specification’s perspective, these are two distinct roles, providing the advantage of allowing two separate entities to handle them independently.</p><p>If we map OAuth2 terminology to MCP, the tools, prompts, and resources exposed by an MCP can be considered as playing the Resource Server (RS) role, while the authorization capabilities defined by MCP are akin to the Authorization Server (AS) role. The issue, then, is that in the MCP server, both of these roles are defined as one.</p><p><strong>One potential reason for this design decision could be to enable the metadata discovery mechanism — described earlier in this section — solely based on the MCP server URL provided to the host application.</strong> However, based on several discussions and opinions from identity experts, the behavior of this discovery mechanism has been changed in the draft MCP specification.</p><p>The draft specification does not define its own mechanism to discover the metadata endpoint URL. Instead, it employs the <a href="https://datatracker.ietf.org/doc/html/rfc9728/"><strong>OAuth2 Protected Resource Metadata (PRM) specification</strong> </a>for that purpose. This specification defines a standard mechanism for OAuth2 Resource Servers — in this case, the MCP server — to return a URL to its own metadata document (known as the Resource Server Metadata) as part of the initial 401 Unauthorized response. Eventually, this metadata document can be used to discover the location of the Authorization Server Metadata endpoint. The future revisions of the MCP specification will require you to implement the <a href="https://datatracker.ietf.org/doc/html/rfc9728/"><strong>OAuth2 Protected Resource Metadata(PRM)</strong></a> specification as well. I’ve recently written a <a href="https://medium.com/@sagarag/what-is-oauth-2-0-protected-resource-metadata-prm-417ff7b7c196">post</a> about <a href="https://datatracker.ietf.org/doc/html/rfc9728/"><strong>OAuth2 Protected Resource Metadata(PRM)</strong></a></p><p><a href="https://sagarag.medium.com/what-is-oauth-2-0-protected-resource-metadata-prm-417ff7b7c196">What is OAuth 2.0 Protected Resource Metadata (PRM)</a></p><h4>Client Registration</h4><p>Proceeding to the next step, now we can register an OAuth2 client application by sending a simple request to the registration endpoint as per the <a href="https://datatracker.ietf.org/doc/html/rfc7591"><strong>OAuth2 Dynamic Client Registration</strong></a> protocol. As shown in the following figure, we have registered an OAuth2 confidential client and received client_id and client_secret as the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzVqo996FEe2UZmX394ofA.png" /><figcaption>Registering OAuth2 client</figcaption></figure><p>If you would like to read further, one of my <a href="https://sagarag.medium.com/how-to-register-and-manage-oauth2-clients-896e553b7cf1">previous posts </a>covers DCR in detail.</p><p><a href="https://sagarag.medium.com/how-to-register-and-manage-oauth2-clients-896e553b7cf1">How to register and manage OAuth2 clients?</a></p><p><strong>Just to summarize our current progress so far</strong>:</p><ul><li>We derived the metadata endpoint of the server using the MCP server connection URL, which was the only URL available to us.</li><li>Then we discovered the registration, authorization, and token endpoints from the server metadata.</li><li>Finally, we managed to register an OAuth2 client application and received the required client credentials.</li></ul><p>As the next step, we can now start the OAuth2 security flow. When an MCP server doesn’t support MCP authorization capabilities, the client application can obtain the required credentials through an out-of-band mechanism supported by the MCP server implementer.</p><p><strong>One important point:</strong> usually you need these activities only once — when adding a new MCP server to your MCP host application. Once the OAuth2 application is registered and metadata is retrieved, the host application can securely persist them to be used with the OAuth2 grant type to obtain access tokens.</p><p>It’s worth highlighting a couple of other important points at this stage:</p><ul><li>Based on the capability of a client application to store and manage client secrets securely, you need to use either a <strong>public client</strong> or a <strong>confidential client</strong>.</li><li>MCP specification uses the <a href="https://datatracker.ietf.org/doc/draft-ietf-oauth-v2-1/"><strong>OAuth2.1 draft spec</strong></a>, not the OAuth2 spec, which means that regardless of whether you use a public client or a confidential client, <strong>you must use the </strong><a href="https://datatracker.ietf.org/doc/html/rfc7636"><strong>PKCE extension</strong></a> with your OAuth2 flows.</li></ul><p><a href="https://sagarag.medium.com/secure-oauth2-a-simple-story-of-two-keys-pkce-2bdd96232105">Secure OAuth2: A Simple Story of Two Keys — PKCE</a></p><h4>Authorisztion Code Flow</h4><p>There are many options available to try out the OAuth2 flow. In this case, for the <strong>OAuth2 Authorization Code Grant</strong> flow, we stick with <strong>Postman’s built-in OAuth2 configuration</strong>. We can fill in the Postman OAuth2 security settings using the information received from the <strong>server metadata</strong> — such as the <strong>authorization</strong> and <strong>token</strong> endpoints — as well as from the <strong>DCR response</strong>, including the <strong>grant type</strong>, client_id, client_secret, and registered <strong>callback URL (redirect_uri)</strong>. Once these are added, we should see a screen similar to the one shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeHPZmR1fwn7RUBnpxL_tw.png" /><figcaption>Postman OAuth2 configuration</figcaption></figure><p>When you press the <strong>Get Access Token</strong> button, if everything is configured properly, you will see the following <strong>login screen from the PayPal IdP</strong> — not much different from a usual login screen you’ve likely seen before. Under the hood, Postman constructs an <strong>authorization request</strong> and sends it to the PayPal IdP. The IdP processes this request and returns a login screen to authenticate the end user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpvtKgFnaJlxGvwbZkcGqA.png" /><figcaption>Paypal login screen</figcaption></figure><p>An example authorization request used by Postman is given below.</p><pre>https://mcp.paypal.com/authorize?response_type=code&amp;client_id=Krtwtsf&amp;redirect_uri=https://localhost:5000</pre><p>Once the end user logs into PayPal and consents to share the token with the client application — <strong>Claude Desktop</strong>, in our case — the PayPal returns an <strong>authorization code</strong> to the client via the browser.</p><p>Claude Desktop then makes a <strong>direct token call</strong> to the token endpoint, using the code received in the previous step to <strong>obtain an access token</strong>. An example token request is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKVVz9SUiEyjh2x_pnOhAw.png" /><figcaption>Token call to Paypal</figcaption></figure><p>For simplicity, we used the embedded browser capabilities in Postman. However, in a real-world scenario, you don’t need to embed browser logic into your app. Instead, you can use the <strong>standard method</strong> — and that’s exactly what Claude Desktop does, as seen in the previous section. However, other than a couple of extra steps, the core security flow remains the same.</p><p>Here’s how a real world application handles this flow:</p><ol><li>During the application registration, application register the redirect URI in one of two ways: it either registers a <strong>custom URL scheme</strong> (e.g., appname://auth/callback) with the operating system, or it uses a port of a <strong>temporary local web server</strong> (e.g., <a href="http://localhost:3000/auth/callback)">http://localhost:3000/auth/callback)</a> that it would start before the authorization flow starts.</li><li>Constructs the authorization request, acting as the OAuth2 client. <strong>Opens the system’s default web browser </strong>programmatically and navigates to the constructed OAuth2 authorization URL to send the end user to the MCP server. On macOS and Windows, this is typically done using system calls like open or start to ensure a seamless and secure experience.</li><li>The web browser sends the authorization request. The server validates the request and returns a login page to the user.</li><li>Once the authentication and consent steps are completed, the server <strong>forwards the user back</strong> with code parameters to the registered redirect URI. If a <strong>custom URL scheme</strong> is used, the browser detects this and opens the registered app along with the code.</li><li>The client application processes the code, constructs a <strong>token request</strong>, and sends it to the <strong>token endpoint</strong> to receive an <strong>access token</strong>.</li><li>The client application receives an access token from.</li></ol><p>This entire process is illustrated in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7Cbzq4DN7liieP3i9nLmg.png" /><figcaption>Obtaining tokens in real world</figcaption></figure><p>Finally, at this stage, we can run the very first message we sent to the MCP server again — this time with the access token. As shown in the following diagram, the client successfully connects to the MCP server, and a session is established.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGWMIbNJ0lmbM6I8y2D_gg.png" /><figcaption>Accessing MCP Server with an access token</figcaption></figure><p>The following sequence diagram illustrates the entire security flow that we discussed throughout this blog post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4K7Rp_0DgpgkLcs6Jlimw.png" /></figure><p>At this point, we’ve covered most of the practical information you need to understand MCP security. I’ll skip the MCP messages and flows beyond this stage, as I’ve already covered them in great detail in my <a href="https://sagarag.medium.com/unwrapping-mcp-a-walkthrough-with-the-github-mcp-server-293608deaec8">previous post</a>.</p><p><a href="https://sagarag.medium.com/unwrapping-mcp-a-walkthrough-with-the-github-mcp-server-293608deaec8">Unwrapping MCP : A Walkthrough with the GitHub MCP Server</a></p><p>Just for completeness, below is the MCP request message for the listTransactions tool call:</p><pre>{<br>  &quot;method&quot;: &quot;tools/call&quot;,<br>  &quot;params&quot;: {<br>    &quot;name&quot;: &quot;listTransactions&quot;,<br>    &quot;arguments&quot;: {<br>      &quot;start_date&quot;: &quot;2025-04-07T10:29:00Z&quot;,<br>      &quot;end_date&quot;: &quot;2025-04-27T10:29:00Z&quot;,<br>      &quot;page_size&quot;: 10,<br>      &quot;page&quot;: 1<br>    },<br>    &quot;_meta&quot;: {<br>      &quot;progressToken&quot;: 12<br>    }<br>  }<br>}</pre><p>And here is the corresponding response message:</p><pre>{<br>  &quot;transaction_details&quot;: [],<br>  &quot;account_number&quot;: &quot;fgdgt34413r4&quot;,<br>  &quot;start_date&quot;: &quot;2025-04-07T10:29:00+0000&quot;,<br>  &quot;end_date&quot;: &quot;2025-04-27T10:29:00+0000&quot;,<br>  &quot;last_refreshed_datetime&quot;: &quot;2025-05-07T08:29:59+0000&quot;,<br>  &quot;page&quot;: 1,<br>  &quot;total_items&quot;: 0,<br>  &quot;total_pages&quot;: 0,<br>  &quot;links&quot;: [<br>    {<br>      &quot;href&quot;: &quot;https://api.paypal.com/v1/reporting/transactions?end_date=2025-04-27T10%3A29%3A00Z&amp;start_date=2025-04-07T10%3A29%3A00Z&amp;page_size=10&amp;page=1&quot;,<br>      &quot;rel&quot;: &quot;self&quot;,<br>      &quot;method&quot;: &quot;GET&quot;<br>    }<br>  ]<br>}</pre><h3>Wrap up</h3><p>The foremost objective of this post is to elaborate on the security flow that must be implemented by MCP server developers and MCP host/client developers.</p><p>As per the current revision of the MCP protocol (2025–03–26), MCP servers and clients should support the OAuth 2.1 draft specification, the OAuth 2.0 Authorization Server Metadata specification, and the OAuth 2.0 Dynamic Client Registration specification as follows with HTTP transport which includes SSE and Streaming HTTP.</p><p><strong><em>MCP Servers:</em></strong></p><ul><li><strong>Must</strong> support <a href="https://datatracker.ietf.org/doc/draft-ietf-oauth-v2-1/">OAuth 2.1 Draft specification</a></li><li><strong>Should</strong> support <a href="https://datatracker.ietf.org/doc/html/rfc8414">OAuth 2.0 Authorization Server Metadata</a></li><li><strong>Should</strong> support <a href="https://datatracker.ietf.org/doc/html/rfc7591">OAuth 2.0 Dynamic Client Registration Protocol</a></li></ul><p><strong><em>MCP Clients:</em></strong></p><ul><li><strong>Must</strong> support <a href="https://datatracker.ietf.org/doc/draft-ietf-oauth-v2-1/">OAuth 2.1 Draft specification</a></li><li><strong>Must</strong> support <a href="https://datatracker.ietf.org/doc/html/rfc8414">OAuth 2.0 Authorization Server Metadata</a></li><li><strong>Should</strong> support <a href="https://datatracker.ietf.org/doc/html/rfc7591">OAuth 2.0 Dynamic Client Registration Protocol</a></li></ul><p>In addition, future revisions of the MCP protocol are likely to mandate support for the following specifications.</p><p><strong><em>MCP Servers:</em></strong></p><ul><li><strong>Must</strong> support <a href="https://datatracker.ietf.org/doc/html/rfc9728/">OAuth 2.0 Protected Resource Metadata</a></li></ul><p><strong><em>MCP Clients:</em></strong></p><ul><li><strong>Must</strong> support <a href="https://datatracker.ietf.org/doc/html/rfc9728/">OAuth 2.0 Protected Resource Metadata</a></li></ul><p>You can find my posts related to</p><p>I hope this post provides a practical insight into how you can tackle security when developing an MCP Server or MCP Host.</p><p>Stay tuned for the next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90077baa6436" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unwrapping MCP : A Walkthrough with the GitHub MCP Server]]></title>
            <link>https://sagarag.medium.com/unwrapping-mcp-a-walkthrough-with-the-github-mcp-server-293608deaec8?source=rss-fe43db0e480e------2</link>
            <guid isPermaLink="false">https://medium.com/p/293608deaec8</guid>
            <dc:creator><![CDATA[Sagara Gunathunga]]></dc:creator>
            <pubDate>Tue, 06 May 2025 23:13:15 GMT</pubDate>
            <atom:updated>2025-05-06T23:13:15.075Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unwrapping MCP : A Walkthrough with the GitHub MCP Server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Op_yDPEB8v5sJ0as_p0nWw.png" /><figcaption>(Generated image using Gemini)</figcaption></figure><p>We started to see the popping up of MCP servers from various organizations — from tools used in software development all the way through retail, finance, healthcare, and entertainment industries — at an unprecedented scale and speed. And there’s no shortage of content out there that dives deep into MCP, covering the good, the bad, and all sorts of opinions.</p><p>In this post, I’m taking a slightly different approach. Rather than jumping straight into the protocol itself, I’ll unwrap the MCP protocol layer by layer — starting from the user experience, in this case the <em>developer</em> <em>experience</em> as we use the GitHub MCP server as our example today.</p><p>So, without any further due, let’s start our walk.</p><blockquote><strong><em>NOTE</em></strong> — this blog post is based on 2025–03–26 version of the MCP protocol.</blockquote><h3>The Experience</h3><p>To begin, I’ve already created a simple React sample in <a href="https://code.visualstudio.com/docs/copilot/chat/mcp-servers">VS Code</a> using GitHub Copilot — just by giving natural language instructions (a.k.a. prompts). While this step isn’t directly related to our main discussion, I’m sharing the exact prompts I used to create and test the React web application project.</p><pre>Create a React web application using the default Vite template</pre><p>Other than the natural language instructions I gave, I haven’t touched the code at all. <em>M</em><strong><em>y next step was to create a proper README file, set up a GitHub repo, and commit and push the project to GitHub — again, all through natural language instructions.</em></strong> To do this, I simply installed the <a href="https://github.com/github/github-mcp-server">GitHub MCP Server </a>as a Docker container running locally by adding <a href="https://github.com/github/github-mcp-server?tab=readme-ov-file#usage-with-vs-code">this configuration snippet</a> into the VS Code <a href="https://code.visualstudio.com/docs/configure/settings#_how-can-i-reset-my-user-settings">user setting file</a>. I can start and stop the Docker instance though this file.</p><p>The GitHub MCP Server requires the following dependencies:</p><ul><li>A Docker runtime (Docker Desktop/Rancher Desktop).</li><li>A <a href="https://github.com/settings/personal-access-tokens/">GitHub PAT token </a>with enough permission to create repository and commit/push.</li></ul><p>First, I wanted to make sure everything was working fine by checking the GitHub ID with the following simple question.</p><pre>What is my GitHub id?</pre><p>At this stage, GitHub Copilot understands that it needs to run a tool called get_me, which is exposed by the GitHub MCP Server. In the following screen, you’ll see a very important aspect of the MCP protocol in action: the agent—GitHub Copilot—explicitly informs me that it needs to run the get_me tool and asks for my consent before doing so.</p><p><strong>This is a very important principle of the MCP protocol</strong>. Users should clearly agree before anything is done with their data. They should always control what is shared and what actions are taken. Agent apps must show clear prompts that allow users to review and approve actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*GtqNOWVkdHq9wODBurxAJQ.png" /><figcaption>Running the get_me tool from GitHub MCP Server</figcaption></figure><p>Once I gave permission, Copilot ran the tool, processed the response, and returned the result in natural language, as shown in the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*UQCko5N9-2j7uHJwPpu6Wg.png" /><figcaption>Results after running the get_me tool from GitHub MCP Server</figcaption></figure><p>Next, I asked it to create a new GitHub repository with the following simple instruction.</p><pre>Create a GitHub repo caleld unwrapping-mcp-github </pre><p>Again, just like before, GitHub Copilot asked for my consent to run a tool called create_repository.</p><p><em>(Well, it wasn’t intentional, but I had made a spelling mistake here — yet with the help of the LLM, GitHub Copilot still managed to process what I really wanted to achieve.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*P46hcQZxtMndTRR8esgv3Q.png" /><figcaption>Running the create_repository tool from GitHub MCP Server</figcaption></figure><p>Once I confirmed, it ran the tool and showed me the URL of the newly created repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*6TD7hE10UZXQdZXaVDQQUw.png" /><figcaption>Results after running the create_repository tool from GitHub MCP Server</figcaption></figure><p>Finally, I asked Copilot to create a proper README file, commit, and push this code into the new repository — all with a single instruction.</p><pre>create a proper README file, commit and push this code into the <br>newly created repo</pre><p>This time, GitHub Copilot had to perform multiple tasks, and it asked for my explicit approval for each one. At the end, it displayed a success message confirming that the code was committed and pushed to the repo. You can check out the final version <a href="https://github.com/sagara-gunathunga/unwrapping-mcp-github">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*wgJIxWTYVJflGlDCiAKP3Q.png" /><figcaption>Results after running several tools by the GitHub Copilot</figcaption></figure><p>Now you’ve seen a simple yet complete React application built entirely through GitHub Copilot and GitHub MCP Server — and along the way, we explored a key design principle of the MCP protocol.</p><p>Before we wrap up this section, let’s look at the main roles defined by the MCP protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*h_ayxzYXD50QKSekG0zg4A.png" /><figcaption>MCP protocol roles</figcaption></figure><ul><li><strong>Hosts</strong>: Agent applications that create and manage client instances and their lifecycle. They’re responsible for handling client connections and applying security policies. This includes tools like Claude Desktop, IDEs such as Cursor and Windsurf, or any AI-enabled applications that access data through MCP. In our example, VS Code acted as the host. As we’ve seen, the host also takes care of context aggregation across multiple clients and manages user authorization decisions.</li><li><strong>Clients</strong>: Connectors within the host application. Each client connects to a specific MCP server and maintains a 1:1 stateful session with that server. Clients are responsible for routing protocol messages in both directions — between the host and the server.</li><li><strong>Servers</strong>: Provide the context and capabilities via the MCP protocol. These capabilities can reside in the <strong>local environment</strong> (like accessing your file system or a local database), or they can offer <strong>remote access</strong>, similar to how the GitHub MCP Server communicates with GitHub’s APIs remotely.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLe0awtgVy522CqpqoHbpg.png" /><figcaption>MCP Server Features</figcaption></figure><p>The diagram below shows how all the components work together in our example use case at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQiK_z8OK1i0cEYJij2hpg.png" /><figcaption>GitHub MCP Server conneted with VS Code</figcaption></figure><p><strong>At this point, one can ask a very valid question: </strong><em>given that at the end of the day the GitHub API is called, why not just directly call the GitHub API instead of going through several components? And why do we really have to invent a new protocol like MCP?</em></p><p>In fact, there are ready-made GitHub SDKs and even Terraform modules used by DevOps teams that make such integrations relatively easy.</p><p>To answer this question, the MCP protocol provides the following benefits over integrating directly through a proprietary API:</p><ul><li><strong>Standardization and Simplified Integration — </strong>MCP acts as a <strong>universal connector just like USB-C</strong>, standardizing how systems — especially AI agents — connect to external data sources and APIs. Instead of building and maintaining separate, often complex connectors for every proprietary API, developers can integrate once with MCP and reuse that integration across multiple projects and models. This reduces code duplication, minimizes maintenance overhead, and streamlines onboarding of new tools or data sources. If you can recall, we did’t write any code or did’t use SDK during the above exercise.</li><li><strong>Capability Discovery for LLMs</strong> — MCP enables LLMs to automatically discover what capabilities are available on a server. This means LLMs can dynamically understand and tap into new functionality — no manual prompt engineering or hardcoding required. The result? AI applications that are more adaptive and extensible out of the box.</li><li><strong>Improved Security, Compliance, and Maintenance</strong> — With authentication, access control, and data retrieval managed centrally by MCP, the risk of security breaches and compliance headaches is reduced. There’s no need to store credentials or intermediary data across different systems.</li></ul><p>Let’s wrap up this section with the following quite from the spec about the purpose of the MCP protocol.</p><blockquote><a href="https://modelcontextprotocol.io/">Model Context Protocol</a> (MCP) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. Whether you’re building an AI-powered IDE, enhancing a chat interface, or creating custom AI workflows, MCP provides a standardized way to connect LLMs with the context they need.</blockquote><h3>The Messages and the Flow</h3><p>In this section, let’s move to the next layer to understand various messages going back and forth as well as the flow. To begin, let’s connect the GitHub MCP Server to a tool called <strong>MCP Inspector</strong>, which facilitates debugging MCP servers and allows us to look at message-level interactions more easily.</p><p>You can run both the MCP Inspector and GitHub MCP Server locally. Once you configure <a href="https://modelcontextprotocol.io/docs/tools/inspector">MCP Inspector </a>to connect with the GitHub MCP Server, you should be able to see a screen similar to the one below. Considering the length of this post, I’ve included instructions on how to configure and connect the GitHub MCP Server with MCP Inspector <a href="http://gist.github.com/sagara-gunathunga/4b87a5ff02f98e8982766757d4fd1cc3">here</a>, in case you’re interested in trying this out yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Gk6hQN_po6J-ni5Uzg8UQ.png" /><figcaption>MCP Inspector interface after connecting to the GitHub MCP Server</figcaption></figure><p>As I highlighted in the above diagram, a MCP server offers three types of features called <em>Resource, Prompts and Tools</em>. Let’s briefly look at each of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*7P-C4FGYrMnqVHhlkLN2GA.png" /><figcaption>MCP server featuers</figcaption></figure><ul><li><strong>Resources (Structured Data for Context) — </strong>Resources in MCP are application-controlled data sources that servers expose to clients, allowing Large Language Models (LLMs) to access external content as context for their interactions. These can include files, database records, API responses, system logs, images, or any other data the model might need. In our case, as shown below, you can see a set of resource templates to interact with the artefacts managed by the Github.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeyeD9VZMI5d4UQthxezSQ.png" /><figcaption>Resources from the GitHub MCP Server</figcaption></figure><ul><li><strong>Prompts (Predefined Templates for Optimal Use) — </strong>Prompts in MCP are user-controlled templates designed to guide how LLMs interact with tools or resources. By providing structured, pre-defined prompts, users or developers can ensure that the AI leverages external data or functions in the most effective way.</li><li><strong>Tools (Model-Controlled Functionality) — </strong>Tools in MCP represent model-controlled functions that LLMs can call to perform specific actions — similar to function calling or invoking APIs. In the following screenshot you can find tools expose by the Github MCP server and we have already used a bunch of them during the above exercise.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pit8PKSq0p3EMj5aXQzaqA.png" /><figcaption>Tools from the GitHub MCP Server</figcaption></figure><p>Now let’s look into the flow of the MCP protocol. MCP is stateful protocol and defines a connection lifecycle between a client and server in three phases, as shown in the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WP8o6Vf2FrSOAZ-m_AhrVw.png" /><figcaption>MCP client-server connection lifecyccle</figcaption></figure><p>During the first phase — known as the <strong>initialization phase</strong> — the client and server agree on a specific version of the protocol and exchange capabilities. The server declares capabilities like resource subscriptions, tool support, and prompt templates. The client declares its own capabilities like sampling support and notification handling. Both parties must respect the declared capabilities throughout the session. MCP protocol uses <strong>JSON-RPC</strong> as the messaging format.</p><p>Here is the exact message that our client, MCP Inspector, sent to the GitHub MCP server — this is called an <strong>initialize request</strong>. Since MCP Inspector is a testing and debugging tool (not a production client), it hasn’t sent any capabilities in this message.</p><pre>{<br>  &quot;method&quot;: &quot;initialize&quot;<br>}</pre><p>Then the GitHub MCP server returns with its own capabilities and information, as shown in the following example.</p><pre>{<br>  &quot;capabilities&quot;: {<br>    &quot;logging&quot;: {},<br>    &quot;resources&quot;: {<br>      &quot;subscribe&quot;: true,<br>      &quot;listChanged&quot;: true<br>    },<br>    &quot;tools&quot;: {<br>      &quot;listChanged&quot;: true<br>    }<br>  },<br>  &quot;serverInfo&quot;: {<br>    &quot;name&quot;: &quot;github-mcp-server&quot;,<br>    &quot;version&quot;: &quot;v0.2.1&quot;<br>  }<br>}</pre><p>Once this exchange is complete and a session is established, the second phase begins — the <strong>operation phase</strong> — where the client and server exchange messages based on the negotiated capabilities.</p><p>To see what tools are available, we can invoke the tools/list method using the following request message.</p><pre>{<br>  &quot;method&quot;: &quot;tools/list&quot;,<br>  &quot;params&quot;: {}<br>}</pre><p>The MCP server returns with a list of available tools. In our case, the GitHub MCP server exposes quite a large number of tools — the following response message is truncated to fit this post.</p><pre>{<br>  &quot;tools&quot;: [<br><br>    {<br>      &quot;name&quot;: &quot;get_me&quot;,<br>      &quot;description&quot;: &quot;Get details of the authenticated GitHub user.<br>                           Use this when a request include \&quot;me\&quot;, \&quot;my\&quot;...&quot;,<br>      &quot;inputSchema&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>          &quot;reason&quot;: {<br>            &quot;description&quot;: &quot;Optional: reason the session was created&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>          }<br>        }<br>      }<br>    }<br>   ]<br>}</pre><p>Next, we can run one of these tools. For example, we invoke the tools/call method by passing get_me as the parameter, which is the name of the tool we want to run.</p><pre>{<br>    &quot;method&quot;: &quot;tools/call&quot;,<br>    &quot;params&quot;: {<br>        &quot;name&quot;: &quot;get_me&quot;,<br>        &quot;arguments&quot;: {}<br>    },<br>    &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>    &quot;id&quot;: 5<br>}</pre><p>This time, the GitHub MCP server returns my GitHub username and other details in the response. This is the exact same flow that occurred when we executed the get_me tool using VS Code in the previous section of this post.</p><pre>{<br>    &quot;method&quot;: &quot;tools/call&quot;,<br>    &quot;data&quot;: {<br>        &quot;content&quot;: [<br>            {<br>                &quot;type&quot;: &quot;text&quot;,<br>                &quot;text&quot;:&quot;{\&quot;login\&quot;:\&quot;sagara-gunathunga\&quot;, .....&quot;<br>            }<br>        ]<br>    }<br>}</pre><p>Finally, one of the parties closes the connection to complete the lifecycle and terminate the session.</p><p><strong><em>Just to be clear:</em></strong> with agentic applications like VS Code, Claude desktop, you don’t need to manually hand craft any of these messages or run any tools by yourselves. Instead, when we provide a prompt, the application (with the help of the LLM) can automatically pick the right tool to execute and handle this entire client-server session for us.</p><h3><strong>MCP Transports</strong></h3><p>MCP uses <strong>JSON-RPC</strong> to encode messages, and JSON-RPC messages <strong>MUST</strong> be UTF-8 encoded. The protocol currently defines two standard transport mechanisms for client-server communication:</p><ul><li><strong>STDIO</strong> — communication over standard input and standard output</li><li><strong>Streamable HTTP and SSE</strong></li></ul><p>In addition to these, it’s also possible for clients and servers to implement <strong>custom transports</strong> in a pluggable fashion.</p><p>During both exercises we did in this post — connecting the GitHub MCP Server with <strong>VS Code</strong> and <strong>MCP Inspector</strong> — we used the <strong>STDIO transport</strong>. In this section, we’ll only focus on STDIO, and we’ll discuss HTTP transport in a separate post.</p><p>STDIO stands for “<strong>standard input/output</strong>,” which is a fundamental way programs communicate by reading input and writing output through streams provided by the operating system. Standard input (stdin) is typically used for reading data, while standard output (stdout) is for writing data.</p><p>MCP lets a client and server exchange messages directly by sending and receiving data over these streams. When an MCP server runs as a subprocess, it reads client requests from its standard input and writes responses to standard output. This concept is depicted in the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*MCA7w59cfcuRPoz_-n0jGQ.png" /><figcaption>MCP STDIO transport</figcaption></figure><p><strong><em>Using STDIO for MCP client-server communication is often recommended over HTTP/SSE</em> </strong>because it offers a <strong>simpler, more efficient, and secure</strong> transport mechanism for local integrations. STDIO enables <strong>direct, bidirectional communication</strong> between the client and server processes on the same machine without the overhead of network protocols, reducing latency and complexity. Unlike HTTP/SSE, which requires setting up servers, managing network connections, and handling OAuth 2.1 security requirements, STDIO leverages the operating system’s built-in streams — making it ideal for tightly coupled, local environments where performance and simplicity are priorities.</p><h4>Wrap up</h4><p>We started this post by looking at what kind of experience an MCP server can bring in — by creating and committing a complete web application without any manual intervention using <strong>VS Code Copilot</strong> together with the <strong>GitHub MCP server</strong>. Then in the next phase, we connected GitHub MCP to a debugging tool called <strong>MCP Inspector</strong> so that we could clearly see the messages and protocol flow, and we discussed what exactly happens at each stage of the flow with the exact messages.</p><p>Finally, we looked into the transport mechanisms supported by MCP and dug into the details of <strong>STDIO transport</strong>.</p><p>The <strong>GitHub MCP server</strong> was taken as an example because it perfectly fits with the sample use case used in this post — but everything we discussed is <strong>common for any MCP server</strong>, after all, that’s the whole purpose of the <strong>MCP protocol</strong>.</p><p>Hope this is helpful and stay tuned for the next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=293608deaec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is OAuth 2.0 Protected Resource Metadata (PRM)]]></title>
            <link>https://sagarag.medium.com/what-is-oauth-2-0-protected-resource-metadata-prm-417ff7b7c196?source=rss-fe43db0e480e------2</link>
            <guid isPermaLink="false">https://medium.com/p/417ff7b7c196</guid>
            <dc:creator><![CDATA[Sagara Gunathunga]]></dc:creator>
            <pubDate>Sun, 04 May 2025 11:19:11 GMT</pubDate>
            <atom:updated>2025-06-21T23:17:38.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-oVtk9vNJCkCwo9VRs1NQ.png" /><figcaption>(Source — <a href="https://www.nzherald.co.nz/kahu/parks-and-buildings-across-auckland-will-have-dual-names-and-tell-stories-of-tamaki-makaurau-in-te-reo/JOKLC5UMHVFQZFQQU56PLA3REM/">https://www.nzherald.co.nz/kahu/parks-and-buildings-across-auckland-will-have-dual-names-and-tell-stories-of-tamaki-makaurau-in-te-reo/JOKLC5UMHVFQZFQQU56PLA3REM/</a>)</figcaption></figure><p>At the very core of the OAuth2 authorization framework is a mechanism that allows a client application to access a protected resource on behalf of an end user — based on that user’s approval — without exposing the user’s credentials to the client. OAuth2 achieves this by introducing a new authorization layer and issuing a temporary credential, known as an access token, with the help of an authorization server — typically an identity provider.</p><p>OAuth2 defines three distinct roles:</p><ul><li><strong>Client</strong> — the application acting on behalf of the end user</li><li><strong>Authorization Server</strong> — issues access tokens and manages user interactions</li><li><strong>Resource Server</strong> — hosts the protected resource</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*7G-NNFtiY8hpi08XStmZaw.png" /><figcaption>Roles defined in the OAuth2 authorization framework</figcaption></figure><p>The core OAuth2 specification, along with several related standards, outlines how these roles interact. Let’s revisit these interactions in more detail.</p><h4><strong>Interactions between Client and Authorization Server</strong></h4><p>The interaction begins when a client application retrieves the metadata of the authorization server by sending an HTTP GET request to its metadata endpoint. The structure of this metadata and the endpoint URL itself are defined by the <a href="https://datatracker.ietf.org/doc/html/rfc8414">OAuth2 Authorization Server Metadata specification</a>, which is now widely adopted.</p><p><a href="https://sagarag.medium.com/how-do-you-discover-the-oauth2-server-configuration-d42d30ad5b9d">How do you discover the OAuth2 server configuration?</a></p><p>This metadata document allows the client application to discover:</p><ul><li>Supported grant types</li><li>URLs of authorization and token endpoints</li><li>Client registration endpoint</li><li>Security features such as PKCE support</li></ul><p>Next, the client may register itself with the authorization server using the client registration endpoint. It receives credentials (e.g., client_id and client_secret) necessary for requesting access tokens. The <a href="https://datatracker.ietf.org/doc/html/rfc7591">OAuth2 Dynamic Client Registration (DCR) specification </a>standardizes this interaction, enabling any compliant client to register with any compliant authorization server in an interoperable way.</p><p><a href="https://sagarag.medium.com/how-to-register-and-manage-oauth2-clients-896e553b7cf1">How to register and manage OAuth2 clients?</a></p><p>Once registration is complete, the client can initiate authorization using a supported grant type — most commonly the <strong>authorization code flow</strong> — with a user agent such as a web browser mediating communication between the end user, the client app, and the authorization server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*H8KdoiLiQhfeybhvume81A.png" /><figcaption>Interactions between Client and Authorization Server</figcaption></figure><p>After obtaining an access token, the client presents it to the resource server to gain access. What’s important here is that, once the metadata endpoint is known, everything from metadata retrieval to registration and token handling can be automated at runtime, without manual intervention or hardcoded configurations. This brings us to a key question: how does the client know which metadata endpoint to contact in the first place? We’ll come back to that.</p><h4>Interactions between Resource Server and Authorization Server</h4><p>When the resource server receives an access token from a client, it must validate it. This validation process differs depending on the token type:</p><ul><li><strong>Opaque (by-reference) tokens</strong>: validated using the <strong>token introspection endpoint</strong>, as defined by the OAuth2 Token Introspection specification.</li><li><strong>JWT (by-value) tokens</strong>: validated by verifying the token’s signature using public keys retrieved from the <strong>JWKS (JSON Web Key Set) endpoint</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*e25HSXauKv0IvXDbElA4oQ.png" /><figcaption>Interactions between Resource Server and Authorization Server</figcaption></figure><p>Both introspection and JWKS-based validation can be fully automated, allowing the resource server to validate tokens at runtime without manual setup.</p><p><strong><em>Now back to our earlier question — how does a client learn which authorization server protects a given resource?</em></strong></p><p>Traditionally, developers rely on documentation — such as wikis or OpenAPI specs — to determine the security requirements of a protected resource. This includes learning which authorization server to use and where to find its metadata.</p><p>That approach has worked so far. But modern applications — like AI agents needing to dynamically access third-party tools through protocols like MCP — demand full automation. They need to discover all necessary information at runtime, without hardcoded configurations for <strong>dynamic integration</strong>.</p><h4>Protected Resource Metadata (PRM)</h4><p><strong>This is the challenge addressed by the</strong><a href="https://datatracker.ietf.org/doc/html/rfc9728"><strong> OAuth 2.0 Protected Resource Metadata (PRM) specification</strong></a>, which recently became a standard. Though the first draft appeared in 2016, it only recently became a priority due to emerging use cases. One of the spec’s authors reflected the same in his <a href="https://self-issued.info/?p=2653">blog post</a>. <a href="https://datatracker.ietf.org/doc/html/rfc9728">Protected Resource Metadata (PRM)</a> is a mechanism that allows a protected resource — typically an API — to publish a machine-readable JSON document detailing its authorization requirements. This document specifies which OAuth authorization servers the resource trusts, the expected token formats and how to send them, the scopes clients must request to access it, and any additional security requirements such as use of sender-constrained tokens such as DPoP and certificate-bound tokens.</p><p><a href="https://datatracker.ietf.org/doc/html/rfc9728"><strong>OAuth 2.0 Protected Resource Metadata (PRM) specification</strong> </a>also completes the interactions between among OAuth 2.0 roles by adding the missing piece, alongside the <a href="https://datatracker.ietf.org/doc/html/rfc8414">Authorization Server Metadata a</a>nd <a href="https://datatracker.ietf.org/doc/html/rfc7591">Dynamic Client Registration</a> specifications providing full dynamic integration for client applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*Ni_hmmK-srfb5zo1-WeWCA.png" /><figcaption>Protected Resource Metadata</figcaption></figure><h4>How PRM Works</h4><p>When a client tries to access a protected resource without any secuity details , the resource server responds with an HTTP 401 Unauthorized as usual. In a PRM-compliant resource server, this response includes a WWW-Authenticate header with a resource_metadata field that points to the resource metadata URL. This is shown in the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_I01F4U8_RwKRLpsUt1VIA.png" /><figcaption>401 Unauthorized Response with Resource Metadata URL</figcaption></figure><p>A sample HTTP 401 Unauthorized response message is also given below.</p><pre>HTTP/1.1 401 Unauthorized<br>WWW-Authenticate: Bearer resource_metadata=&quot;https://resource.example.com/<strong>.well-known/oauth-protected-resource</strong>&quot;</pre><p>Once the client application receives this response, it can make a <strong>Protected Resource Metadata Request</strong> — this is nothing but a simple HTTP GET — to fetch the resource metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*guuGwbqGkAxp36uVwCv6Sw.png" /><figcaption>Protected Resource Metadata Request and Response</figcaption></figure><p>In the above example, the PRM response contains the a<strong>uthorization server issuer identifier</strong> which can be used to construct the metadata endpoint of the authorization server along with the scopes that the client has to request to acces the the specific resource. Additionally, it also indicate that the clioent should only send the bearer token as HTTP header. This process of deriving the <strong>authorization server metadata URL </strong>form<strong> the authorization server issuer identifier</strong> field of the protected resource metadata is shown in the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PrEMgryjUVVBB6zhj_X7Q.png" /><figcaption>Construction of the authorization server metadata URL</figcaption></figure><p>One important processing instruction to highlight here is that, at any given time, a resource can return a WWW-Authenticate challenge to indicate that the resource metadata has changed. In such scenarios, the client application should fetch the new resource server metadata and reflect the changes at the resource server. This allows the client application to update changes from the resource server in a consistent and automated fashio</p><p>Below are the key metadata parameters defined by the OAuth 2.0 Protected Resource Metadata specification:</p><ul><li><strong>resource</strong> — This is the only mandatory parameter and represent the unique identifier of the protected resource. The <strong>resource identifier </strong>is defined as a URL that points to the protected resource. It must use HTTPS and should not include a fragment. Ideally, it shouldn’t have a query string either.</li><li><strong>authorization_servers</strong> — A list of authorization server issuer identifiers that can be used with this resource. Note that as per the specification this is an optional parameter.</li><li><strong>scopes_supported</strong> — A list of supported OAuth 2.0 scopes that clients can request to access this resource. It is recommended to use this parameter.</li><li><strong>bearer_methods_supported</strong> — This indicates which methods are supported for passing access tokens to the resource. Valid values are &quot;header&quot;, &quot;body&quot;, and &quot;query&quot;. An empty array ([]) means no bearer methods are supported.</li><li><strong>jwks_uri</strong> — URL pointing to the JSON Web Key Set (JWKS) of the resource. This includes public keys used for signing or encrypting responses. The URL must use HTTPS.</li><li><strong>resource_signing_alg_values_supported</strong> — Lists the JWS signing algorithms supported by the resource when signing its responses. The value none must not be used.</li><li><strong>authorization_details_types_supported</strong> — Lists the types of authorization_details supported by the resource when that parameter is used in requests.</li></ul><p>The following human readable parameters are also defined but optional:</p><ul><li><strong>resource_name</strong> — A human-readable name of the resource, intended for display to the end user and should supports internationalization.</li><li><strong>resource_documentation</strong> <em>(optional)</em><br> URL to human-readable documentation about the resource—useful for developers. Supports internationalization.</li><li><strong>resource_policy_uri</strong> <em>(optional)</em><br> URL describing any policy restrictions or usage requirements associated with the resource. Supports internationalization.</li><li><strong>resource_tos_uri</strong> <em>(optional)</em><br> URL pointing to the resource’s terms of service. Supports internationalization.</li></ul><p>In addition to that following parameters are defined to be used with certificate-bound tokens that we discussed in a <a href="https://sagarag.medium.com/mtls-and-oauth2-certificate-bound-tokens-8204b7bc5833">previous post</a> and DPoP-bound tokens.</p><p><em>For certificate-bound tokens:</em></p><ul><li><strong>tls_client_certificate_bound_access_tokens</strong> — A boolean indicating whether the resource supports mutual-TLS client certificate-bound access tokens. Defaults to false if omitted.</li></ul><p><a href="https://sagarag.medium.com/mtls-and-oauth2-certificate-bound-tokens-8204b7bc5833">mTLS and OAuth2 — Certificate-Bound Tokens</a></p><p><em>For DPoP-bound tokens tokens:</em></p><ul><li><strong>dpop_bound_access_tokens_required</strong> — A boolean indicating whether the resource requires all access tokens to be DPoP-bound. Defaults to false if not specified.</li><li><strong>dpop_signing_alg_values_supported</strong> — Lists the supported JWS algorithms for validating DPoP proofs.</li></ul><p><strong>The Human-readable metadata </strong>values can be provided in multiple languages using language tags (like #en or #it) to support localization, and it&#39;s recommended to also include a default version without a tag for broader compatibility.</p><p>In addition to regular JSON elements, <strong>metadata about a protected resource can be provided as a signed JWT </strong>, which contains the same metadata values in a bundled, cryptographically signed format. This JWT must be signed or MACed using JSON Web Signature (JWS) and must include an #iss (issuer) claim to identify who is asserting the metadata. While systems that don’t support signed metadata can ignore it, those that do must treat the signed values as authoritative over the plain JSON value. The signed metadata can be included in the resource meta suing the signed_metadata parameter.</p><p>The following sequence diagram illustrates the end-to-end resource access flow along with the relevant standards. While the PAM specification highlights <a href="https://datatracker.ietf.org/doc/html/rfc7591">Dynamic Client Registration (DCR)</a> as a possible approach for client registration, it does not mandate its use. However, DCR is included in this diagram to provide a complete picture of the flow and to emphasize how it enables full automation of the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*EO53ut1iT2Gmf58bFAORNQ.png" /><figcaption>The complete resource access sequence</figcaption></figure><h4><strong>Authorization Server Metadata</strong></h4><p>In addition to defining the above discussed, resource server metadata PRM specification define a new <a href="https://datatracker.ietf.org/doc/html/rfc8414">authorization server metadata</a> called protected_resources . This parameter can be used by an Authorization Server metadata document to include a set of resources protected by the authorization server. This parameter facilitate the crosschecking of authorization server metadata and protected resource metadata.</p><p>In summary, the OAuth 2.0 Protected Resource Metadata specification fills a critical gap in the dynamic integration story of OAuth 2.0. By enabling clients to discover protected resource details at runtime, it eliminates reliance on static configuration and documentation. Combined with <a href="https://datatracker.ietf.org/doc/html/rfc8414">Authorization Server Metadat</a>a and <a href="https://datatracker.ietf.org/doc/html/rfc7591">Dynamic Client Registration</a>, PRM supports fully automated, interoperable flows across OAuth 2.0 roles — laying the foundation for scalable and adaptable authorization in modern applications.</p><ul><li><a href="https://sagarag.medium.com/how-do-you-discover-the-oauth2-server-configuration-d42d30ad5b9d">How do you discover the OAuth2 server configuration?</a></li><li><a href="https://sagarag.medium.com/how-to-register-and-manage-oauth2-clients-896e553b7cf1">How to register and manage OAuth2 clients?</a></li><li><a href="https://sagarag.medium.com/mtls-and-oauth2-certificate-bound-tokens-8204b7bc5833">mTLS and OAuth2 — Certificate-Bound Tokens</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=417ff7b7c196" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[mTLS and OAuth2 — Certificate-Bound Tokens]]></title>
            <link>https://sagarag.medium.com/mtls-and-oauth2-certificate-bound-tokens-8204b7bc5833?source=rss-fe43db0e480e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8204b7bc5833</guid>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[mtls-authentication]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[api-security]]></category>
            <dc:creator><![CDATA[Sagara Gunathunga]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 02:21:16 GMT</pubDate>
            <atom:updated>2025-04-26T02:21:16.366Z</atom:updated>
            <content:encoded><![CDATA[<h3>mTLS and OAuth2 — Certificate-Bound Tokens</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8SxBuwP2R2vPF4AG2ScuA.png" /><figcaption>(Source — <a href="https://cardinsider.com/blog/should-i-sign-the-back-of-my-credit-card/">https://cardinsider.com/blog/should-i-sign-the-back-of-my-credit-card/</a>)</figcaption></figure><p>In the <a href="https://sagarag.medium.com/mtls-and-oauth2-client-authentication-5958f6f9b098">previous post</a>, we discussed the <strong>certificate-based mutual authentication</strong> process that takes place during the <strong>TLS handshake</strong>, and how that same mechanism can be leveraged for <strong>OAuth2 client authentication</strong> — a more secure approach, especially in scenarios where mTLS is already in use.</p><p>In this post, we’ll explore how <strong>certificates can be used to restrict the use of a token</strong>, such as an <strong>access token</strong>, so that only the <strong>intended party</strong> can use it. This helps prevent misuse — even if someone else gains access to the token, they won’t be able to use it without the corresponding certificate.</p><p><a href="https://sagarag.medium.com/mtls-and-oauth2-client-authentication-5958f6f9b098">mTLS and OAuth2 — Client Authentication</a></p><p>Let’s start our discussion by reviewing the OAuth2 token types.</p><h3>Chapter 1— OAuth2 Token Types</h3><p>Tokens can be categorized based on several criteria, but for the scope of this post, we’ll focus on two key aspects: the format of the token and how the token is intended to be used.</p><p>Starting with the <strong>token format</strong>, there are two main types: <strong><em>reference-type</em> </strong>and <strong>v<em>alue-type </em></strong>tokens.</p><p>In reference-type tokens, the actual authorization details — such as the permissions granted by the end user — are stored exclusively on the authorization server. Instead of receiving the full content, the client is issued a reference value, which is why these are commonly called <strong>opaque</strong> <strong>tokens</strong> — the client has no visibility into what’s inside. This provides a <strong>security advantage</strong> — in the event of token exposure, <strong>no meaningful information can be extracted</strong> from the token since it contains <strong>no encoded data</strong>. It’s just a reference, not a payload.</p><p>When the client or resource server needs to retrieve the actual authorization data, <strong>they can present this opaque token to the introspection endpoint of the authorization server</strong>. Typically, these tokens are randomly generated strings with no embedded information.</p><p>While opaque tokens were more common in the early days of OAuth2, they’re still actively used in many systems today — especially in scenarios where token confidentiality is prioritized.</p><p>A sample authorization response with a reference token is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*0wrdgyz2LxWFqey5VYXWFQ.png" /><figcaption>An authorization response with a reference token</figcaption></figure><p>In contrast to <strong>reference-type (opaque) tokens</strong>, <strong>value-type tokens</strong> contain the <strong>authorization details and token metadata embedded directly within the token</strong> itself. One of the most widely adopted formats for value-type tokens is the <strong>JSON Web Token (JWT)</strong>.</p><p>With JWTs, the authorization granted by the end user — as well as additional metadata — is represented in a <strong>JSON-encoded format</strong>. This allows the client or resource server to <strong>validate and extract token information locally</strong>, without needing to reach out to the authorization server. That’s a key reason why JWTs are often seen as more efficient and flexible compared to opaque tokens.</p><p>It’s important to understand that, in the context of OAuth2, <strong>JWT is an abstract format</strong>. You won’t typically encounter plain, unsigned JWTs in real-world scenarios. Instead, you’ll see:</p><ul><li><strong>JWS (JSON Web Signature)</strong> — JWTs that are <strong>digitally signed</strong> by the token issuer</li><li><strong>JWE (JSON Web Encryption)</strong> — JWTs that are <strong>encrypted</strong> by the token issuer</li></ul><p>The following diagram shows you an authorization response with a JWT access token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MTif0neLEHpl0Eok" /><figcaption>An authorization response with a JWT access token.</figcaption></figure><p>If you decode the above JWT token, you would be able to see a JWT claim set similar to below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C_f_V-kz7EWe4HeU" /><figcaption>Decoded JWT token</figcaption></figure><p>Moving on to our next token categorization criteria, let’s now classify tokens based on <strong>how they’re intended to be used</strong> — specifically in the context of how a <strong>client presents the token when accessing a protected resource</strong> on a resource server. Once again, we have two primary types:</p><ul><li><strong>Bearer tokens</strong></li><li><strong>Proof-of-Possession (PoP) tokens</strong> (also known as <strong>sender-constrained tokens</strong>)</li></ul><p>These two types can be best understood through a <strong>real-world analogy</strong>, illustrated in the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D5v6cRptYP-4-OXo" /></figure><p>To understand the difference between bearer tokens and proof-of-possession (PoP) tokens, let’s use a simple real-world analogy — <strong>cash notes vs. credit cards</strong>. While cash notes may be less common these days, the comparison still helps illustrate the core concept.</p><p>When you walk into a shop and pay with <strong>cash</strong>, the merchant doesn’t verify your identity or whether the cash actually belongs to you. They may check if the note is authentic, but not who’s handing it over. You could have found that note on the street — and as long as you possess it, you’re allowed to use it. This is exactly how <strong>bearer tokens</strong> work. When a client presents a bearer token to a resource server, the server might validate the token itself, but <strong>not the party presenting it</strong>. Bearer tokens are widely adopted today due to their simplicity — you typically pass them as an HTTP header, and that’s it.</p><p>Now, consider paying with a <strong>credit card</strong>. In this case, the merchant often asks for a signature, and may even compare it with the one on the card. In some cases, your identity might be verified against the printed name. That’s how <strong>PoP tokens</strong> behave. Simply presenting the token isn’t enough — the client must <strong>prove it legitimately possesses</strong> what the token represents. The authorization server ensures this by <strong>binding the token to something the client can prove ownership of</strong>. Unlike bearer tokens, a client <strong>can’t just use someone else’s PoP token</strong>, because it won’t be able to demonstrate ownership.</p><p>PoP tokens offer a <strong>much stronger security posture</strong> than bearer tokens — but they’re not as commonly used just yet, mostly due to the additional complexity in implementation.</p><h3>Chapter 2— Certificate-bound Tokens</h3><p>We just discussed that <strong>Proof-of-Possession (PoP) tokens</strong> provide a stronger level of security than bearer tokens, as they require the client to present additional evidence proving it’s the legitimate party authorized to use the token.</p><p>If you recall from t<a href="https://medium.com/@sagarag/mtls-and-oauth2-client-authentication-5958f6f9b098">he previous post</a>, we explored how during the <strong>mutual TLS (mTLS) handshake</strong>, a client proves possession of its private key by sending the CertificateVerify message along with its certificate. That verification step is already a built-in proof of possession mechanism.</p><p><a href="https://sagarag.medium.com/mtls-and-oauth2-client-authentication-5958f6f9b098">mTLS and OAuth2 — Client Authentication</a></p><p>So here’s the interesting part: when an OAuth2 client establishes an mTLS connection with the <strong>authorization server</strong>, it has already demonstrated ownership of its private key. <strong>Can we use this same concept to create a new type of token binding mechanism?</strong></p><p>That’s exactly what the <strong>second part of the </strong><a href="https://datatracker.ietf.org/doc/html/rfc8705"><strong>OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens</strong></a> specification enables — by introducing a new concept called <strong>Certificate-Bound Access Tokens</strong>.</p><p>At its core, a certificate-bound token is simply a token that the <strong>authorization server binds to the client certificate</strong> presented during the mTLS handshake. This means that in order to use the token, the client must establish an mTLS connection with the <strong>resource server using the exact same certificate</strong>. The resource server can then verify that the certificate associated with the token matches the one used in the current connection — ensuring the token is only usable by the rightful holder.</p><p>Now you might be wondering: <em>how exactly is this binding achieved?</em></p><p>Instead of storing or transmitting the full certificate, the binding is typically done using the <strong>unique fingerprint of the certificate</strong> (as we discussed in the <a href="https://medium.com/@sagarag/mtls-and-oauth2-client-authentication-5958f6f9b098">previous post</a>). This fingerprint serves as a lightweight yet reliable way to <strong>link the token to its corresponding certificate</strong>, ensuring a secure and verifiable association between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HUhX3AUdJkSa3nb_" /><figcaption>Token binding process</figcaption></figure><p>In the <a href="https://medium.com/@sagarag/mtls-and-oauth2-client-authentication-5958f6f9b098">previous post </a>we discussed how certificate fingerprint is calculated in detail. Jut for completeness, let’s revisit the process here:</p><ol><li><strong>Convert the underlying certificate</strong> associated with mTLS into <strong>DER binary format</strong>.</li><li><strong>Calculate the hash value</strong> by applying the <strong>SHA-256</strong> hash function to the DER binary data.</li><li><strong>Apply Base64 URL encoding</strong> to the resulting hash value.</li></ol><p>These steps help generate the unique fingerprint that will be used to bind the <strong>certificate-bound access token</strong> to the specific client certificate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iEcROvbLEduR7vVz" /></figure><p>Once the authorization server calculates the certificate fingerprint, it establishes a link with the token based on the token type.</p><ul><li><strong>For opaque tokens</strong>, this association is maintained in the authorization server’s database. When needed, a resource server can retrieve the fingerprint by using the <strong>introspection endpoint</strong>.</li><li><strong>For JWT tokens</strong>, the fingerprint is included directly within the token. This eliminates the need for the resource server to contact the authorization server, allowing it to independently verify the token’s binding. To achieve this, the <a href="https://datatracker.ietf.org/doc/html/rfc8705"><strong>OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens</strong></a><strong> </strong>specification reuses the <strong>Confirmation Claim (cnf)</strong> from the <a href="https://datatracker.ietf.org/doc/html/rfc7800/"><strong>Proof-of-Possession Key Semantics for JSON Web Tokens (JWTs)</strong></a> spec. It introduces a new JWT confirmation method member: &quot;x5t#s256&quot;, which represents the certificate’s fingerprint.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*76fSnE_wcA2LkHCN" /></figure><p>In simple terms, an authorization server can signal its support for certificate-bound tokens by adding the tls_client_certificate_bound_access_tokens parameter to its server metadata. When a client registers through the <strong>Dynamic Client Registration (DCR)</strong> endpoint, it can express its intention to use certificate-bound tokens by including this same parameter in its registration request. This allows the client and server to align on using mTLS for enhanced security with certificate-bound tokens.</p><h4><strong>Certificate-bound token validation at the resource server</strong></h4><p>From the resource server’s perspective, verifying a certificate-bound token involves ensuring that the client certificate used in the mTLS connection matches the certificate associated with the token. Here’s how the verification process works for both JWT and opaque tokens:</p><p><strong>For JWT tokens: </strong>The resource server can verify the certificate bound to the JWT token by checking the <strong>cnf claim</strong> in the token. This claim contains the certificate&#39;s fingerprint (using the <strong>x5t#s256</strong> method).</p><p>Steps for verification:</p><ol><li><strong>Extract the fingerprint</strong> from the cnf claim in the JWT.</li><li><strong>Obtain the certificate</strong> from the mTLS connection (i.e., the certificate used by the client).</li><li><strong>Calculate the fingerprint</strong> of the client’s certificate using the same hash algorithm (SHA-256) and Base64 URL encoding.</li><li><strong>Compare</strong> the calculated fingerprint with the one stored in the cnf claim. If they match, the client is authorized to access the resource.</li><li>If the fingerprints do not match, return an invalid_token error.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Um3B8yKvh83WscCX" /><figcaption>JWT token verification at the resource server</figcaption></figure><p><strong>For opaque tokens: </strong>Opaque tokens do not carry embedded certificate information like JWT tokens. Instead, the resource server must call the <strong>introspection endpoint</strong> of the authorization server to validate the token and retrieve the associated certificate fingerprint.</p><p>Steps for verification:</p><ol><li><strong>Call the introspection endpoint</strong> with the opaque token to retrieve metadata about the token.</li><li><strong>Check the certificate fingerprint</strong> retrieved from the introspection response.</li><li><strong>Obtain the certificate</strong> from the mTLS connection.</li><li><strong>Calculate the fingerprint</strong> of the client’s certificate.</li><li><strong>Compare</strong> the calculated fingerprint with the one received from the introspection response. If they match, the token is valid.</li><li>If the fingerprints do not match, return an invalid_token error.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TL_TboZNPMziQ7KF" /><figcaption>Opaque token verification at the resource server</figcaption></figure><p>By ensuring that the certificate associated with the token is used during the mTLS handshake, both the client and resource server can confirm that the client presenting the token is indeed the rightful owner of the certificate and the associated access token. This strengthens security by preventing the misuse of tokens across different clients.</p><h3>Chapter 3— Certificate-bound tokens and public clients</h3><p>When an <strong>mTLS connection</strong> is established between an OAuth2 client and an authorization server, the <strong>verified certificate</strong> used during the initial handshake can serve as a <strong>client authentication method</strong> for <strong>confidential clients</strong>, such as server-side applications. This mechanism provides strong assurance of the client’s identity without relying on secrets or credentials passed over the network.</p><p>That said, while a <strong>public client</strong> can also establish an mTLS connection and complete the handshake, the <strong>authorization server should not authenticate it</strong> using mTLS — or any other client authentication method. Instead, public clients are typically handled using alternative mechanisms like <a href="https://medium.com/@sagarag/secure-oauth2-a-simple-story-of-two-keys-pkce-2bdd96232105"><strong>Proof Key for Code Exchange (PKCE) </strong></a>, which are better suited for apps running in browsers or mobile environments.</p><p><a href="https://sagarag.medium.com/secure-oauth2-a-simple-story-of-two-keys-pkce-2bdd96232105">Secure OAuth2: A Simple Story of Two Keys — PKCE</a></p><p>Another important point to highlight, according to <a href="https://datatracker.ietf.org/doc/html/rfc8705"><strong>OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens</strong></a> specification, the use of <strong>mTLS client authentication</strong> and <strong>certificate-bound tokens</strong> is independent — they do not require each other. For example:</p><ul><li>A client can <strong>authenticate using mTLS</strong> but still choose to use <strong>bearer tokens</strong> for simplicity.</li><li>Conversely, a <strong>public client</strong> with no client authentication method can still use <strong>certificate-bound tokens</strong>, as long as it’s capable of establishing mTLS connections with <strong>both the authorization server and the resource server</strong>.</li></ul><p>This flexibility is key to making mTLS a practical option across a wide range of OAuth2 deployment scenarios.</p><p>Continuing our discussion on how you can leverage mTLS for OAuth2, we took a closer look at how client certificates used in mTLS can be used to bind tokens to a client. We can ensure that only the intended party can use the token — even if it somehow falls into the wrong hands, it remains completely useless to anyone else. This approach not only raises the security bar but also brings a new level of trust and control.</p><p>I hope this post, along with the<a href="https://medium.com/@sagarag/mtls-and-oauth2-client-authentication-5958f6f9b098"> previous one</a>, has shed some light on how to use mTLS in OAuth2. There’s plenty more to explore in this space, so stay tuned for the next post!</p><p><a href="https://sagarag.medium.com/mtls-and-oauth2-client-authentication-5958f6f9b098">mTLS and OAuth2 — Client Authentication</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8204b7bc5833" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[mTLS and OAuth2 — Client Authentication]]></title>
            <link>https://sagarag.medium.com/mtls-and-oauth2-client-authentication-5958f6f9b098?source=rss-fe43db0e480e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5958f6f9b098</guid>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[certificate]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[wso2is]]></category>
            <category><![CDATA[mtls-authentication]]></category>
            <dc:creator><![CDATA[Sagara Gunathunga]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 02:58:17 GMT</pubDate>
            <atom:updated>2025-04-25T02:58:17.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>mTLS and OAuth2 — Client Authentication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*RB2eXHXNfecT7CFG35thoQ.png" /><figcaption>(Source — <a href="https://www.cathaypacific.com/cx/en_HK/prepare-trip/visa-information/overview.html">https://www.cathaypacific.com/cx/en_HK/prepare-trip/visa-information/overview.html</a>)</figcaption></figure><p>Whenever we hit a website or web application, we simply trust the browser to verify its authenticity and establish a secure, encrypted communication channel. As we all know, the underlying mechanism used here is known as <strong>TLS/SSL</strong> over HTTP — commonly referred to as <strong>HTTPS</strong>.</p><p>Generally, our web browser verifies the <strong>server’s identity</strong> before establishing this secure connection. But this is a <strong>one-way verification</strong>, where the browser (acting as the <em>client</em>) checks the identity of the server hosting the web application or the website (acting as the <em>server</em>). In short, the client verifies the identity of the server.</p><p>However, there are scenarios where both the <strong>client and the server</strong> need to authenticate each other before a secure connection can be established. This is known as <strong>mutual TLS</strong>, or <strong>mTLS</strong> for short. This isn’t a new concept — we’ve been using mTLS in various systems for over a quarter century now. While <strong>mTLS is less common in public web applications</strong>, it is <strong>widely used in system-to-system communication</strong>, especially in <strong>regulated industries</strong> like <strong>finance</strong> and <strong>healthcare</strong>.</p><p>In this post, we’re going to explore whether the authentication mechanism used in mTLS can be applied to <strong>OAuth2 client authentication</strong>. This can offer stronger security than using shared secrets like client_secret, and better interoperability with systems where mTLS is already in use.</p><p>Given that this is a broad topic, I’ve broken it down into several chapters for easier reading. Let’s start by exploring <strong>certificates</strong>, the key enabler of authentication in both <strong>TLS</strong> and <strong>mTLS</strong>.</p><h3>Chapter 1 — Handshake</h3><p>Although we commonly refer to them as <strong>certificates</strong>, the more technically accurate term is <strong>X.509 certificates</strong>. They’re called that because they follow the <strong>X.509 standard</strong>, which was introduced by the <strong>International Telecommunication Union (ITU)</strong> as part of the <strong>X.500 directory services</strong> back in <strong>1988</strong>.</p><p>The diagram below provides a simplified view of a typical certificate, highlighting only the key elements relevant to this discussion</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F9rtPweT_SaUQVkU" /><figcaption>The format of a X.509 certificate</figcaption></figure><p>One important concept to understand is the <strong>Distinguished Name</strong>, or <strong>DN</strong>. A DN is a string composed of <strong>attribute-value pairs</strong>, and it acts as a <strong>unique identifier</strong> for entities such as certificate authorities, servers, or applications within <strong>X.509 certificates</strong>.</p><p>For example:</p><pre>CN = DigiCert Global G2 TLS RSA SHA256 2020 CA, O = DigiCert Inc, C = US</pre><p>This is a DN made up of several key attributes:</p><ul><li><strong>CN</strong> — Common Name</li><li><strong>O</strong> — Organization</li><li><strong>C</strong> — Country</li></ul><p>Together, these elements form a unique identifier that can be used to represent the <strong>issuer</strong> or <strong>subject</strong> in a certificate.</p><p>Now, let’s break down some of the key components you’ll find in the diagram above.</p><p>🏷️ <strong>Issuer — </strong>Identifies the entity that issued the certificate. This is usually represented as a <strong>Distinguished Name (DN)</strong>, following the <strong>LDAP</strong> protocol.</p><p>Examples:</p><pre>CN = DigiCert Global G2 TLS RSA SHA256 2020 CA, O = DigiCert Inc, C = US</pre><pre>CN = GTS CA 1C3, O = Google Trust Services LLC, C = US</pre><p>🧾 <strong>Subject — </strong>Identifies the entity the certificate was issued to. Like the issuer, this is typically a <strong>Distinguished Name (DN)</strong> or a <strong>Subject Alternative Name (SAN)</strong>.</p><p>Examples:</p><pre>CN = *.wso2.com, O = WSO2, Inc, L = Mountain View, ST = California, C = US</pre><pre>CN = *.google.com</pre><p>🔑<strong> Public Key — </strong>Contains the <strong>public key</strong> that corresponds to the <strong>private key</strong> held by the subject. This key is used in the TLS handshake for encryption and key exchange.</p><p>🖋️ <strong>Signature </strong>— The certificate’s digital signature, created by the issuer using its private key. The certificate content is first encoded, then hashed, and that hash is signed. This ensures the integrity and authenticity of the certificate</p><p>Most certificates you encounter in the wild (e.g., websites) are issued by a <strong>Certificate Authority (CA)</strong> as part of the <strong>Public Key Infrastructure (PKI)</strong>. But it’s also quite easy to generate <strong>self-signed certificates</strong>, especially for internal use or server-to-server communication. The key difference? With <strong>self-signed certificates</strong>, the <strong>issuer and the subject are the same.</strong></p><p><em>🔎 Example 1: PKI-Issued Certificate (from </em><a href="https://wso2.com/"><em>WSO2 Website</em></a><em>)</em></p><ul><li><strong>Issuer:</strong> CN = DigiCert Global, O = DigiCert Inc, C = US</li><li><strong>Subject:</strong> CN = *.wso2.com, O = WSO2, Inc, L = Mountain View, ST = California, C = US</li></ul><p><em>🔎 Example 2: Self-Signed Certificate (from </em><a href="https://wso2.com/identity-server/"><em>WSO2 Identity Server</em></a><em>)</em></p><ul><li><strong>Issuer:</strong> CN = localhost, OU = WSO2, O = WSO2, L = Mountain View, ST = CA, C = US</li><li><strong>Subject:</strong> CN = localhost, OU = WSO2, O = WSO2, L = Mountain View, ST = CA, C = US</li></ul><p>Now, let’s take a brief look at how we validate a certificate received from another party. The approach to validation depends on whether the certificate is CA-issued or self-signed.</p><p><strong>For CA-issued certificates</strong>, the main process is certificate chain validation. This involves verifying the certificate’s signature using the public key of the issuer. It also requires checking that the issuer’s Distinguished Name (DN) in the current certificate matches the subject’s DN in the next certificate in the chain. The validation process begins with the leaf certificate (which corresponds to the entity being verified, like a server or client). Once that’s validated, the process moves on to the intermediate certificates, eventually reaching the root certificate, which provides the foundation of trust for the entire certificate infrastructure.</p><p>Root certificates come from highly trusted Certificate Authorities (CAs) and are recognized in systems that rely on Public Key Infrastructure (PKI) — like web browsers and operating systems. Only a select few CAs can issue root certificates. Once the entire certificate chain is validated, the subject of the certificate is confirmed as the identity of the entity being verified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WMt8wdf0boWPQ1Xd" /><figcaption>CA-issued certificates verification process</figcaption></figure><p>When it comes to <strong>self-signed certificates</strong>, there’s no one-size-fits-all method to confirm the validity , as the approach often depends on the use case.</p><p>When connecting to a web server with a self-signed certificate, web browsers typically show warnings to users, informing them that the certificate is not trusted by the browser or the operating system. However, many browsers allow users to manually inspect and accept the certificate. Additionally, certain client-side tools, like cURL, offer an option (using -k or --insecure) that lets users bypass certificate verification when establishing the TLS connection. This flexibility allows users to work with self-signed certificates, though it’s important to be cautious when doing so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/0*yQCAY-YwbxjY0WXV" /><figcaption>Browser warning for an unverified certificate</figcaption></figure><p>Non-browser applications, such as in system-to-system communication, as well as APIs, have the ability to explicitly trust a self-signed certificate by presenting a copy of the certificate before initiating communication. This can be done by either directly uploading the certificate in PEM or another format, or by providing a URL where the certificate content can be retrieved. For example, the JSON Web Key Set (JWKS) endpoint is often used to offer an entity’s public key information through a network-accessible endpoint. In OAuth 2.0 and OpenID Connect (OIDC), JWKS is commonly used to provide clients with the public keys necessary to verify JSON Web Tokens (JWTs).</p><p>Before we conclude this section, let’s touch on an important point regarding certificates. If you’ve ever viewed a certificate using the pop-up in web browsers, you might have noticed a small string called a <strong>certificate fingerprint or thumbprint</strong>. Interestingly, this is not part of the certificate itself; rather, it’s calculated by the browser and presented to uniquely reference the certificate. To better understand how this works, let’s quickly go over the steps involved in creating certificate fingerprints:</p><ol><li>If the certificate is in PEM format (a Base64-encoded ASCII sequence), it should first be converted into DER format, which is a binary encoding format.</li><li>Then, a hash value is calculated by applying a hash function such as SHA-256.</li><li>Finally, this hash is formatted into a human-readable fingerprint.</li></ol><p>After reviewing the fundamental concepts of certificates and their validation methods, let’s move on to the core topic of this chapter: <strong>TLS and mTLS handshakes</strong>. It’s important to clarify that the goal here isn’t to provide an exhaustive discussion of TLS, as there are already many resources available that dive deep into it. Instead, we’ll focus on the key aspects most relevant to our discussion.</p><p>The first step in establishing a secure, encrypted communication channel between two entities using the TLS protocol is known as the TLS handshake. The diagram below provides a comparative illustration of TLS and mTLS handshakes. To simplify things, let’s break it down into two roles: the client and the server. The client is the entity that initiates communication to obtain a service, such as a web browser or mobile app. The server, on the other hand, listens for incoming communication on a network port to provide that service. For example, a web server might listen on port 80 to serve web pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0wZqV7rzmS8JqSI_" /><figcaption>TLS and mTLS handshakes</figcaption></figure><p>In step 3 of the handshake process, the server sends its certificate to the client using the <strong>Certificate</strong> message as defined in the TLS protocol. This allows the client to validate the server’s certificate and ensure the server’s identity. The validation process can be carried out using one of the certificate validation methods we discussed earlier. For example, if the certificate is a PKI certificate, the client can validate the certificate chain. If it’s a self-signed certificate, the client may choose to trust the certificate by comparing the provided details before initiating the handshake. This step is common to both TLS and mTLS protocols.</p><p>In contrast, mTLS introduces an additional layer of security. In step 5, the server requests the client to provide its certificate by sending the <strong>CertificateRequest</strong> message. This occurs after the client has verified the server’s certificate in step 3. The client responds by sending its certificate to the server using the <strong>Certificate</strong> message. Similar to client-side certificate validation, the server must validate the client certificate using one of the methods discussed earlier, confirming the client’s identity before proceeding. After step 7, the server has successfully authenticated the client, and the client’s identity is now known to the server. The diagram below illustrates these steps in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L1__Y5tD8LeDoxgA" /><figcaption>mTLS handshake</figcaption></figure><p>In summary, in <strong>TLS</strong>, only the client authenticates the server during the handshake, while in <strong>mTLS</strong>, both the client and server authenticate each other using certificates.</p><p>As illustrated in the diagram above, it’s crucial to highlight another important message that the client sends to the server during <strong>step 9</strong>: the <strong>CertificateVerify</strong> message. The primary purpose of the <strong>CertificateVerify</strong> message is to demonstrate to the server that the client holds the private key corresponding to the presented public key, thereby proving possession of the private key. This step is essential for understanding the upcoming Chapter-X of this post.</p><p>The steps involved in generating the content of the <strong>CertificateVerify</strong> message are as follows:</p><ol><li><strong>Collect the handshake messages</strong> exchanged between the client and server up to this point.</li><li><strong>Apply a secure hash function</strong> like SHA-256 to the collected message data to generate a hash value.</li><li><strong>Sign the hash value</strong> using the client’s private key to create the signature that will be included in the <strong>CertificateVerify</strong> message.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qvIxXtwt16c3g8HN" /><figcaption>CertificateVerify message</figcaption></figure><p>When the <strong>server</strong> receives the <strong>CertificateVerify</strong> message, it checks if the client’s signature is valid. To do so, the server uses the client’s <strong>public key</strong>, which it obtains from the client’s certificate. The server then independently calculates a <strong>hash value</strong> based on the messages exchanged earlier during the handshake. It compares this calculated hash value with the one sent by the client. If they match, the server confirms that the client used the correct <strong>private key</strong> to create the signature. This process ensures the client is authentic and possesses the private key associated with the presented certificate.</p><p>With a clear understanding of <strong>certificates</strong>, <strong>certificate validation</strong>, and the key steps in the <strong>mTLS handshake</strong>, we can now conclude this chapter and proceed to <strong>Chapter 2</strong>.</p><h3>Chapter 2 — Client Authentication</h3><p>In the realm of <strong>OAuth2</strong>, a <strong>client</strong> refers to an entity that obtains an <strong>access token</strong> from an <strong>authorization server</strong> on behalf of an end user. <strong>OpenID Connect (OIDC)</strong>, an authentication protocol built on top of OAuth2, redesignate the OAuth2 client as the <strong>Relying Party (RP)</strong>. OAuth2 clients are categorized into two main types: <strong>confidential clients</strong> and <strong>public clients</strong>.</p><ul><li><strong>Confidential clients</strong>, such as server-side web applications, can securely hold client-associated security credentials.</li><li><strong>Public clients</strong>, like browser-based applications, cannot securely store credentials.</li></ul><p><a href="https://sagarag.medium.com/understanding-oauth2-landscape-1b80cc9ed303">Understanding OAuth2 Landscape</a></p><p>As per the OAuth2 specification, <strong>authorization servers (AS)</strong> are required to authenticate <strong>confidential clients</strong> before issuing tokens. The OAuth2 specification outlines client authentication as an abstract requirement, giving implementers the flexibility to choose a client authentication method that suits their needs. However, the specification also defines one specific client authentication method based on a shared secret known as client_secret. During <strong>client registration</strong>, both the client and authorization server agree on the client_secret value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BTcQz38faiAgIDuc" /></figure><p>When making <strong>token generation</strong> calls, the <strong>client</strong> authenticates with the <strong>authorization server</strong> by providing the client_secret. A commonly adopted practice is to send the client_id and client_secret through the <strong>HTTP Authorization header</strong>.</p><p>Despite its widespread use, <strong>shared secret-based client authentication</strong> may not be suitable for all use cases. To address diverse industry needs, the <strong>OAuth2 working group</strong> has introduced various client authentication strategies over time, allowing for more flexibility in different contexts.</p><h3>Chapter 3 — mTLS for OAuth2 Client Authentication</h3><p>In <strong>Chapter 1</strong>, we highlighted a key point about <strong>mTLS</strong>: the <strong>client</strong> entity needs to authenticate with the <strong>server</strong> entity during the handshake by presenting its certificate.</p><p>According to <strong>OAuth2</strong> security requirements, a <strong>server-side application</strong> acting as an OAuth2 client should exclusively communicate with the <strong>Authorization Server</strong> using <strong>HTTP over TLS</strong>, avoiding plain HTTP. In this scenario, the OAuth2 client acts as the <strong>TLS client</strong>, while the authorization server assumes the role of the <strong>TLS server</strong>. Furthermore, as discussed in Chapter 1, when <strong>mTLS</strong> is employed, the <strong>OAuth2 client</strong> undergoes authentication with the <strong>Authorization Server</strong> during the mTLS handshake.</p><p>Now, considering this: when an <strong>OAuth2 client</strong> initiates a request to an <strong>Authorization Server</strong> using an mTLS connection, the client has already been authenticated during the mTLS handshake through a <strong>client certificate</strong> at the <strong>TLS level</strong>.</p><p>Can we then leverage this authentication, which has already occurred at the TLS level, to fulfill the <strong>OAuth2 client authentication</strong> requirement outlined in Chapter 2? The straightforward answer is <strong>yes</strong> — and that’s exactly the objective addressed in the first part of the <strong>OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens</strong> (RFC 8705) specification.</p><p>In fact, <strong>mTLS-based OAuth2 client authentication</strong> is more secure than the <strong>shared secret-based</strong> authentication method.</p><p>We previously explored two types of certificates — <strong>PKI certificates</strong> and <strong>self-signed certificates</strong>. Now, let’s see how both types can be employed for <strong>OAuth2 client authentication</strong>, as outlined in the <a href="https://datatracker.ietf.org/doc/html/rfc8705"><strong>OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens</strong></a> specification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a7reHjgrFLL1KIry" /><figcaption>mTLS based client Authentication</figcaption></figure><p>When a <strong>PKI certificate</strong> is used in the <strong>mTLS handshake</strong>, the <strong>Authorization Server</strong> already possesses the verified certificate through <strong>certificate chain verification</strong>. This allows the Authorization Server to simply compare the <strong>subject</strong> of the underlying certificate with the subject information provided during the <strong>client registration</strong> of the specific <strong>OAuth2 client</strong>.</p><p>Similar to how an OAuth2 client provides registration data like the <strong>client name</strong> and <strong>redirect URL</strong>, it can register the <strong>Distinguished Name (DN)</strong> or <strong>Server Alternative Name (SAN)</strong> during the <strong>client registration</strong>. These pieces of information can then be utilized to authenticate the client by comparing the registered <strong>DN/SAN</strong> with the <strong>DN/SAN</strong> values present in the subject of the certificate. However, for each OAuth2 client, a single <strong>DN</strong> or <strong>SAN</strong> should be used.</p><p>One of the main advantages of <strong>PKI certificates</strong> is that the client can <strong>rotate certificates</strong> as long as the new certificates contain the same subject value. Authorization servers may optionally check the <strong>revocation status</strong> of the certificate as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0dRPo6vc4eABNDq6" /><figcaption>mTLS based client Authentication</figcaption></figure><p>Here is an sample token request:</p><pre>curl --location --request POST &#39;https://localhost:9443/oauth2/token&#39; \<br>  --header &#39;Content-Type: application/x-www-form-urlencoded&#39; \<br>  --data-urlencode &#39;code=be728f21-8b3b-3c90-98e3-66188a647407&#39; \<br>  --data-urlencode &#39;grant_type=authorization_code&#39; \<br>  --data-urlencode &#39;client_id=QGR5np4F_OYGSH8L5F3klJJPrUEa&#39; \<br>  --data-urlencode &#39;redirect_uri=https://myapp/login&#39;</pre><p>An <strong>Authorization Server</strong> can advertise its support for <strong>OAuth2 mTLS</strong> by adding the <strong>tls_client_auth</strong> entry to the <strong>server metadata</strong> definition.</p><p><a href="https://sagarag.medium.com/how-do-you-discover-the-oauth2-server-configuration-d42d30ad5b9d">How do you discover the OAuth2 server configuration?</a></p><p>For the purpose of <strong>client registration</strong> using the <strong>DCR endpoint</strong>, the <a href="https://datatracker.ietf.org/doc/html/rfc8705"><strong>OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens</strong></a> specification defines the following additional parameters to register the <strong>DN</strong> and <strong>SAN</strong> associated with an OAuth2 client:</p><ul><li><strong>tls_client_auth_subject_dn</strong>: Specifies the expected <strong>Subject DN</strong> of the certificate that the OAuth2 client will present during mTLS authentication and use this when you want to match the full Distinguished Name (DN) of the client certificate.</li><li><strong>tls_client_auth_san_dns</strong>: Specifies the expected <strong>Subject DN</strong> of the certificate that the OAuth2 client will present during mTLS authentication and useful for matching domain names tied to the client identity.</li><li><strong>tls_client_auth_san_uri</strong>: Specifies the expected <strong>Subject DN</strong> of the certificate that the OAuth2 client will present during mTLS authentication and often used when the client is identified by a URI, such as a service URL.</li><li><strong>tls_client_auth_san_ip</strong>: Specifies the expected <strong>Subject DN</strong> of the certificate that the OAuth2 client will present during mTLS authentication and common in internal network setups where services are identified by IP.</li><li><strong>tls_client_auth_san_email</strong>: Specifies the expected <strong>Subject DN</strong> of the certificate that the OAuth2 client will present during mTLS authentication and helpful when the client identity is tied to an email address.</li></ul><p><a href="https://sagarag.medium.com/how-to-register-and-manage-oauth2-clients-896e553b7cf1">How to register and manage OAuth2 clients?</a></p><p>When <strong>self-signed certificates</strong> are used, the <strong>Authorization Server</strong> can allow the <strong>OAuth2 client</strong> to easily upload the client certificate in <strong>PEM</strong> or <strong>JWKS format</strong>, or provide a <strong>JWKS endpoint URL</strong>. When the client initiates a token request using an <strong>mTLS</strong> connection, the certificate linked to the mTLS connection can be matched with the certificate details registered during the <strong>OAuth2 client registration</strong>. If the complete certificate is accessible as client registration metadata, the Authorization Server can directly compare it with the mTLS client certificate. If not, the Authorization Server can retrieve the registered certificate using the <strong>JWKS endpoint URL</strong> provided during client registration.</p><p>If the client certificate is directly uploaded to the <strong>Authorization Server</strong>, any changes in the certificate, such as rotation, would necessitate modifying the certificate information in the <strong>Authorization Server</strong>. This poses a potential drawback to this approach. However, if the client certificate is specified as a reference, such as a <strong>JWKS endpoint URL</strong>, then certificate rotation can be carried out without changing the client registration data in the <strong>Authorization Server</strong>.</p><p>An <strong>Authorization Server</strong> can advertise its support for <strong>OAuth2 mTLS</strong> by adding the <strong>self_signed_tls_client_auth</strong> entry to the <strong>server metadata</strong> definition.</p><p>The <a href="https://datatracker.ietf.org/doc/html/rfc8705"><strong>OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens</strong></a> specification does not introduce new client registration parameters. Instead, it utilizes the <strong>“jwks”</strong> and <strong>“jwks_uri”</strong> parameters, as defined in the <strong>DCR specification</strong>. These parameters enable an <strong>OAuth2 client</strong> to furnish certificate details during the <strong>client registration process</strong> through the <strong>DCR endpoint</strong>.</p><ul><li><strong>jwks</strong> — JSON Web Key Set of the client.</li><li><strong>Jwks_uri</strong> — The URL referring to the JSON Web Key Set of the client.</li></ul><p>The OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens specification also doesn’t provide recommendations on the <strong>deployment architecture</strong> for <strong>OAuth2 clients</strong> and <strong>Authorization Servers</strong>. However, addressing this practical aspect is crucial. We can primarily identify <strong>two deployment scenarios</strong>:</p><ol><li>Direct mTLS connection between the client and the Authorization Server</li><li>The mTLS connection is terminated at a reverse proxy</li></ol><p>Establishing an <strong>mTLS connection</strong> between the <strong>client</strong> and the <strong>Authorization Server</strong> is a straightforward approach, especially when using <strong>Identity as a Service (IDaaS)</strong> as the Authorization Server. This involves creating a direct mTLS connection between the client and the Authorization Server, relying on pre-configured TLS settings on both ends.</p><p>In the latter case, a <strong>reverse proxy</strong>, like <strong>Nginx</strong>, handles the mTLS handshake, managing the mTLS connection between the client and the reverse proxy, which acts as an intermediary or front-end for the Authorization Server. The mTLS connection is terminated at the reverse proxy, allowing clients with successful mTLS connections to access the Authorization Server. This setup is commonly used in <strong>on-premise deployments</strong> of Authorization Servers because mTLS configuration can be handled at the reverse proxy level, simplifying the deployment of the Authorization Server. Additionally, a single reverse proxy can distribute traffic among multiple instances of Authorization Servers. From a <strong>network security</strong> perspective, the reverse proxy is typically placed in a <strong>DMZ</strong> zone, while the Authorization Server is deployed in a restricted zone. Despite this separation, both the reverse proxy and the Authorization Server belong to the same trust domain, and logically, the reverse proxy can be considered an <strong>internal component</strong> of the Authorization Server deployment.</p><p>However, there is a challenge in this scenario: the <strong>Authorization Server</strong> doesn’t conduct the mTLS handshake, so the client certificate isn’t directly accessible to it. While the official specification doesn’t provide a specific solution for this, <strong>IAM vendors</strong> have implemented a simple approach that is becoming common across the industry.</p><p>Though the Authorization Server isn’t directly involved in the mTLS handshake, the reverse proxy acts on its behalf. To resolve the issue, the reverse proxy can forward the client certificate to the Authorization Server as an <strong>HTTP header</strong> after terminating the mTLS connection. The good news is that most modern reverse proxies can append the client certificate as an HTTP header for use in upstream applications. The specific name of the HTTP header is not standardized, so vendors use their own conventions. For example, <strong>WSO2 Identity Server</strong> defaults to the <strong>x-wso2-mtls-cert</strong> HTTP header, which can be customized during server configuration. The following diagram illustrates the complete solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vTgnNgnQfQGljgKp" /><figcaption>OAuth 2.0 m-TLS client authentication in WSO2 Identiy Server</figcaption></figure><p>In this post, we explored how <strong>authentication works in the mTLS protocol</strong>, and how that same mechanism can be applied to <strong>OAuth2 client authentication</strong> to enable a more <strong>secure</strong> and <strong>interoperable</strong> approach.</p><p>In <strong>Part 2</strong>, we’ll dive into how certificates can be used to <strong>bind a token — like an access token — to the intended recipient only</strong>, ensuring it can’t be misused if intercepted or leaked. This is a powerful technique that enhances trust between the authorization server and the client.</p><p><strong>Stay tuned — it’s coming soon!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5958f6f9b098" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure OAuth2: A Simple Story of Two Keys — PKCE]]></title>
            <link>https://sagarag.medium.com/secure-oauth2-a-simple-story-of-two-keys-pkce-2bdd96232105?source=rss-fe43db0e480e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bdd96232105</guid>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[application-security]]></category>
            <dc:creator><![CDATA[Sagara Gunathunga]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 23:21:33 GMT</pubDate>
            <atom:updated>2025-04-23T23:21:33.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>Secure OAuth2: A Simple Story of Two Keys — PKCE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSRoRIyNBoqjtigXkDhFyw.png" /><figcaption>(Source — <a href="https://www.amazon.co.uk/Genie-Hand-Mechanic-Security-Cabinet/dp/B074H5SFPJ?th=1">https://www.amazon.co.uk/Genie-Hand-Mechanic-Security-Cabinet/dp/B074H5SFPJ?th=1</a>)</figcaption></figure><p>This is the final post in my <em>Secure OAuth2</em> blog series. I <a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">began</a> this series by examining the security gaps in the OAuth2 authorization code grant type, with the goal of introducing and advocating for a set of complementary specifications that have been developed over time to strengthen the flow — namely JAR, PAR, and JARM. Over the last four posts, we looked into each of these specs in detail, along with hands-on examples to help you apply them in practice using <a href="https://wso2.com/asgardeo/">Asgardeo</a> — cloud identity solution.</p><p><a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">Secure OAuth2 : Is Authorization Code Grant Type Secure Enough?</a></p><p>In this final post, I want to talk about <a href="https://datatracker.ietf.org/doc/html/rfc7636"><strong>Proof Key for Code Exchange (PKCE)</strong></a>.</p><p>You’re probably already familiar with how the OAuth2 authorization code flow works: it involves two calls to the authorization server. First, the client application sends an authorization request via the user agent (typically a browser or app), and in return, it receives an authorization code. Then, in the second call, the client exchanges that code for tokens — such as an access token or ID token. The important point here is that <strong>without a valid authorization code, the client cannot obtain tokens</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*m3aguRQJ3Txo5P42jHqdMw.png" /><figcaption><strong>OAuth2 authorization code grant type</strong></figcaption></figure><p><em>Now, here’s the key question:<br></em><strong>What if a malicious actor somehow gets hold of that authorization code — could they use it to get a token?</strong></p><p>The short answer is: <em>it depends</em>. And we can’t completely rule out the possibility.</p><p>Let’s break it down.</p><p>If the application is a traditional server-side app — what we call a <strong>confidential client</strong> — it must authenticate itself when making the token request. Without the proper credentials, it won’t get a token. So even if someone manages to steal an authorization code, they wouldn’t be able to do much without the app’s credentials, making this a relatively safe scenario.</p><p>But that’s not the case for <strong>public clients</strong> — like mobile apps or single-page applications (SPAs) that run in the browser. These apps can’t securely store credentials, and therefore aren’t expected to authenticate themselves when calling the token endpoint. If an authorization code from such an app is intercepted, the attacker <em>could</em> exchange it for tokens using information like the client_id and redirect_uri, which are often publicly visible in the original authorization request.</p><p>For instance, if you build mobile apps on Android or iOS, you’ll often register a custom URI scheme — such as myapp://callback— so your application can receive the authorization code after a user signs in. It’s a convenient feature, but it has a critical weakness: <strong>multiple apps can register the same URI</strong>. An attacker could publish a malicious app that also claims myapp://callback.</p><p>Here’s how the attack plays out:</p><ol><li>Your real app initiates the OAuth flow, sending the user to the authorization server.</li><li>After login, the server redirects to myapp://callback?code=….</li><li>Because two apps both handle that URI, the operating system prompts the user (or defaults) to choose which app should open the link.</li><li>If the malicious app is selected, it receives the authorization code instead of your app.</li><li>The attacker’s app then calls the token endpoint — using its own credentials if required — to exchange the stolen code for valid tokens.</li></ol><p>By the time your legitimate app sees the callback, the attacker already holds the tokens and can impersonate the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgDBnRs4arbozMhHSGKF7w.png" /><figcaption>Hijacking authorization code from a mobile device</figcaption></figure><p>You can mitigate this with features like <a href="https://developer.android.com/training/app-links">Android App Links</a> or <a href="https://developer.apple.com/documentation/xcode/allowing-apps-and-websites-to-link-to-your-content/">iOS Universal Links</a> but the best approach would be to harden the OAuth2 flow itself to be resistant to such issues.</p><h4><strong>So what can we do?</strong></h4><p>One intuitive idea would be to somehow <strong>ensure that the same application that made the original authorization request is also the one making the token reques</strong>t — using some kind of a secret. But again, public clients can’t securely store secrets, which is the core issue here.</p><p><strong>That’s exactly the problem that </strong><a href="https://datatracker.ietf.org/doc/html/rfc7636"><strong>PKCE</strong></a><strong> (pronounced “pixy”) is designed to solve based on cryptographic hashing.</strong></p><p>At the heart of PKCE is the use of a hash function. Hash functions take an input and produce a fixed-length string of characters — called a hash — that appears random and is unique to that input. A key property of hash functions is that even a small change in the input produces a completely different hash, and most importantly, they are one-way functions — meaning you can’t reverse-engineer the original input from the hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*3RLOJ5jZ63V6UOfoD9MzKg.png" /><figcaption>How hash functions work</figcaption></figure><p>PKCE works by requiring the client application to first generate a cryptographically random string typically between 43 to 128 characters that’s hard to guess. Then this random string is encoded using base64url schema to derive a string known as the <strong>code verifier</strong>. The client then applies a secure hash algorithm like SHA-256 to the code verifier and encodes the result using Base64 URL encoding. This final value is called the <strong>code challenge</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*t0lUsA5Avg-oz5Wpc54rpg.png" /><figcaption>Generation of code verifier and code challenge</figcaption></figure><p>At this point, the client holds two values: the <strong>code verifier </strong>and the <strong>code challenge. </strong>The authorization request begins with the client sending the code challenge to the authorization server. For this, the PKCE specification introduces an authorization request parameter called code_challenge. A simplified example of such a request is shown below.</p><p>Note that to keep things simple, I’ve used the standard authorization request here. But it’s entirely possible — and recommended in high-security environments —<strong> to include this parameter inside a signed Request Object (as per the JAR specification) or within a PAR request</strong>, both of which we’ve already discussed in previous posts.</p><p>Once the authorization server receives the request, it processes it and stores the code_challenge value. If everything is valid and the user successfully authenticates, the server issues an authorization code to the client application. In the following diagram, I’ve given a sample authorization request with the code_challenge parameter. In addition to that, you can also see the optional code_challenge_method parameter in the request. This parameter is used to specify the code verifier transformation method, which is usually set to S256 implying SHA-256 hash algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*IANQrjoAf5EBIaDRpLuzOg.png" /><figcaption>Authorization request with PKCE parameters</figcaption></figure><p>One important point to highlight here is that the PKCE spec defines another transformation method called &quot;plain&quot;. In that case, code_challenge = code_verifier. You shouldn&#39;t use the &quot;plain&quot; transformation, as it doesn&#39;t use the hash algorithm discussed above and doesn&#39;t provide adequate security strengthening to the flow.</p><p>In the next phase — during the token request — the client sends the authorization code <em>along with</em> the previously generated code verifier. For this, the PKCE specification introduces another parameter, code_verifier, in the token request. A sample token request showing how to include this parameter is provided below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*FuApiLk5TCOSnwWDXg-I1A.png" /><figcaption>Token request with PKCE parameters</figcaption></figure><p>Once PKCE is enabled, the complete authorization code grant flow looks like the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*0WFkEnVpdzpQhC2ELO_2dg.png" /><figcaption>Sending the code verifier and code challenge</figcaption></figure><p>Here’s where the interesting validation step happens. The authorization server now hashes the code_verifier using the same algorithm and compares it against the stored code_challenge from the initial authorization request. If the values match, it confirms that the same client made both the authorization and token requests. Even if an attacker intercepted the authorization code, they wouldn’t be able to use it—because they wouldn’t have access to the original code verifier, which was never shared at that point.</p><h4>PKCE Metadata Parameters and DCR</h4><p>The next question we should find an answer to is how does a client application discover whether a particular authorization server supports the PKCE extension — and if so, which method should be used. The OAuth 2.0 Authorization Server Metadata specification defines a metadata parameter called code_challenge_methods_supported to imply PKCE support, and this parameter can be set to either S256 or plain.</p><p><a href="https://sagarag.medium.com/how-do-you-discover-the-oauth2-server-configuration-d42d30ad5b9d">How do you discover the OAuth2 server configuration?</a></p><p>Once the authorization server’s support for PKCE is discovered by the client application, it can use the enforce_pkce and code_challenge_method DCR parameters during the client registration to inform the authorization server that the client expects to enforce PKCE and which transformation method it supports.</p><p><a href="https://sagarag.medium.com/how-to-register-and-manage-oauth2-clients-896e553b7cf1">How to register and manage OAuth2 clients?</a></p><p>Compared to the other specifications I’ve discussed in this series, PKCE stands out as the most widely adopted. The good news is that support for PKCE is already built into most modern languages, frameworks, and SDKs. In many cases, it’s enabled by default or can be turned on with just a simple configuration. For instance, the <a href="https://github.com/asgardeo/asgardeo-auth-spa-sdk">Asgardeo React SDK</a> has PKCE enabled by default, making it easier for developers to follow best practices without much extra effort. What’s also worth noting is that the OAuth 2.1 draft specification goes even further — it recommends using PKCE for <em>all</em> types of applications, not just public clients. This shows how important PKCE has become in securing the authorization code flow.</p><h3>PKCE in Action</h3><p>For this demo, I’ll be using <a href="https://wso2.com/asgardeo/"><strong>Asgardeo</strong></a> — a cloud identity service by WSO2 which comes with a generous free tier, making it a great option to try out your identity use cases. <a href="https://wso2.com/asgardeo/"><strong>Asgardeo</strong></a> fully supports the <a href="https://datatracker.ietf.org/doc/html/rfc7636">PKCE</a> extension and enable it by default in <a href="https://wso2.com/identity-and-access-management/developer/applications/">Asgardeo SDKs</a> so you don’t need to put any extra step to use PKCE with your applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*poeiTeO2RTB7CDjg.png" /></figure><p><strong>Step 1 — Configure Asgardeo</strong></p><p>If you don’t already have an Asgardeo account, you can sign up <a href="https://wso2.com/asgardeo/">here</a>. Once you’re logged in:</p><ul><li>Create a new <strong>Traditional Web Application</strong> from the left-side menu and Keep <strong>OpenID Connect</strong> selected as the protocol (this is the default). For the <strong>Authorized redirect URLs</strong>, enter <a href="https://myapp.io/login">https://myapp.io/login</a> as the value. Then save the application settings.</li><li>Next follow <a href="https://wso2.com/asgardeo/docs/guides/users/manage-users/#onboard-single-user">this guide</a> to create a test user, which you’ll use later in this flow.</li></ul><p><strong>Step 2 — Set Up Postman</strong></p><p>Next, you’ll need to configure Postman. First, Download <a href="https://www.postman.com/warped-eclipse-61593/workspace/public/collection/25632817-3c15b3bb-1892-41d1-b273-379471c24cb9?action=share&amp;creator=25632817">this Postman collection</a> for this demo. Open the collection and update the collection variables with the following values, which you can copy from your Asgardeo application:</p><ul><li><a href="https://myapp.io/login">authorize_ep</a> — Token Endpoint URL from the <strong>Info</strong> tab.</li><li>token_ep — Authorization Endpoint URL from the <strong>Info</strong> tab.</li><li>client_id — Client ID <strong>protocol</strong> tab.</li><li>client_secret — Client Secret <strong>protocol</strong> tab.</li></ul><p><strong>Step 3 — Execute the Flow</strong></p><ol><li>First, execute the “Generate-PKCE” request in the above Postman collection, this call would’t go anywhere, it just uses to generate c<strong>ode verifier </strong>and<strong> code challenge</strong> to be used in the next step.</li><li>Since Postman can’t simulate browser-based redirects, we’ll take a small manual step here. Open the <strong>Code Snippet</strong> tab for each request <em>( e.g — pkce-authz-code-grant-Browser</em> <em>) </em>from the right-hand menu in Postman and select <strong>cURL</strong> from the dropdown. Then copy the location value from the cURL snippet. Finally paste that URL into your browser’s address bar and hit Enter.</li><li>You should now be redirected to Asgardeo’s login screen. Enter the credentials of the test user you created earlier. If authentication is successful, you’ll be redirected to the callback URL with JWT authorization response which you can decode from your prefred JWT decoder tool.</li><li>Go back to Postman and open the <em>pkce-authz-code-token</em> request. Paste the copied code into the code parameter in the request body and send the request. If everything is set up correctly, you should receive a valid token from Asgardeo.</li></ol><p><strong><em>Note</em></strong> — as an exercise create a public client application in Asgardeo and try out the PKCE , you can refer <a href="https://wso2.com/asgardeo/docs/guides/authentication/oidc/implement-auth-code-with-pkce/">Asgardeo docs</a> as well.</p><p>With that, we’re reaching the end of this blog series where we discussed the security implications of the OAuth2 authorization code grant type and how complementary specifications developed over time can be used to mitigate these issues. Stay tuned for the next post with a new topic!</p><h3>Other posts in the secure OAuth2 series</h3><p>Read the other posts in<strong> Secure OAuth2</strong> series.</p><ul><li><a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">Secure OAuth2 : Is Authorization Code Grant Type Secure Enough?</a></li><li><a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517">Secure OAuth2 (Part -2): Put it in a JAR (JWT-Secured Authorization Request)</a></li><li><a href="https://sagarag.medium.com/secure-oauth2-part-3-push-authorization-request-par-to-rescue-529820f060d9">Secure OAuth2 (Part -3) : Push Authorization Request (PAR) to Rescue</a></li><li><a href="https://sagarag.medium.com/secure-oauth2-part-4-securing-response-using-jwt-secured-authorization-response-mode-jarm-11fceb9e4f6a">Secure OAuth2 (Part -4) : Securing Response Using JWT Secured Authorization Response Mode (JARM)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bdd96232105" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure OAuth2 (Part -4) : Securing Response Using JWT Secured Authorization Response Mode (JARM)]]></title>
            <link>https://sagarag.medium.com/secure-oauth2-part-4-securing-response-using-jwt-secured-authorization-response-mode-jarm-11fceb9e4f6a?source=rss-fe43db0e480e------2</link>
            <guid isPermaLink="false">https://medium.com/p/11fceb9e4f6a</guid>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[security-token]]></category>
            <category><![CDATA[app-security]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Sagara Gunathunga]]></dc:creator>
            <pubDate>Sat, 19 Apr 2025 21:25:01 GMT</pubDate>
            <atom:updated>2025-04-19T21:25:01.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Secure OAuth2 (Part -4) : Securing Response Using JWT Secured Authorization Response Mode (JARM)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nl86KOUD61LkkNk88Rh2CA.png" /><figcaption>(Source — <a href="https://www.flat-living.co.uk/overcoming-the-challenges-of-rising-parcel-delivery-volumes-to-apartment-blocks/">https://www.flat-living.co.uk/overcoming-the-challenges-of-rising-parcel-delivery-volumes-to-apartment-blocks/</a>)</figcaption></figure><p>So far in this blog series, we’ve explored whether the OAuth2 authorization code grant type has any security imperfections. We’ve already covered how to strengthen the <strong>authorization request</strong> using <a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517"><strong>JWT-Secured Authorization Request (JAR)</strong></a> and <a href="https://sagarag.medium.com/secure-oauth2-part-3-push-authorization-request-par-to-rescue-529820f060d9"><strong>Pushed Authorization Request (PAR)</strong></a> specifications to address several key issues. In this post, I’d like to shift our focus to the <strong>authorization response</strong> — and specifically, how we can enhance its security using the <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a>.</p><p><a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">Secure OAuth2 : Is Authorization Code Grant Type Secure Enough?</a></p><p>But before we dive into the details of <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a>, let’s quickly recap the potential security concerns related to the <strong>authorization response</strong> in the standard authorization code flow. If you haven’t read the <a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">first post</a> in this series, I’d highly recommend checking it out before diving into this one.</p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#56ea">P5 </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">— </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#56ea">Server integrity protection failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#8c27">P6 — Client confidentiality failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#139b">P7 — Mixed-up attack</a></p><p>Now, let’s begin our discussion by looking at the following diagram. It shows how the code parameter—which represents the authorization grant—is returned to the client application. This is typically done by appending it as a parameter to the registered redirect URL, and it&#39;s passed through the user agent, such as a browser. The key issue here is that there&#39;s no built-in mechanism for the client application <strong>to verify whether the authorization response was altered or tampered with during transit</strong>, or <strong>even to confirm that it genuinely originated from the legitimate authorization server</strong>. From the client&#39;s perspective, this lack of validation represents an integrity protection failure. Moreover, there’s no way to apply cryptographic protections—like <em>signing or encryption</em>—to the authorization response in this standard flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*wqdz0gUNSmMfwAFhdsiKNQ.png" /><figcaption>How authorization response is shown in the browser</figcaption></figure><p>If you recall the second post in this series, we explored how the <a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517"><strong>JWT-Secured Authorization Request</strong></a><strong> (JAR) </strong>specification addresses similar issues on the request side. JAR introduces the concept of a Request Object, which wraps the request parameters inside a signed and optionally encrypted JWT to ensure integrity, confidentiality, and source authentication.</p><p><a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517">Secure OAuth2 (Part -2): Put it in a JAR (JWT-Secured Authorization Request)</a></p><p>Applying the same principle to the authorization response makes a lot of sense — and that’s exactly what the <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT-Secured Authorization Response Mode (JARM)</strong></a> specification does. <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a><strong> </strong>was developed by OpenID Foundation’s FAPI working group and became a stable specification in 2021. <strong>In a nutshell, just as the <em>JAR</em> secures the authorization</strong> <strong>request, <em>JARM</em> secures the authorization</strong> <strong>response by encapsulating it in a signed (and optionally encrypted) JWT.</strong></p><p>One important point to highlight here is that when we talk about the <em>authorization server response</em> in the context of <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a>, it includes <strong>both success and error responses</strong>. That means even an error message is encoded inside a JWT, and generally, we refer to this as the <strong><em>JWT response document</em></strong>.</p><h4>Response Mode and Response Type</h4><p>To put <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> into action, the client application simply needs to indicate — in the authorization request — that it expects the authorization server to return the response in a JWT format. This is done using a request parameter called response_mode, which comes from another specification by the OpenID Foundation: <a href="https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes"><em>OAuth 2.0 Multiple Response Type Encoding Practices</em></a>.</p><p>The response_mode parameter tells the authorization server <strong><em>how</em></strong> to return the authorization response from the authorization endpoint. This makes it a perfect fit for what <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> is trying to achieve. While <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> still uses the same redirection mechanism to send the user back to the client application using the registered redirect URI, it introduces a new parameter called response, which carries the JWT response document as part of that redirect. To provide more flexibility, <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> defines <strong>four </strong><strong>response_mode values</strong> that let developers choose how the JWT should be delivered to the client application. These are:</p><ul><li><strong>query.jwt</strong> – The JWT response is added as a query parameter to the redirect URI.</li><li><strong>fragment.jwt</strong> – The JWT response is added as a URI fragment.</li><li><strong>form_post.jwt</strong> – The JWT response is embedded as an HTML form field and auto-submitted via an HTTP POST.</li><li><strong>jwt</strong> – A shorthand value that uses the default mechanism (query or fragment) based on the response_typeparamter discssed below.</li></ul><p>Now, what exactly goes inside the JWT response document depends on another authorization request parameter called response_type. This one should be familiar—it’s defined in the core <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-3.1.1">OAuth2 specification ( section 3.1.1)</a> and used to distinguish between different grant types supported by the authorization endpoint. Due to it’s extensibility, the above-mentioned <a href="https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#MultiValueResponseTypes">OAuth 2.0 Multiple Response Type Encoding Practices</a> specification from OpenID foundation extends the use of response_type by defining multiple and new response types to be used with the OpenID Connect protocol.For this blog series, though, we’re sticking with the <strong>authorization code grant type</strong>, where the response_type is set to code.</p><p>As you can see in the following sample request, other than adding query query.jwt as the value of response type there is no change to the authorization request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*y30lxB6KswFzfz6gyfU86g.png" /><figcaption>Sample authorization request with query.jwt response mode</figcaption></figure><p>Now, let’s look at the authorization server’s response for the above request. You can see that the JWT response is added as a query parameter using the response. Note that, given we stick with response_type=code as the scope of this post, passing response_mode=jwt also returns the same result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*mKX8XRysS2VhyhxNPUwuHw.png" /><figcaption>Sample authorization response for query.jwt response mode</figcaption></figure><p>If we use fragment.jwtas the value of the response_mode parameter, the authorisation request will looks likes the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*WfhY2hCJHOCUC783hELkqQ.png" /><figcaption>Sample authorization request with fragment.jwt response mode</figcaption></figure><p>In this case, the authorization response will be modified as shown in the following example. As you can see, the JWT response is appended as a fragment to the redirect URI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*bi_2CVXNIAhdtqvHjHvstA.png" /><figcaption>Sample authorization response for fragment.jwt response mode</figcaption></figure><p>Finally, if we use form_post.jwt as the value of the response_mode parameter, the authorization request would look like the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*s2GzXSN1w-UuLaygeYnhgA.png" /><figcaption>Sample authorization request with form_post.jwt response mode</figcaption></figure><p>Unlike the previous two cases, here the authorization server submits the JWT authorization response to the client application using an HTTP POST. As a result, the JWT response won’t be visible in the browser URL. Instead, the application receives it as part of a form submission, similar to the one shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*gkYuDSZKSkLNgkRtfyFXqA.png" /><figcaption>Sample authorization response for form_post.jwt response mode</figcaption></figure><p>One important point to mention here is that, in the examples above, I used the authorization request as in the standard authorization code grant type — mainly to keep things simple and easier to follow. However, the <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> specification can absolutely be used alongside the <a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517"><strong>JWT-Secured Authorization Request (JAR)</strong></a> and <a href="https://sagarag.medium.com/secure-oauth2-part-3-push-authorization-request-par-to-rescue-529820f060d9"><strong>Pushed Authorization Request (PAR)</strong></a> specifications, which significantly enhance the security of the authorization request phase. If you want to use <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> along with<a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517"><strong>JWT-Secured Authorization Request (JAR)</strong></a> and <a href="https://sagarag.medium.com/secure-oauth2-part-3-push-authorization-request-par-to-rescue-529820f060d9"><strong>Pushed Authorization Request (PAR)</strong></a>, you just need to include the response_mode and response_type parameters within the Request Object or the PAR request—nothing else changes.</p><p>No matter how the client application receives the JWT-encoded authorization response, once you decode it, you’ll see a JWT that looks something like the example below. As with any JWT, there are a few standard claims you’ll always find:</p><ul><li>iss: the issuer URL of the authorization server</li><li>aud: the client_id of the client application</li><li>exp: the expiration time of the JWT that is usually less than o10 minutes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*lg7ZKo5Q7rEmP2pZmNmcMQ.png" /><figcaption>Decoded JWT claim set from a JWT authorization response</figcaption></figure><p>As mentioned earlier, the exact claims included in the JWT will depend on the value of the response_type parameter. For example, when response_type=code, you&#39;ll find the code claim (which is the authorization code) along with the state value originally sent by the client.</p><p>If the authorization response indicates an error, the JWT will contain an error claim representing the error code. It may also include optional claims like error_description, error_uri, and state, as shown in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*Ei5_zDgwe27uzQpEnu1T9A.png" /><figcaption>Decoded JWT claim set from a JWT authorization response error message</figcaption></figure><p>If the JWT is encrypted, the client first needs to decrypt it. This is usually done using the default encryption key associated with the authorization server, or in some cases, a key identified by the kid (key ID) in the JWT header if it’s avilable. The key could be either a private key (with the corresponding public key registered in the client’s metadata) or a key derived from the client secret.</p><p>Once decrypted, the client should check the following:</p><ul><li>The iss (issuer) claim should match the expected authorization server. If it doesn&#39;t, the client should reject the response.</li><li>The aud (audience) claim should match the client_id the client used in the original request. If not, the response should be rejected.</li><li>The exp (expiration) claim tells the client if the JWT is still valid. If it’s expired, the response must be rejected.</li><li>Finally, the client must validate the signature of the JWT to make sure it hasn’t been tampered with. If the <strong>alg</strong> value is <strong>none in the JOSE header then the response should be rejected </strong>and<strong> </strong>If the <strong>signature check fails, the response should be rejected as well</strong>.</li></ul><p>Sinceses JWTs and requires successful signature validation, it naturally provides integrity protection, source authentication, audience restriction, and protection from mix-up attacks. And when the JWT is encrypted, it also ensures confidentiality.</p><h4>JARM in Action</h4><p>At this point, we’ve covered the key details you need to understand about the <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> specification and how it helps improve the security of the authorization response of the authorization code grant type. Before wrapping up this post, I want to give you a set of instructions to run a quick hands-on demo to see <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> in action using a cloud-based identity provider. It should only take about 5 minutes.</p><p>For this demo, I’ll be using <strong>Asgardeo</strong> — a cloud identity service by WSO2. It fully supports the <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> specification and comes with a generous free tier, making it a great option to try out your identity use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Q4M7ytIXMTiSy-7j_ztqg.png" /></figure><p><strong>Step 1 — Configure Asgardeo</strong></p><p>If you don’t already have an Asgardeo account, you can sign up <a href="https://wso2.com/asgardeo/">here</a>. Once you’re logged in:</p><ul><li>Create a new <strong>Traditional Web Application</strong> from the left-side menu and Keep <strong>OpenID Connect</strong> selected as the protocol (this is the default). For the <strong>Authorized redirect URLs</strong>, enter <a href="https://myapp.io/login">https://myapp.io/login</a> as the value. Then save the application settings.</li><li>Next follow <a href="https://wso2.com/asgardeo/docs/guides/users/manage-users/#onboard-single-user">this guide</a> to create a test user, which you’ll use later in this flow.</li></ul><p><strong>Step 2 — Set Up Postman</strong></p><p>Next, you’ll need to configure Postman. First, Download <a href="https://www.postman.com/warped-eclipse-61593/workspace/public/collection/25632817-3c15b3bb-1892-41d1-b273-379471c24cb9?action=share&amp;creator=25632817">this Postman collection</a> for this demo. Open the collection and update the collection variables with the following values, which you can copy from your Asgardeo application:</p><ul><li><a href="https://myapp.io/login">authorize_ep</a> — Token Endpoint URL from the <strong>Info</strong> tab.</li><li>token_ep — Authorization Endpoint URL from the <strong>Info</strong> tab.</li><li>client_id — Client ID <strong>protocol</strong> tab.</li><li>client_secret — Client Secret <strong>protocol</strong> tab.</li></ul><p><strong>Step 3 — Execute the Flow</strong></p><ol><li>Since Postman can’t simulate browser-based redirects, we’ll take a small manual step here. Open the <strong>Code Snippet</strong> tab for each request <em>( e.g — [Browser]jarm-query.jwt) </em>from the right-hand menu in Postman and select <strong>cURL</strong> from the dropdown. Then copy the location value from the cURL snippet. This URL includes the correct response_mode and response_type values. Finally paste that URL into your browser’s address bar and hit Enter.</li><li>You should now be redirected to Asgardeo’s login screen. Enter the credentials of the test user you created earlier. If authentication is successful, you’ll be redirected to the callback URL with JWT authorization response which you can decode from your prefred JWT decoder tool.</li><li>Go back to Postman and open the <strong>Token-Request</strong> request. Paste the copied code into the code parameter in the request body and send the request. If everything is set up correctly, you should receive a valid token from Asgardeo.</li></ol><p>This quick walkthrough shows how easy it is to implement <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> using a modern identity platform.</p><p>So far in this series, we’ve looked at how to secure the authorization request using <a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517"><strong>JWT-Secured Authorization Request (JAR)</strong></a> and <a href="https://sagarag.medium.com/secure-oauth2-part-3-push-authorization-request-par-to-rescue-529820f060d9"><strong>Pushed Authorization Request (PAR)</strong></a>, and in this post, we focused on how <a href="https://openid.net/specs/oauth-v2-jarm.html"><strong>JWT Secured Authorization Response Mode (JARM)</strong></a> strengthens the authorization response. With these improvements in place, we’ve successfully addressed all the security concerns we identified in the very first post of this series. As we are reaching the end of this blog series, stay tune for the last post of the series.</p><h3>Other posts in the secure OAuth2 series</h3><p>Read the other posts in<strong> Secure OAuth2</strong> series.</p><ul><li><a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">Secure OAuth2 : Is Authorization Code Grant Type Secure Enough?</a></li><li><a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517">Secure OAuth2 (Part -2): Put it in a JAR (JWT-Secured Authorization Request)</a></li><li><a href="https://sagarag.medium.com/secure-oauth2-part-3-push-authorization-request-par-to-rescue-529820f060d9">Secure OAuth2 (Part -3) : Push Authorization Request (PAR) to Rescue</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11fceb9e4f6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure OAuth2 (Part -3) : Push Authorization Request (PAR) to Rescue]]></title>
            <link>https://sagarag.medium.com/secure-oauth2-part-3-push-authorization-request-par-to-rescue-529820f060d9?source=rss-fe43db0e480e------2</link>
            <guid isPermaLink="false">https://medium.com/p/529820f060d9</guid>
            <category><![CDATA[app-security]]></category>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[asgardeo]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[oidc]]></category>
            <dc:creator><![CDATA[Sagara Gunathunga]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 03:30:18 GMT</pubDate>
            <atom:updated>2025-04-18T03:31:53.921Z</atom:updated>
            <content:encoded><![CDATA[<h3>Secure OAuth2 (Part -3) : Push Authorization Request (PAR) to Rescue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tB1lJ9ou5LLs7ftKobA5mg.png" /><figcaption>(Source — <a href="https://www.straitstimes.com/tech/new-security-feature-to-let-bank-customers-lock-up-savings-for-in-person-access-only">https://www.straitstimes.com/tech/new-security-feature-to-let-bank-customers-lock-up-savings-for-in-person-access-only</a> )</figcaption></figure><p>In the very <a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">first post</a> of this series, I explored whether the authorization code grant type truly provides the highest level of security — and what potential risks it might carry. This grant type is widely regarded as the recommended option when involving end users, both in <a href="https://datatracker.ietf.org/doc/rfc9700/">OAuth 2.0 best current practices</a> and the <a href="https://datatracker.ietf.org/doc/draft-ietf-oauth-v2-1/">OAuth 2.1</a> draft specification. If you haven’t already, I highly recommend reading that first post before diving into this one.</p><p><a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">Secure OAuth2 : Is Authorization Code Grant Type Secure Enough?</a></p><p>Just to recap, the potential security shortcomings in the authorization request of the authorization code flow includes:</p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#3bd7">P1 </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">— </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#3bd7">Integrity protection failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">P2 — Source Authentication Failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7301">P3 — Confidentiality failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7cb3">P4 — Lack of Request as a Reference semantic</a></p><p>The implications tied to the authorization response of the authorization code flow includes:</p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#56ea">P5 </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">— </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#56ea">Server integrity protection failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#8c27">P6 — Client confidentiality failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#139b">P7 — Mixed-up attack</a></p><p>In the most recent post, we looked at how <a href="https://datatracker.ietf.org/doc/html/rfc9101">JWT-Secured Authorization Request</a> (JAR) helps address some of those concerns by introducing the concept of a <em>Request Object</em> — essentially a JWT that can be signed (JWS) and encrypted (JWE) to offer integrity protection, source authentication, and confidentiality. We also touched on the request-by-reference semantics in the JAR spec, which remain open-ended and somewhat vague for implementation.</p><p><a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517">Secure OAuth2 (Part -2): Put it in a JAR (JWT-Secured Authorization Request)</a></p><p>In this post, I’ll continue our conversation by introducing another spec in the OAuth 2.0 ecosystem: <a href="https://datatracker.ietf.org/doc/html/rfc9126"><strong>Pushed Authorization Requests</strong></a><strong> (PAR)</strong>. We’ll look at how PAR and JAR complement each other to bring maximum security to the authorization request process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*ahcBOUv6NO5r4sEp" /><figcaption>OAuth2 Authorization Code grant type</figcaption></figure><h4>Making Authorization Code grant more secure</h4><p>If we go back to the following diagram — which captures the last point I discussed in my previous post on JWT-Secured Authorization Request (JAR) — you’ll see how a signed and optionally encrypted <strong><em>Request Object</em></strong> can be sent to the Authorization Server <strong>as a reference</strong>, rather than being passed directly in the authorization request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*5-gl6-wye63TSDQHCA3gHw.png" /><figcaption>Passing by reference flow in the JWT-Secured Authorization Request (JAR)</figcaption></figure><p>This approach makes use of the request_uri parameter, introduced in the JAR specification, to point to a URI where the Request Object is stored. It&#39;s a smart way to ensure <strong>confidentiality</strong> in the authorization request and is especially handy in resource-constrained environments, like mobile devices, where sending large requests via the user agent isn’t always practical.</p><p>However, despite these benefits, the JAR spec has a few open-end areas related to pass by reference approach. It doesn’t define a standard mechanism or location for storing the Request Object. It’s a bit <em>too</em> open — your options include a local client location, a remote location at the Authorization Server, or even a trusted third-party location. On top of that, there’s no clear guidance on how to store the Request Object, what security measures should be applied, or how the Authorization Server is supposed to fetch it securely. Another limitation is that the send-by-reference approach in JAR is tightly coupled with the use of the Request Object itself. That makes it a less-than-ideal fit for simpler use cases where a full JWT-based Request Object might be overkill.</p><p>This is exactly where <strong>Pushed Authorization Requests (PAR)</strong> come in. The PAR specification introduces a dedicated endpoint called <strong>Pushed Authorization Request Endpoint</strong> <strong>(PAR endpoint in short)</strong> at the Authorization Server. This endpoint offers a <em>generic, secure, and standardized</em> way to achieve request-by-reference semantics. In the <strong>standard Authorization Code flow</strong>, the client sends the authorization request by directing the user agent — typically a web browser — to make an HTTP GET request to the authorization server’s authorization endpoint. <strong>PAR</strong>, however, introduces a key shift: it <strong>splits the authorization request into two distinct steps</strong> — and this change plays a big role in strengthening the overall security of the flow.</p><p>Let’s now walk through that protocol flow step by step.</p><p>With <strong>Pushed Authorization Requests (PAR)</strong>, the flow begins when the client application sends a <strong>HTTP </strong><strong>POST request</strong>—called a <em>pushed authorization request</em>, or simply <strong>PAR request</strong>—to a newly introduced <strong>PAR endpoint</strong> on the authorization server. Just like the token request that happens later in the flow, this is a <strong>direct client-to-server call via TLS encrypted HTTP channel</strong>, with no involvement from the user agent (i.e., the browser).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*flNvidYOTd_Z_lWOSex8uA.png" /><figcaption>Sending a PAR request to the PAR endpoint of the Authorization Server</figcaption></figure><p>Later in this post, we’ll look at how you can include a <strong>Request Object</strong> (as defined by the JAR spec) in the PAR request. But the beauty of PAR is that you don’t have to — <strong>you can simply send the request parameters encoded within the body of HTTP POST message</strong>, making it much more flexible.</p><p>Here’s what a sample PAR request looks like…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*MTA-61Op5jdMPEFc9HC2xg.png" /><figcaption>A sample PAR request</figcaption></figure><p>Just like in the standard authorization request, a <strong>PAR request</strong> includes parameters like client_id, redirect_uri, response_type, and scope, but this time they’re <strong>encoded in the body</strong> of the HTTP POST request instead of encoding them as URL parameters in the GET call used in the authorization request of the standard authorization code grant flow. It’s important to note that the response_type should be set to &#39;code&#39;.</p><p>The <strong>PAR endpoint</strong> is designed to accept <strong>any parameter defined by the OAuth 2.0 core specification for the authorization request</strong>, as well as any supported extensions. For example, you can easily use PKCE (Proof Key for Code Exchange) with PAR. And since OIDC (OpenID Connect) is technically an OAuth 2.0 extension, PAR works with OIDC too.</p><p>One key difference compared to the traditional approach is that, in PAR <strong>confidential clients must authenticate with the authorization server</strong> right at this first step — <strong>before any user interaction happens</strong>. This is clearly a security enhancement. In the above example, the client authenticates using a client_secret, but you can use any supported method, including mutual TLS (mTLS), private_key_jwt, etc.</p><p>Now, once the <strong>authorization server receives the PAR request</strong>, it performs client authentication and request validation. If everything checks out, it generates a <strong>request_uri</strong> (yep—the same one we discussed in the <a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517">last post</a> on JAR) and sends it back to the client, along with an expires_in value indicating how long the request_uri is valid. If something goes wrong, the server responds with a JSON-formatted error. The diagram below illustrates a successful PAR response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*Yt1F0LT2phzpt0YZdk9Dxg.png" /><figcaption>A sample PAR response</figcaption></figure><p>Now with the <strong>request_uri</strong> in hand, the client application can build the <strong>authorization request URL</strong>, similar to how it&#39;s done in the traditional flow. The only real difference is that, other than client_id, <strong>none of the sensitive request parameters are included in the URL anymore</strong>—they’re all safely tucked away in the previously sent PAR request. Here’s an example of what that request might look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*HR9UnEByX9lK5TBY8Znp7Q.png" /><figcaption>A sample authorization request</figcaption></figure><p>Finally, once the user authenticates and authorizes the request, the authorization server sends back an authorization grant using the code parameter appended to the redirect URI—just like in the standard flow. It’s important to note that PAR does’t not introduce any change except the above discussed modifications to the authorization request flow. The complete authorization code grant flow with the introduction of PAR is depicted in the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*q9wqKHWEOq74afA1j_34bw.png" /><figcaption>Complete authorization code grant flow with PAR</figcaption></figure><p>PAR offers a major security and usability improvement for a couple of reasons:</p><ul><li>The <strong>request parameters no longer travel through the browser</strong>, which eliminates exposure to the end user and solves both <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7301">P3 — Confidentiality failure</a> and <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7cb3">P4 — Lack of Request as a Reference semantic</a> that we discussed in this series.</li><li>It also solves the issue of handling <strong>large request payloads</strong>, since those are now sent directly over a secure connection instead of being embedded in a URL making this is a preferable for resource constraint mobile devices and also in environments low internet connectivity.</li></ul><p>The following diagram provides comparison between standard authorization code grant flow and authorization code grant flow with PAR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*Itk0xYBYOU4z4iviNh1gTQ.png" /><figcaption>standard authorization code grant flow Vs authorization code grant flow with PAR</figcaption></figure><h4>Request Object support</h4><p>In situations where you need <strong>tighter security controls</strong> — like when working with sensitive data or operating in high-stakes industries such as <strong>finance or healthcare</strong> — you can take things a step further. Instead of directly encoding each authorization request parameter in the body of the PAR request, you can use a <strong>signed (and optionally encrypted) Request Object</strong>, which we explored in detail in my previous post on JAR.</p><p>In this approach, the signed and/or encrypted <strong>Request Object</strong> is added to the PAR request using the request parameter ( the one defined in the JAR specification). This lets you combine the benefits of <strong>PAR</strong> and <strong>JAR</strong>, giving you <strong>the highest level of security</strong>—something that&#39;s more than sufficient for even the most regulated industries.</p><p>Take a look at the example below to see how this looks like in PAR request. Instead of passing individual parameters like redirect_uri, scope, etc., directly in the body of the POST request, here you&#39;re wrapping them all in a signed JWT and attaching that via the request parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*eXApawMkkc72vTFSpMORjg.png" /><figcaption>Sending a Request Object in a PAR request</figcaption></figure><p>Once the authorization server receives this PAR request, it goes through the usual steps: authenticates the client, decrypts the Request Object if it’s encrypted, verifies the signature, performs any additional validation, and finally responds with a request_uri. This request_uri will then be used in the next stage of the flow, just like before.</p><p>So, other than swapping individual parameters for a <strong>Request Object </strong>, the flow remains the same—but now you’ve layered in an extra level of protection.</p><h4>Dynamic Redirect URIs</h4><p>The core <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-3.1.2.3">OAuth 2.0 specification</a> is actually a bit relaxed when it comes to callback URLs. It allows scenarios where only part of the callback URL is registered — or, in some cases, where <strong>no redirect URI</strong> is pre-registered at all. This gives client applications a bit of wiggle room to send dynamically constructed callback URLs along with their authorization requests.</p><p>However, both the <a href="https://datatracker.ietf.org/doc/html/rfc9700"><strong>OAuth2 Best Current Practice</strong></a> and the <a href="https://datatracker.ietf.org/doc/draft-ietf-oauth-v2-1/"><strong>OAuth 2.1 draft</strong></a><strong> spec</strong> strongly recommend that authorization servers <strong>require an exact match</strong> between the redirect_uri used in a request and one that was pre-registered by the client. In fact, most identity vendors have already adopted this stricter behavior. And it makes sense—this practice helps prevent client impersonation, token leakage, and open redirection vulnerabilities.</p><p>That said, in some cases, dynamically generating a callback URL per transaction is just a better architectural fit — especially for certain app designs. With PAR, that exact redirect URI matching requirement can be relaxed — but only under specific conditions. Since PAR introduces client authentication <em>before</em> the authorization request gets processed, the authorization server can be sure it’s dealing with a legitimate client. That means it can allow redirect URIs that weren’t pre-registered, giving your app the flexibility to use <strong>dynamic redirect URIs</strong>, say, to model per-session or transaction use cases. Of course, this flexibility isn’t mandatory — <strong>it’s up to the authorization server</strong> to support it or not. And even if it does, it should be used thoughtfully to avoid introducing security risks.</p><h4>Authorization Server Metadata</h4><p>The PAR specification also introduces a few metadata additions that make life easier for client applications. One of them is a new parameter called <strong>pushed_authorization_request_endpoint</strong>. This shows up in the server’s metadata document and tells client apps exactly where to send their PAR requests.</p><p>Given the <strong>client authentication rules</strong> used for token endpoint are also applicable to the PAR endpoint the existing metadata parameter <strong>token_endpoint_auth_methods_supported</strong> is applicable for PAR endpoint as well—it tells you which client authentication methods are accepted at the PAR endpoint.</p><p>Additionally the <strong>require_pushed_authorization_requests</strong> parameter indicates whether the use of PAR is mandatory or not. When is set to true, it means the authorization server <strong>only accepts authorization requests that go through PAR</strong>.</p><h4>PAR in Action</h4><p>At this point, we’ve covered most of the important details around the Pushed Authorization Requests (PAR) specification that you’ll need when applying it in real-world scenarios. Before we wrap up this post, I’d like to walk you through a quick hands-on demonstration to see PAR in action using a cloud-based identity provider. This should only take around 5 minutes.</p><p>For this, I’ll be using <a href="https://wso2.com/asgardeo/"><strong>Asgardeo</strong></a> — a public identity cloud offering from WSO2. <a href="https://wso2.com/library/blogs/pushing-the-boundaries-of-oauth-andoidc-security/">It supports</a> the PAR specification and comes with a generous free tier, which makes it a great option for testing your identity use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Q4M7ytIXMTiSy-7j_ztqg.png" /></figure><p><strong>Step 1 — Configure Asgardeo</strong></p><p>If you don’t already have an Asgardeo account, you can sign up <a href="https://wso2.com/asgardeo/">here</a>. Once you’re logged in:</p><ul><li>Create a new <strong>Traditional Web Application</strong> from the left-side menu and Keep <strong>OpenID Connect</strong> selected as the protocol (this is the default). For the <strong>Authorized redirect URLs</strong>, enter <a href="https://myapp.io/login">https://myapp.io/login</a> as the value. Then save the application settings.</li><li>Next follow <a href="https://wso2.com/asgardeo/docs/guides/users/manage-users/#onboard-single-user">this guide</a> to create a test user, which you’ll use later in this flow.</li></ul><p><strong>Step 2 — Set Up Postman</strong></p><p>Next, you’ll need to configure Postman. First, Download t<a href="https://www.postman.com/warped-eclipse-61593/workspace/public/collection/25632817-a82a5e32-4ae1-40ff-8012-d512698a6a3c?action=share&amp;creator=25632817">his Postman collection</a> for this demo. Open the collection and update the collection variables with the following values, which you can copy from your Asgardeo application:</p><ul><li>par_ep —PAR Endpoint URL from the <strong>Info</strong> tab.</li><li><a href="https://myapp.io/login">authorize_ep</a> — Token Endpoint URL from the <strong>Info</strong> tab.</li><li>token_ep — Authorization Endpoint URL from the <strong>Info</strong> tab.</li><li>client_id — Client ID <strong>protocol</strong> tab.</li><li>client_secret — Client Secret <strong>protocol</strong> tab.</li></ul><p><strong>Step 3 — Execute the Flow</strong></p><ol><li>Run the <strong>PAR-Request</strong> request from the Postman collection. You should receive a response containing a request_uri. This value is key to constructing the authorization request.</li><li>Since Postman can’t simulate browser-based redirects, we’ll take a small manual step here. Open the <strong>Code Snippet</strong> tab from the right-hand menu in Postman and select <strong>cURL</strong> from the dropdown. Then copy the location value from the cURL snippet. This URL includes the request_uri from the previous step. Finally paste that URL into your browser’s address bar and hit Enter.</li><li>You should now be redirected to Asgardeo’s login screen. Enter the credentials of the test user you created earlier. If authentication is successful, you’ll be redirected to the callback URL with a code parameter in the query string. This is your authorization code. Copy the value of the codefor the next step.</li><li>Go back to Postman and open the <strong>Token-Request</strong> request. Paste the copied code into the code parameter in the request body and send the request. If everything is set up correctly, you should receive a valid token from Asgardeo.</li></ol><p>This quick walkthrough shows how easy it is to implement PAR using a modern identity platform.</p><p>This post is the third part of my <strong>Secure OAuth2</strong> series. We explored how the <a href="https://datatracker.ietf.org/doc/html/rfc9126"><strong>Pushed Authorization Requests</strong></a><strong> (PAR)</strong> specification enhances the standard authorization code flow by introducing confidentiality, source authentication, and a more secure “pass by reference” mechanism for authorization requests.</p><p>At this point, we’ve covered both <a href="https://datatracker.ietf.org/doc/html/rfc9101"><strong>JWT-Secured Authorization Request</strong> (<strong>JAR)</strong></a> and <a href="https://datatracker.ietf.org/doc/html/rfc9126"><strong>Pushed Authorization Requests</strong></a><strong> (</strong><a href="https://datatracker.ietf.org/doc/html/rfc9126"><strong>PAR</strong></a> )— two important specifications that together help address the four security concerns: <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#3bd7">P1 </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">— </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#3bd7">Integrity protection failure</a>, <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">P2 — Source Authentication Failure</a>, <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7301">P3 — Confidentiality failure</a>, <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7cb3">P4 — Lack of Request as a Reference semantic</a> . These two specifications significantly strengthen the request side of the authorization flow.</p><p>In the next post, we’ll shift our focus to the <strong>response flow</strong>, which we haven’t fully explored yet. There are still a few important details to unpack in order to make the entire OAuth2 flow as secure and robust as possible — so stay tuned!</p><h3>Other posts in the secure OAuth2 series</h3><p>Read the other posts in<strong> Secure OAuth2</strong> series.</p><ul><li><a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">Secure OAuth2 : Is Authorization Code Grant Type Secure Enough?</a></li><li><a href="https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517">Secure OAuth2 (Part -2): Put it in a JAR (JWT-Secured Authorization Request)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=529820f060d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure OAuth2 (Part -2): Put it in a JAR (JWT-Secured Authorization Request)]]></title>
            <link>https://sagarag.medium.com/secure-oauth2-part-2-put-it-in-a-jar-jwt-secured-authorization-request-fc42ca36a517?source=rss-fe43db0e480e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc42ca36a517</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[application-security]]></category>
            <dc:creator><![CDATA[Sagara Gunathunga]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 11:02:06 GMT</pubDate>
            <atom:updated>2025-04-19T07:33:54.491Z</atom:updated>
            <content:encoded><![CDATA[<h3>Secure OAuth2 (Part -2): Put it in a JAR — JWT-Secured Authorization Request</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cu7ueU84V87mYSX8kA1FIA.png" /><figcaption>(Source — <a href="https://www.thepurposefulpantry.com/alternatives-to-vacuum-sealing-jars/">https://www.thepurposefulpantry.com/alternatives-to-vacuum-sealing-jars/</a>)</figcaption></figure><p>In my <a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">last post </a>— which I published almost a year ago — I explored whether the authorization code grant type truly provides the highest level of security, and what potential risks it might carry. This grant type is widely regarded as the recommended option when involving end users, both in the <a href="https://datatracker.ietf.org/doc/rfc9700/">OAuth 2.0 best current practices</a> and the <a href="https://datatracker.ietf.org/doc/draft-ietf-oauth-v2-1/">OAuth 2.1</a> draft specification.</p><p>If you haven’t already, I highly recommend reading that <a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">first post</a> before diving into this one.</p><p><a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">Secure OAuth2 : Is Authorization Code Grant Type Secure Enough?</a></p><p>To quickly recap — in the standard <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1">Authorization Code grant</a> flow, the authorization request is sent by encoding all the necessary parameters directly into the URL as query parameters this approach is known as <strong>query parameter serialization</strong>. This request then travels through the user agent (usually a browser) to the authorization server.</p><p>While this approach works, it also comes with a few security shortcomings, here are some issues related to <strong>authorization request:</strong></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#3bd7">P1 </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">— </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#3bd7">Integrity protection failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">P2 — Source Authentication Failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7301">P3 — Confidentiality failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7cb3">P4 — Lack of Request as a Reference semantic</a></p><p>The implications tied to the <strong>authorization response</strong> of the authorization code flow includes:</p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#56ea">P5 </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">— </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#56ea">Server integrity protection failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#8c27">P6 — Client confidentiality failure</a></p><p><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#139b">P7 — Mixed-up attack</a></p><p>To start with a bit of history — the questions that I mentioned earlier weren’t really addressed in the original <a href="https://datatracker.ietf.org/doc/html/rfc6749">OAuth2 core specification</a> released back in 2012. But if we go back to the basics and think about how we can sign and encrypt the request parameters themselves, we realize that most of these security concerns could be addressed right at the foundation level. Thankfully, we didn’t have to wait too long for a solution — around the same time, a JSON-based token format called <a href="https://datatracker.ietf.org/doc/html/rfc7519">JWT</a> started gaining traction, bringing along powerful signing capabilities through <a href="https://datatracker.ietf.org/doc/html/rfc7515">JWS</a> and encryption through <a href="https://datatracker.ietf.org/doc/html/rfc7516">JWE</a>.</p><p>In 2014, the <a href="https://openid.net/specs/openid-connect-core-1_0.html">OpenID Connect (OIDC) core specification</a> introduced a concept called the <a href="https://openid.net/specs/openid-connect-core-1_0.html#JWTRequests"><strong>Request Object</strong></a><strong> solving most of the above problem</strong>. This is essentially a <a href="https://datatracker.ietf.org/doc/html/rfc7519">JWT</a> that encapsulates the request parameters, allowing the request to be signed using <a href="https://datatracker.ietf.org/doc/html/rfc7515">JWS</a> and optionally encrypted using <a href="https://datatracker.ietf.org/doc/html/rfc7516">JWE</a>. It helped to solve some of the earlier security concerns — but only within the context of OIDC.</p><p>Then in 2017, the IETF began working on a new specification inspired by this idea, called <a href="https://datatracker.ietf.org/doc/html/rfc9101"><strong>JWT-Secured Authorization Request</strong></a> (or <strong>JAR</strong>). After six years of discussion and iteration, in 2021 JAR finally became an official standard in the OAuth2 ecosystem. Because of that origin, the Request Object concept in OIDC is quite similar to what’s defined in the JAR spec — but it’s worth noting that there are still a few subtle incompatibilities between the two.</p><h4>Request Object</h4><p>The Request Object is really the heart of the JAR specification. It allows us to encode each part of the authorization request as individual JWT claims. To get a better sense of how this works, let’s start with a standard authorization request — like the one shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*ua_ZRXJx1pQVu968QOHsAA.png" /><figcaption>Typical authorization request used in authorization code grant type</figcaption></figure><p>Next, we translate those query parameter values into a JSON-encoded JWT. The following figure will show you what that same request looks like once it’s been encoded as a JWT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*-bsMekPEePjaz2HhGVDAkg.png" /><figcaption>JWT-encoded authorization request paramters</figcaption></figure><p>There are a few rules that you need to follow when doing this. For instance:</p><ul><li><strong>iss(issuer claim) </strong>— This one is mandatory. In most cases, it should be the client_id of your application. However, some authorization servers may support a custom value here, depending on prior agreements.</li><li><strong>aud (audience claim) </strong>— This should match the issuer value of the Authorization Server (AS) you’re talking to.</li></ul><p>The next step is signing the Request Object using JWS. This process involves generating a JOSE header, calculating the signature, and then producing the final JWT in compact format by applying base64url encoding — you can see how final result looks like in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*bHsq_McEAwcNH7kyowhz4g.png" /><figcaption>Signed JWT from a Request Object</figcaption></figure><p>One important thing to keep in mind: the public key that matches the private key used for signing needs to be already configured on the authorization server. Ideally, this happens during the application or client registration phase. You can do this using <a href="https://datatracker.ietf.org/doc/html/rfc7591">Dynamic Client Registration</a> (DCR) or whatever interface your authorization server provides for managing signature verification keys. This step is critical — without the corresponding public key, the authorization server won’t be able to verify the signature of the Request Object. But once it’s in place, the server can ensure that the Request Object really came from your client and that its content hasn’t been tampered with along the way. This directly addresses two of the earlier issues I mentioned: <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#3bd7">P1 </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">— </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#3bd7">Integrity protection failure</a> and <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">P2 — Source Authentication Failure</a>.</p><p>In addition to signing, you can optionally encrypt the signed JWT using JWE, based on a public key that has been agreed upon. This way, the encrypted Request Object can only be decrypted by the authorization server using its private key — which is never shared. This extra step ensures confidentiality between the client and the authorization server, effectively addressing <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7301">P3 — Confidentiality failure</a>.</p><p>So, at this point, by using a signed (and optionally encrypted) Request Object, we’ve tackled first three problems: <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#3bd7">P1 </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">— </a><a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#3bd7">Integrity protection failure</a> , <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#2e6f">P2 — Source Authentication Failure</a> and <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7301">P3 — Confidentiality failure</a>. Now, let’s dive into the different ways the JAR specification allows us to send this JWT-secured Request Object to the authorization server.</p><h4>1. Passing Authorization Request by Value</h4><p>This is the most straightforward approach: the application takes the signed (or signed and encrypted) Request Object we created earlier and encodes it as the value of the request query parameter. Then, it builds the authorization URL by including this encoded Request Object along with the client_id, and sends it to the authorization server’s authorization endpoint. The diagram below illustrates how this flow works in practice. Other than the way the parameters are sent (now wrapped inside the request parameter as a JWT), there’s really no change to the overall flow when compared to the standard Authorization Code authorization request phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*VRRPs8dI7ks4vi5ZMPHvhQ.png" /><figcaption>Authorization request phase of authorization code grant type</figcaption></figure><p>And just to make it more clear, I’ve also included a sample authorization request for reference below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*MlX1JgE255n8xV986Zt1cw.png" /><figcaption>Passing signed JWT Request Object along with the authorization request</figcaption></figure><h4>2. Passing Authorization Request by Reference</h4><p>Instead of directly passing a signed (and optionally encrypted) Request Object in the authorization request, there’s another option — you can store the Request Object in a specific location that the Authorization Server can access. Then, rather than sending the full Request Object through the user agent, you just send a URI pointing to it. The Authorization Server can then fetch the Request Object using that URI to process the authorization request.</p><p>This approach is considered more secure because the actual Request Object doesn’t pass through the user agent — it’s only available to the Authorization Server. It’s also a preferred method when dealing with large Request Objects or when your app needs to work on devices with limited processing power or slow internet connections (like mobile devices). The following diagram outlines how this flow works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*gBfAXZsWC5Z7ufNNl9waMQ.png" /><figcaption>Passing by reference flow</figcaption></figure><p>During the <strong>step-1</strong>, your client application creates the Request Object just like we discussed earlier and stores it in a location that’s accessible to the Authorization Server. This storage location can be:</p><ul><li>A local endpoint hosted by your client application</li><li>A remote endpoint hosted by the Authorization Server</li><li>A trusted third-party endpoint</li></ul><p>Then comes <strong>step 2.</strong> In this step, the client application builds the actual authorization request — but instead of including the full Request Object, it uses a new parameter introduced in the JAR specification called request_uri along with the client_id . The request_uri parameter holds the URI pointing to the previously stored Request Object.</p><p>The client sends this authorization request to the Authorization Server through the user agent, and the server fetches the actual Request Object using the provided URI. The following example shows what this kind of request looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*IcpReCI_nKvXNgPAyarHIQ.png" /><figcaption>Passing by request_uri within the authorization request</figcaption></figure><p>Once the Authorization Server receives the authorization request from the client application, it recognizes that it needs to fetch the actual Request Object. Using the value provided in the request_uri parameter, it reaches out to that location and retrieves the Request Object to continue processing the request as usual. This approach works really well when you’re dealing with large Request Objects and also offers maximum security. Since the actual Request Object isn’t sent through the user agent, it avoids unnecessary exposure. This neatly solves the earlier mentioned <a href="https://medium.com/@sagarag/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18#7cb3">P4 — Lack of Request as a Reference semantic</a> problem.</p><h4>Validating JWT-Based Requests</h4><p>Once the Authorization Server receives the Request Object — either directly as an encoded parameter in the authorization request or as a reference (where the server fetches it) — the next step is validation. If the Request Object is encrypted, the Authorization Server first decrypts it as specified by the JWE standard. Since only the Authorization Server has the private key needed for decryption, we can be confident that confidentiality is maintained between the client application and the Authorization Server.</p><p>Next, the server moves on to signature validation. It verifies the signature using the public key that was configured during the client application’s registration. A successful signature check ensures that the Request Object hasn’t been tampered with and also confirms that it truly originated from the signed client application.</p><p>Just to recap, in this post we explored how J<a href="https://datatracker.ietf.org/doc/html/rfc9101">WT-Secured Authorization Request </a>(JAR) enhances the security of the standard authorization code grant type by introducing <strong>integrity protection</strong>, <strong>source authentication</strong>, <strong>confidentiality</strong>, and support for <strong>request-by-reference</strong> semantics.</p><p>It’s been nearly five years since JAR became a standard, and we’re now seeing its concepts — especially the use of Request Objects along with signing and encryption — being adopted across different industry verticals. That said, the idea of passing the Request Object as a reference didn’t quite take off as expected. It turned out to be a bit too vague and open-ended for practical adoption.</p><p>This is where the <a href="https://datatracker.ietf.org/doc/html/rfc9126">Push Authorization Request</a> (PAR) specification steps in which I’ll dive into in my next post. PAR offers a more robust and standardized way to implement pass-by-reference while still building on the core benefits of JAR. Stay tuned!</p><h4>Other posts in the secure OAuth2 series</h4><p>Read the other posts in<strong> Secure OAuth2</strong> series.</p><p><a href="https://sagarag.medium.com/secure-oauth2-is-authorization-code-grant-type-secure-enough-725adce49f18">Secure OAuth2 : Is Authorization Code Grant Type Secure Enough?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc42ca36a517" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>