<?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 Konstantin Lapine on Medium]]></title>
        <description><![CDATA[Stories by Konstantin Lapine on Medium]]></description>
        <link>https://medium.com/@konstantin.lapine?source=rss-2bbad88d7d1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fiBFuYmHy66MCBIGsDQHRw.jpeg</url>
            <title>Stories by Konstantin Lapine on Medium</title>
            <link>https://medium.com/@konstantin.lapine?source=rss-2bbad88d7d1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:16:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@konstantin.lapine/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[Why Implementing SSO in iOS May Not Be Straightforward and How You Can Make it Work in OAuth 2.0]]></title>
            <link>https://medium.com/@konstantin.lapine/why-implementing-sso-in-ios-may-not-be-straightforward-and-how-you-can-make-it-work-in-oauth-2-0-c6176b6c88d?source=rss-2bbad88d7d1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6176b6c88d</guid>
            <category><![CDATA[forgerock]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[appauth]]></category>
            <dc:creator><![CDATA[Konstantin Lapine]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 19:40:04 GMT</pubDate>
            <atom:updated>2024-01-04T07:11:00.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Implementing SSO in iOS May Not Be Straightforward, and How You Can Make it Work in OAuth 2.0 Clients Built with AppAuth</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ca-Og4R_xBec6tH1_kFpQ.jpeg" /></figure><p>As <a href="https://tools.ietf.org/html/rfc8252">the best current practice</a> prescribes, the AppAuth SDK for iOS employs an external user-agent to interact with the user. Doing so should provide the benefit of sharing session information existing in the user’s browser. This single sign-on (SSO) approach comes with a limitation in iOS.</p><blockquote><em>This article assumes familiarity with the </em><a href="https://oauth.net/2/"><em>OAuth 2.0</em></a><em> framework and the best current practice for using it in Native Apps, outlined in RFC 8252. In </em><a href="https://developer.forgerock.com/docs/platform/how-tos/implementing-oauth-20-authorization-code-grant-protected-pkce-appauth-sdk-ios"><em>an earlier article</em></a><em>, we described in detail how to create a simple app acting as an OAuth 2.0 client with the help of the </em><a href="https://github.com/openid/AppAuth-iOS"><em>AppAuth SDK for iOS</em></a><em>. Some of the examples here will be based on the code from that simple app with the server components provided by the </em><a href="https://www.forgerock.com/"><em>ForgeRock Identity Platform</em></a><em>.</em></blockquote><h3>Contents</h3><ul><li><a href="#ea37">Introduction</a></li><li><a href="#508c">Selecting a User-Agent</a></li><li><a href="#8b3d">Enabling Persistent Cookies in ForgeRock Access Management</a></li><li><a href="#23e5">Employing Embedded User-Agent</a></li><li><a href="#ef9f">Conclusion</a></li></ul><h3>Introduction</h3><p><a href="#8d17">Back to the Contents</a></p><p>If the system browser was used as the external user-agent, no sharing of users’ authentication state would be required. However, leaving an app and opening the default browser for authentication (and/or authorization) is generally considered to be a poor user experience. Instead, the so called “in-app browser tabs” should be used for allowing the user to interact with the authorization server. Thus, by default, AppAuth calls Safari as the external user-agent only as a fall-back option, when in-app browser tabs are not available — that is, in iOS versions below 9.</p><p>In iOS 9–10, <a href="https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller">SFSafariViewController</a> is used as the user-agent. This class allows for sharing browser data, including authentication cookies, between its instances in iOS 9 and 10.</p><p>In iOS 11–13, designated authentication classes are used for interacting with the user:</p><ul><li><a href="https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession">ASWebAuthenticationSession</a> (iOS 12.0+)</li><li><a href="https://developer.apple.com/documentation/safariservices/sfauthenticationsession">SFAuthenticationSession</a> (iOS 11.0–12.0 Deprecated)</li></ul><blockquote><a href="https://developer.apple.com/support/app-store/"><em>According to Apple</em></a><em>, more than 90% of all devices are using iOS 11+.</em></blockquote><p>The authentication classes do not share <a href="https://en.wikipedia.org/wiki/HTTP_cookie#Session_cookie">session cookies</a> with Safari or other classes’ instances, making SSO an option only with persistent cookies. Session cookies are never written to disk and, conceivably, present the more secure way of maintaining user sessions. It is possible that your authorization server is using session cookies and, therefore, the SSO experience will not be automatically available with the AppAuth SDK for iOS.</p><blockquote><em>The authentication classes will ask the user for their consent to share the website data with the browser tab opened by the app. This means that the SSO experience in this case comes at the cost of an extra action required from the user.</em></blockquote><p>Here, we will discuss three options for enabling SSO with session cookies when it is not available by default in an OAuth 2.0 client built with AppAuth for iOS:</p><ul><li>Using Safari for user authentication will allow sharing of session cookies in all versions of iOS. This technique is described in the <a href="#508c">Selecting User-Agent</a> section.<br> <br>PROS:<br>- Full control over sharing browser data between authentication events.<br> <br>CONS:<br>- Authentication in Safari forces the user to leave the app.<br>- Safari tabs cannot be controlled from the app.</li><li>If calling the default browser for front-channel communications is not acceptable, enabling persistent cookies for session management could be an option in the authorization server configuration. This will allow sharing the authentication state in the iOS in-app browser tabs. An example of this approach is described in the <a href="#8b3d">Enabling Persistent Cookies in ForgeRock Access Management</a> section.<br> <br>PROS:<br>- Supported with “out of the box” configuration in AppAuth for iOS.<br> <br>CONS:<br>- May require configuration changes in the authorization server.</li><li>Alternatively, a trusted app could be given access to the user session information and allowed to share it with other apps produced by the same development team, effecting SSO via the back channel (that is, without the user being involved). A particular implementation of this method is demonstrated in the <a href="#23e5">Employing Embedded User-Agent</a> section.<br> <br>PROS:<br>- Does not depend on the operating system policies.<br>- Does not require an external user-agent.<br> <br>CONS:<br>- Requires inter-app communications; hence, works only for apps belonging to the same development team in iOS.<br>- May violate principles described in the best current practices for implementing OAuth 2.0 clients.</li></ul><p>The details for each implementation are outlined below.</p><p>The code is hosted on <a href="https://github.com/ForgeRock/exampleOAuth2Clients/blob/master/iOS-AppAuth/SSO/">GitHub</a>.</p><h3>Selecting User-Agent</h3><p><a href="#8d17">Back to the Contents</a></p><p>In iOS 11+, session cookies are not shared with the in-app browser tabs. If your authorization server uses session cookies, as <a href="https://www.forgerock.com/platform/access-management/">ForgeRock Access Management</a> does by default, SSO can be implemented with the default browser. Doing so will still comply with the best current practices set out in <a href="https://tools.ietf.org/html/rfc8252">RFC 8252</a>.</p><p>Out of the box, AppAuth for iOS automatically selects an external user-agent based on conditions set in the <a href="https://github.com/openid/AppAuth-iOS/blob/e46bf966ba0189986f377719455c3656933a1566/Source/iOS/OIDExternalUserAgentIOS.m">OIDExternalUserAgentIOS</a> class. Using the OIDExternalUserAgent interface, a modified copy of this class could be used for specifying an external user-agent explicitly when the authorization flow is initiated. For example, using Safari as the user-agent in iOS 11-12 will allow for sharing session cookies.</p><p>An example of such a custom version of the OIDExternalUserAgentIOS class can be found at <a href="https://github.com/ForgeRock/exampleOAuth2Clients/blob/master/iOS-AppAuth/SSO/User-Agent/OIDExternalUserAgentIOSSafari.swift">User-Agent/OIDExternalUserAgentIOSSafari.swift</a>. The key part of the class definition is the following statement, unconditionally opening the request URL in Safari:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1cfc604aa2530c2e2003dd3954c6430/href">https://medium.com/media/f1cfc604aa2530c2e2003dd3954c6430/href</a></iframe><p>When initiating the authorization request with AppAuth, create a new instance of the external user-agent with the new class. Then, if the request is initiated with the OIDAuthState automatic code exchange, provide the external user-agent instance as an argument to the authState(byPresenting:externalUserAgent:callback:) method in iOS 11+. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bde94652e1849f9bb99c8673151e51e9/href">https://medium.com/media/bde94652e1849f9bb99c8673151e51e9/href</a></iframe><p>By default, AppAuth for iOS will use SFSafariViewController as the user-agent in iOS versions 9 and 10. Unlike the authentication classes employed by AppAuth in iOS 11-13, SFSafariViewController can share session cookies between its instances; hence, the custom implementation of the external user-agent class is NOT used in the else clause.</p><p>If, on the other hand, you are using OIDAuthorizationService and manually exchange the authorization code for a token at the token endpoint, start the authorization flow with the present(_:externalUserAgent:callback:) method, providing the external user-agent instance as an argument. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/247ec21b748d330029057df7aa067a64/href">https://medium.com/media/247ec21b748d330029057df7aa067a64/href</a></iframe><p>Now, when the user authenticates to the authorization server from an app using Safari as the external user-agent, all browser information, including the user’s session, is naturally available on subsequent requests.</p><p>There are problems with this approach though. Leaving an app for authentication might be considered a less than ideal user experience. At least in the past, there have been reports (<a href="http://www.openradar.appspot.com/19944416">example</a>) that the App Store rejects apps using mobile Safari for signing in.</p><p>Another issue is that the Safari tab used for authentication will not be closed after the user is redirected back to the original app (contrary to an in-app browser tab that can be dismissed by the app):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*BsnqWxsUuLfFGlvcZ67gfA.png" /></figure><blockquote><em>In addition, when a </em><a href="https://tools.ietf.org/html/rfc8252#section-7.1"><em>private-use (custom) URI scheme</em></a><em> is used for redirection, Safari will prompt the user whether or not they want to open the app they are being redirected to. This does NOT happen when the user is redirected to the app via </em><a href="https://developer.apple.com/ios/universal-links/"><em>Universal Links</em></a><em>, which is Apple’s implementation of </em><a href="https://tools.ietf.org/html/rfc8252#section-7.2"><em>claimed “https” scheme URIs</em></a><em>.</em></blockquote><p>Selecting a particular user-agent may help with the opposite use case-when sharing browser data with an in-app browser tab is NOT needed. In iOS 13, setting the <a href="https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession/3237231-prefersephemeralwebbrowsersessio">prefersEphemeralWebBrowserSession</a> property will allow configuring ASWebAuthenticationSession for a private session. The authentication classes used by AppAuth in iOS 11 and 12, SFAuthenticationSession and ASWebAuthenticationSession (respectively), do not offer this option. As a result, they always present a dialog box asking the user to provide their consent for sharing the website data and the existing session information.</p><p>SFSafariViewController, however, can be used for the private session experience in iOS 11 and 12, because it does not share anything between its instances and Safari in those environments. As an in-app browser tab, it lets the user stay in the app, and can be dismissed after user interactions with the web site are no longer needed. In this case, a custom version of the OIDExternalUserAgentIOS class may be used to set the user-agent to SFSafariViewController in iOS 11 and 12. An example of such an implementation can be found at <a href="https://github.com/ForgeRock/exampleOAuth2Clients/blob/master/iOS-AppAuth/SSO/User-Agent/OIDExternalUserAgentIOSSafariViewController.swift">User-Agent/OIDExternalUserAgentIOSSafariViewController.swift</a>.</p><blockquote><em>Currently, the </em><em>OIDExternalUserAgentIOS class, included in the AppAuth SDK for iOS, does not accept arguments that would indicate which user-agent to utilize. Thus, maintaining your own custom copy of the class is necessary for selecting a particular user-agent.</em></blockquote><p>In conclusion, selecting a user-agent is easy to implement in AppAuth for iOS without maintaining a custom version of the SDK. You would only need to extend the OIDExternalUserAgent interface with a custom version of the OIDExternalUserAgentIOS class.</p><h3>Enabling Persistent Cookies in ForgeRock Access Management</h3><p><a href="#8d17">Back to the Contents</a></p><p><a href="https://www.forgerock.com/platform/access-management/">ForgeRock Access Management</a> (AM) can serve the role of an <a href="https://openid.net/specs/openid-connect-core-1_0.html#Terminology">OpenID Provider</a>. By default, it is using session cookies, which are not shared by any of the in-app browser tabs in iOS 11+. As noted in the previous section, using Safari for user authentication has its drawbacks.</p><p>Authentication based on persistent cookies can be implemented in AM by utilizing <a href="https://backstage.forgerock.com/docs/am/6.5/authentication-guide/#sec-configure-authentication-trees">Authentication Trees</a>. A simplified example of such a tree might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5PIYRYVJSnnsrMdbtxXDg.png" /></figure><p>The tree identifier needs to be mapped in OAuth2 Provider service settings in AM to an <a href="https://openid.net/specs/openid-connect-core-1_0.html#IDToken">OIDC Authentication Context Class Reference</a> (ACR) value. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOJTJe_5MaPbtezTCs7CGA.png" /></figure><p>Then, the mapped ACR value could be provided as an additional parameter in the authorization request built by AppAuth. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbe5371787b3c27d3c82f408d3567a78/href">https://medium.com/media/cbe5371787b3c27d3c82f408d3567a78/href</a></iframe><blockquote><em>The example above is based on the code from </em><a href="https://github.com/ForgeRock/exampleOAuth2Clients/blob/master/iOS-AppAuth/iOS-AppAuth-Basic"><em>iOS-AppAuth-Basic</em></a><em> app.</em></blockquote><p>If your user has already been authenticated to AM in a non-private session using the persistent cookie set in this authentication tree, the cookie will be shared with other non-private sessions utilizing the same tree, and it will allow for SSO until the cookie expires. You could initiate an authorization flow in another AppAuth app with the same additional parameters, or you could sign in by navigating to your AM web site in Safari and specify the authentication tree with the service parameter, for example:</p><p><a href="https://default.iam.example.com/am/?service=persistent-cookie">https://default.iam.example.com/am/?service=persistent-cookie</a></p><blockquote><em>According to a </em><a href="http://www.openradar.me/radar?id=5036182937272320"><em>report</em></a><em>, cookie sharing between </em><em>SFAuthenticationSession and Safari used to be delayed/unreliable in iOS 11. We don&#39;t have a confirmation of this issue in later versions of iOS.</em></blockquote><h3>Employing Embedded User-Agent</h3><p><a href="#8d17">Back to the Contents</a></p><ul><li><a href="#d548">Introduction</a></li><li><a href="#9d67">Simple Web View App</a></li><li><a href="#ac64">AppAuth-iOS Web View App</a></li><li><a href="#a575">JavaScript Messaging</a></li></ul><h4>Introduction</h4><p><a href="#23e5">Back to Employing Embedded User-Agent</a></p><p>AppAuth for iOS follows the best current practices (BCPs) outlined in RFC 8252, and calls for an external user-agent to initiate the authorization request. Doing so provides both usability and security benefits: the browser existing authentication state can be shared, system-wide tools (like password managers) can be utilized to provide a consistent user experience, and the user’s credentials are not exposed to the app.</p><p>There are some limitations and negative aspects associated with this strategy. Sharing session information with the in-app browser tabs is not always readily available in iOS. In addition, in iOS 11+, the user is informed about starting a non-private browser session in the app via a dialog box that necessitates an extra input from the user. In addition to that, the external user-agents provide limited options for blending the authentication web page into the app’s general design.</p><p>Potentially, apps could share the user’s authentication state directly, not relying on its persistence in the system browser. For example, collecting the user’s credentials via an embedded user-agent and performing authentication from inside the app code would allow for reusing existing web authentication methods and provide access to the session cookies. In addition, embedding a browser in the app would help with seamless integration of the authentication UI. This approach, however, is strongly discouraged by the BCPs.</p><p>In regard to the security and privacy considerations, the BCPs are mostly written with the third-party clients in mind.</p><blockquote><em>You can think of the first two parties as ones being bound by a contract. For example, in OAuth 2.0 terms, the first two are represented by the resource owner and the system providing access to their resources-the authorization server and the resource server. The client software arrives later on the scene and, unless it is directly controlled by the authorization system, is the third party, which is not a subject to the contract.</em></blockquote><p>Third-party apps belong to security domains separate from the one where the user’s identity is being maintained. Providing the user’s credentials to a third-party app as the means for verifying user’s identity would allow the third-party to access resources that it does not manage, and should only be able to utilize with the user’s consent. In order for the user’s identity and its authentication status to be shared across the trust boundary, a trusted communication channel needs to be established between the Identity Provider (IdP) and the third-party software. This could be done with the help of various federation protocols, which employ digital signing and encryption for setting trusted relationships. With this federation in place, a user can authenticate to an IdP with an external system tool like a browser, which the third party has no control of. Then, the user’s identity is confirmed to the third-party app with the means provided by the trusted relationship.</p><p>In the case of OAuth 2.0 clients, federation could be implemented with policies defined in the <a href="https://openid.net/connect/">OpenID Connect</a> (OIDC) standard, which extends the OAuth 2.0 framework. The OIDC layer allows communication of user’s identity via an <a href="https://openid.net/specs/openid-connect-core-1_0.html#IDToken">ID Token</a>, which contains information about the user’s authentication. Sharing this information with another app by itself does not let the other app authenticate the user to the authorization server via a back channel. An additional protocol needs to be adopted by the client and by the authorization server to enable such authentication with the means of an ID Token. Currently, there is only a draft for <a href="https://openid.net/specs/openid-connect-native-sso-1_0.html">OpenID Connect Native SSO for Mobile Apps</a>, which describes additional specifications and their use for allowing a mobile app to share the identity/authentication info with another mobile app issued by the same vendor (but not necessarily by the company hosting the authorization server).</p><blockquote><em>It is also possible that there is no need for federating identity, and all the client software needs is authorization from the user to access protected resources on their behalf. In that case, authenticating the user </em>to the client<em> against their identity manged by the OIDC Provider may be omitted. The need for SSO, however, may remain.</em></blockquote><p>All of this changes when the client software is created and controlled by the first party. The first-party software represents the business entity which has full access to user’s resources, and which maintains and protects them. Because of this, the first-party software is inherently trusted by the user, and providing user’s credentials directly to a first-party app may be an acceptable way of identifying the user. This makes federation and extra efforts associated with its implementation unnecessary and provides less prominent security benefits.</p><blockquote><em>One may even argue that providing user’s credentials to a first-party app may expose a lesser attack surface than by sharing the credentials with the default system browser. The latter option, however, could contribute to overall security by integrating with system tools; for example, access to the system password manager could make entering user’s credentials an easy and secure process.</em></blockquote><p>The notion of a first-party app introduces a double standard. The end user is not to enter their credentials directly in a third-party software, but it is OK to do so with first-party applications. Ideally, in order to provide a secure environment, the operating system needs to make a distinction between trusted and non-trusted apps. In that regard, the app review process and a <a href="https://en.wikipedia.org/wiki/Mobile_device_management">mobile device management</a> implementation may help to prevent a third party from accessing user’s credentials.</p><blockquote><em>While a good acting third-party app would probably adopt the standards, a malicious app is under no obligation to follow this admirable practice. There have been opinions raised and requests made ( </em><a href="https://openradar.appspot.com/radar?id=4963695432040448"><em>example</em></a><em>) to limit use of embedded user-agents in iOS apps. At the same time, as noted in the </em><a href="https://tools.ietf.org/html/rfc8252#section-8.7"><em>Fake External User-Agents section of RFC 8252</em></a><em>, the very presence of embedded user-agents, even in the first-party apps, makes it more difficult to detect bad actors that could use the native controls to steal user information.</em></blockquote><p>In practice, however, decisions on whether to trust their credentials to an app are often taken to the end user, which represents a black box with unknown, but reliably inconsistent properties.</p><blockquote><a href="https://tools.ietf.org/html/rfc6819#section-5.5"><em>Section 5.5 of OAuth 2.0 Threat Model and Security Considerations</em></a><em> depicts some downsides of relying on user to operate as a security system component. The concerns brought up by the RFC can only be addressed in a specially controlled environment.</em></blockquote><blockquote><em>It is worthwhile to note that all these concerns we discuss here are not specific to OAuth 2.0 implementations. While identity providers ( </em><a href="https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html"><em>example 1</em></a><em> and </em><a href="https://dev.fitbit.com/build/reference/web-api/oauth2/#obtaining-consent"><em>example 2</em></a><em>) may try to prevent the use of embedded browsers for authorization flows, the user’s credentials by themselves present a security threat when in possession of a malicious party.</em></blockquote><p>In the end, the first-party apps do exist, and user authentication with native code does take place, opening the door for developers to provide an uninterrupted user experience, and for users to share their credentials with the apps. It is expected that the end user can recognize the first party software and will enter appropriate credentials when prompted for signing in.</p><p>With access to user’s credentials and to their session information, SSO can be implemented in a proprietary way with other apps belonging to the same organization. iOS lets apps in a group defined by a development team exchange data; thus, the authentication state can be shared and SSO can be effected outside of the default browser environment.</p><p>The in-app authentication can be built with elementary native controls, allowing for almost infinite flexibility in its realization, including the presentation part and integrating the authentication UI into the rest of the app. This is a probable approach for an SDK developed by the first party. Particularities of a given SDK are beyond the scope of this general discussion.</p><p>The more generic option for building an embedded user-agent could be utilizing a prebuilt web view component provided by the operating system. A web view allows for automatic rendering of web pages that are already prepared for the browsers. In recent versions of iOS, the <a href="https://developer.apple.com/documentation/webkit/wkwebview">WKWebView</a> class represents such a component. We will demonstrate how it could be used for furnishing SSO experience between first-party apps. We will also show how the AppAuth SDK for iOS could still be employed for completing the OAuth 2.0 authorization flow after the user authenticates to the authorization server with the native control.</p><blockquote><em>While no federated authentication may be required in this case, OAuth 2.0 flows may still be required to follow the standards and existing authorization policies.</em></blockquote><p>For this, we will need two apps belonging to the same <a href="https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_security_application-groups">App Group</a>. The final result will look and act similar to this short video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZNFjeY0AHd0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZNFjeY0AHd0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZNFjeY0AHd0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/17cb4dce3eb6bb27bdda9f2258bb6473/href">https://medium.com/media/17cb4dce3eb6bb27bdda9f2258bb6473/href</a></iframe><blockquote><em>In the video, the user is firstly authenticated to the authorization server in an app designated to do just that: to open a web view and allow to create a session in the authorization server. Then, in a separate app that features an OAuth 2.0 client built with the AppAuth SDK for iOS, the user is no longer required to sign in order to initiate the authorization flow.</em></blockquote><h4>Simple Web View App</h4><p><a href="#23e5">Back to Employing Embedded User-Agent</a></p><p>The full example code can be found under <a href="https://github.com/ForgeRock/exampleOAuth2Clients/blob/master/iOS-AppAuth/SSO/WebView/SSO-WebView-1/">WebView/SSO-WebView-1/</a>. You can build your own version by following the general steps outlined below:</p><p><strong>1. Create a new iOS Single View App project in Xcode. Select Swift as the language.</strong></p><p><strong>2. Under the target properties, in Capabilities, enable App Groups.</strong><br> <br>You will be asked to select your development team, and you will need an Apple Developer account in order to add the App Groups entitlement.<br> <br>In App Groups, add a group of your choice, for example: group.com.forgerock.sso-webview.<br> <br>The App Groups entitlement will allow the app to share data with other apps in the same group, developed by the same team.<br> <br>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJJGYkk0iaE4dCLRbn3HdA.png" /></figure><blockquote><em>In this example, we assume that cookies for only one App Group need to be manged, but the implementation could be easily extended to handle multiple groups associated with the app, by creating group specific storage locations.</em></blockquote><p><strong>3. In Xcode, create a new Swift file for iOS: File &gt; New &gt; File…; for example: </strong><strong>WebViewController.swift.</strong></p><p>This file defines a class that creates a <a href="https://developer.apple.com/documentation/webkit/wkwebview">WKWebView</a> instance. It can also handle its navigation events. During authentication, the class instance will capture authentication cookies and store them in a <a href="https://developer.apple.com/documentation/foundation/userdefaults">UserDefaults</a> database associated with the App Group this app belongs too. Other apps in the same group will be able to read the cookies. The class instance will check the database for the authentication cookies presence and, if found, inject them in the WKWebView instance, thus, authenticating the user automatically when it is possible.</p><blockquote><a href="https://developer.apple.com/documentation/security/keychain_services/keychain_items/sharing_access_to_keychain_items_among_a_collection_of_apps"><em>Keychain Sharing</em></a><em> provides a more secure option for persistent types of sensitive data and is recommended for production use. This technique deserves its own deliberation and is not covered here. For these demo apps, storing temporary, user specific credentials (like cookies and other short-lived tokens) in unencrypted form may be sufficient. Foreign apps will not be able to access the group data at the run time.</em></blockquote><p>Sounds pretty bad so far, right? Well, that is how the “double standard” manifests in this case. The first-party apps, controlled by a development team representing a business entity, <em>are</em> trusted by the user authenticating to the same party. There is no fundamental requirement for a business entity (including one represented by the user) to hide anything from itself. A given app, of course, should be limited in its capabilities, depending on the environment it operates in, and a given user should have limited access to the system, but the apps installed on the same iOS device and belonging to the same party shouldn’t need to hide the user’s authentication information from each other.</p><blockquote><em>In iOS, a multi-user environment is not currently supported out of the box.</em>The entire content of the class can be found at <a href="https://github.com/ForgeRock/exampleOAuth2Clients/blob/master/iOS-AppAuth/SSO/WebView/SSO-WebView-1/SSO-WebView-1/WebViewController.swift">WebView/SSO-WebView-1/SSO-WebView-1/WebViewController.swift</a></blockquote><p>The key elements of this class are these:</p><p>3.1. We need to create a WKWebView instance; hence the <a href="https://developer.apple.com/documentation/webkit">WebKit</a> framework is imported.</p><p>3.2. We initialize the class with parameters describing which URL to initiate the web view with, which cookies to track, and which App Group to make those cookies available for. The frame to render the web view instance in and the web view configuration parameters could also be provided.</p><p>3.3. We include a default <a href="https://developer.apple.com/documentation/webkit/wknavigationdelegate">WKNavigationDelegate</a>, with an option for the caller of this class to specify their own.<br> <br>Depending on how the web view is used, navigation events could be handled differently. For example, during the OAuth 2.0 authorization, you will need to detect the redirection URI and parse its data, while another application in the App Group may not employ OAuth 2.0 and its redirection flows at all.</p><blockquote><em>The custom navigation handlers could be defined via parameters passed to the class and implemented with some conditional logic inside it. On the other hand, processing navigation events outside of the class is, arguably, a more flexible approach, and that is what we implement in this example.</em></blockquote><p>3.4. We capture cookies in a web view navigation event.</p><p>We could, theoretically, use <a href="https://developer.apple.com/documentation/webkit/wkhttpcookiestoreobserver">WKHTTPCookieStoreObserver</a> for this purpose, but it proved unreliable in our experience and tended to stop working under certain conditions.</p><p>4.5. The class will host methods for storing and retrieving selected (authentication) cookies.</p><p>Maintaining user session and other App Group data could also be done in a separate module; for example, one that is dedicated to session management. In this example, however, we are only trying to demonstrate the role of a web view in the authentication process and not how the code should be organized.</p><p>5.6. The class will expose a public loadWebView(completion:) method that instantiates a web view instance and makes it available for the caller via the completion handler.</p><p>If any authentication cookies are found in the App Group database, they will be injected in the web view before loading the initial URL.</p><p><strong>3. In the main view controller — ViewController.swift by default, we will instantiate the previously defined class, call its </strong><strong>loadWebView(completion:) method, and add the resulting web view as a subview to the root view of the controller.</strong></p><p>When creating a web view instance, you will need to provide the name of the App Group to share cookies with, the authentication cookie name(s) to track, and optionally, a <a href="https://developer.apple.com/documentation/coregraphics/cgrect">CGRect</a> location to place the web view at. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/921976e57cab9fbb1d627642e07b4b2b/href">https://medium.com/media/921976e57cab9fbb1d627642e07b4b2b/href</a></iframe><blockquote><em>No WKWebViewConfiguration will be used and no custom WKNavigationDelegate will be specified in this case.</em></blockquote><p><strong>4. Optionally, create a simple UI to load the web view on demand.</strong></p><p>In the provided code sample, the UI layout is defined programmatically, in <a href="https://github.com/ForgeRock/exampleOAuth2Clients/blob/master/iOS-AppAuth/SSO/WebView/SSO-WebView-1/SSO-WebView-1/AppDelegate.swift">WebView/SSO-WebView-1/SSO-WebView-1/AppDelegate.swift</a>, in the application(_:didFinishLaunchingWithOptions:) method. You can use a storyboard for the same purpose, if that is your preference. You can also choose to require no interaction from the user and display no navigation items, loading the web view automatically.</p><p>Signing in at the provided URL in this example will save authentication cookies in the App Group specific location; thus making the cookies available for another app belonging to the same group.</p><p>If you built and run the example app, it should take you to the authentication endpoint and let to sign in. Subsequent requests to this site in a web view created with the WebViewController class and instantiated with the same authentication parameters should not require the user to authenticate again, unless the user’s session is expired.</p><h4>AppAuth-iOS Web View App</h4><p><a href="#23e5">Back to Employing Embedded User-Agent</a></p><p>In this app, we will try to reuse existing authentication information, and also perform an authorization flow with the help of the AppAuth SDK for iOS.</p><p>To highlight the essence of this implementation, we will modify an existing app described in <a href="https://developer.forgerock.com/docs/platform/how-tos/implementing-oauth-20-authorization-code-grant-protected-pkce-appauth-sdk-ios">Implementing OAuth 2.0 Authorization Code Grant protected by PKCE with the AppAuth SDK in iOS apps</a>. The original app authenticates with the external user-agent called up by AppAuth. We will authenticate with a web view instead, and then continue the authorization flow with the methods provided by the SDK. All identity provider references like URIs, cookie names, and others will be incidental here and serve only as examples. You can replace them with your own identity provider specifics.</p><p>The full code example can be found at <a href="https://github.com/ForgeRock/exampleOAuth2Clients/blob/master/iOS-AppAuth/SSO/WebView/iOS-AppAuth-Basic/">WebView/iOS-AppAuth-Basic/</a>. It was built by following a procedure outlined below:</p><p><strong>1. Make a copy of the </strong><a href="https://github.com/ForgeRock/exampleOAuth2Clients/blob/master/iOS-AppAuth/iOS-AppAuth-Basic/"><strong>iOS-AppAuth-Basic</strong></a><strong> app.</strong></p><p><strong>2. In the root of that folder, run:</strong></p><pre>carthage bootstrap --platform iOS</pre><p>You can also try to update the library content with the latest:</p><pre>carthage update --platform iOS</pre><p><strong>3. Add a copy of the WebViewController.swift file (created in the previous section) to this project.</strong></p><p><strong>4. Optionally, in Xcode, change the project’s Display Name and bundle identifier just to indicate that it uses a web view instead of an external user-agent.</strong></p><p><strong>5. Under the target properties, in Capabilities, enable App Groups, and select your development team.</strong></p><p>In App Groups, add <em>the same</em> group as the one we created for the first app; here, it is: group.com.forgerock.sso-webview.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vJVx5MCF-E4N5Cw2.png" /></figure><p><strong>6. In ViewController.swift, add the following properties to the main class:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84a3cb66e3a3fd1f5c9c20983a04bc0e/href">https://medium.com/media/84a3cb66e3a3fd1f5c9c20983a04bc0e/href</a></iframe><p>These properties will let you instantiate a web view and use it for interacting with the user in the authorization process.</p><p><strong>7. In the main view controller, add a new </strong><strong>authorizeWithWebView(configuration:clientId:redirectionUri:scopes:completion:) method, which will instantiate the web view with the URL for authorization endpoint. For example:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0123afa8b9bc245df83772bfe73e2ae6/href">https://medium.com/media/0123afa8b9bc245df83772bfe73e2ae6/href</a></iframe><p><strong>8. To use the web view in the authorization flow, the redirection response from the authorization endpoint will need to be handled in the view’s WKNavigationDelegate.</strong></p><p>The default implementation of the WebViewController class does not have a special handler for navigation action from the authorization endpoint. The class could, in theory, accept a parameter defining this behavior. However, having its own version of the entire delegate provides the calling class with more freedom in responding to navigation events.</p><blockquote><em>For handling redirection with a </em><a href="https://tools.ietf.org/html/rfc8252#section-7.1"><em>private-use (custom) URI scheme</em></a><em>, you could use </em><a href="https://developer.apple.com/documentation/webkit/wkurlschemehandler"><em>WKURLSchemeHandler</em></a><em>. Intercepting a navigation action, however, provides a more reliable and generic way to process the redirection URI. As was explained in </em><a href="https://developer.forgerock.com/docs/platform/how-tos/implementing-oauth-20-authorization-code-grant-protected-pkce-appauth-sdk-ios"><em>Implementing OAuth 2.0 Authorization Code Grant protected by PKCE with the AppAuth SDK in iOS apps</em></a><em>, custom URI schemes, in comparison to Universal Links, are the less secure option when used in OAuth 2.0 redirection flows. Universal Links utilize “https” scheme, which WebKit already knows how to handle.</em></blockquote><p>Import the WebKit framework in the main view controller to make the WKNavigationDelegate protocol available:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a93c79d7c1c8a672d196375495958490/href">https://medium.com/media/a93c79d7c1c8a672d196375495958490/href</a></iframe><p>Add an extension to the main view controller that will adopt the WKNavigationDelegate protocol. You could use the content of the default WKNavigationDelegate delegate definition from WebViewController.swift as a starting point, or define the new delegate from scratch. Then, modify the webView(_:decidePolicyFor:decisionHandler:) method so that redirection data from the authorization endpoint could be processed and the cookies from the authorization endpoint domain could be saved. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d8a381c29b5210c6bfa9b694146d257/href">https://medium.com/media/2d8a381c29b5210c6bfa9b694146d257/href</a></iframe><p>Note, that the cookies from the issuer domain are saved with the public method defined in WebViewController.swift:</p><pre>self.webViewController.saveCookies(cookies)</pre><p><strong>8. Now, you can call the new </strong><strong>authorizeWithWebView(configuration:clientId:redirectionUri:scopes:completion:) method from </strong><strong>authorizeRp(issuerUrl:configuration:completion:):</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d49a499e4b9d9e05967477dc8b2b98cc/href">https://medium.com/media/d49a499e4b9d9e05967477dc8b2b98cc/href</a></iframe><p>If you build and run the app now, the web view will appear in the provided frame loading the specified URL. If the cookies have been saved in the App Group database, the view should take the user to the authorization endpoint or to the consent screen, if one is displayed by the server, bypassing the login prompt.</p><h4>JavaScript Messaging</h4><p><a href="#23e5">Back to Employing Embedded User-Agent</a></p><p>The sign in process may require additional information exchange between the native environment and the authentication system; for example, communicating device information or leveraging multi-factor authentication. While a prebuilt solution like WKWebView imposes certain constraints in this regard, it is still possible to establish such communication. For that purpose, I am afraid, we will have to use JavaScript!</p><p>Imagine, that on an authentication page there is some dynamic content calling for an action to be performed by the native client, the results of which need to be reported back to the web application.</p><p>We will imitate this dynamic web content with a JavaScript injected into the web view content from a source file. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3d089f119ce95628ede397048050430/href">https://medium.com/media/b3d089f119ce95628ede397048050430/href</a></iframe><p>The posted “callback” message represents a hypothetical request for an action from the authentication endpoint to the native app. We will accommodate the message format in a codable structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d8a0fddeb768254bd05648d0f3b5299/href">https://medium.com/media/6d8a0fddeb768254bd05648d0f3b5299/href</a></iframe><p>In order for the source file to be available at the run time, it will need to be added to the app bundle in Target &gt; Build Phases &gt; Copy Bundle Resources. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*loUjCjawr--JUDsj.png" /></figure><blockquote><em>For an imitation of a JavaScript code running on a web page, we could use </em><a href="https://developer.apple.com/documentation/webkit/wkwebview/1415017-evaluatejavascript"><em>evaluateJavaScript(_:completionHandler:)</em></a><em> for executing the statement included in WebViewController.js. However, storing JavaScript content in a file seems to be a solution that is easier to read and maintain.</em></blockquote><p>In order to be able to inject scripts and handle messages received from the web view content, we will need to configure the web view with the <a href="https://developer.apple.com/documentation/webkit/wkusercontentcontroller">WKUserContentController</a> class and adopt the <a href="https://developer.apple.com/documentation/webkit/wkscriptmessagehandler">WKScriptMessageHandler</a> protocol.</p><p>Add the following extension, conforming to the WKScriptMessageHandler protocol, to the main view controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e30e08a0be8b48de52f95dffc4c7890d/href">https://medium.com/media/e30e08a0be8b48de52f95dffc4c7890d/href</a></iframe><p>This example implementation of <a href="https://developer.apple.com/documentation/webkit/wkscriptmessagehandler/1396222-usercontentcontroller">userContentController(_:didReceive:)</a> will respond to the “callback” message, process its data, invoke an action in the native app, and respond back to the page with an action against the web content.</p><blockquote><em>The example actions here serve only demonstrational purposes and could be replaced with some meaningful information exchanged between the native app and the authorization server front-end.</em></blockquote><p>You can now add WKUserContentController to the web view configuration and use its <a href="https://developer.apple.com/documentation/webkit/wkusercontentcontroller/1537172-add">add(_:name:)</a> method to register a message handler for the “callback” name we used in the WebViewController.js script. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37503f37c4bb021302f651750d50b4fd/href">https://medium.com/media/37503f37c4bb021302f651750d50b4fd/href</a></iframe><p>Now, when you build and run the app, you’ll be greeted with a native prompt initiated from the JavaScript code on the web page. Responding to the prompt will execute a JavaScript function on the web page, manifesting itself as the page background change.</p><p>Utilizing a web view allows for reusing functionality already built for the browsers. Building your own embedded browser, with more elementary native controls, may be beneficial in highly specialized cases. It would, however, require replicating the web functionality with native means and maintaining it separately from the web content.</p><h3>Conclusion</h3><p><a href="#8d17">Back to the Contents</a></p><p>There seems to be no standard solution for implementing SSO based on browser cookies in iOS in a way that is compliant with the best current practices and recommendations for OAuth 2.0 clients. In this overview, we extended our experience with the AppAuth SDK for iOS by describing a few additional options for enabling SSO when it is not available with the SDK “out of the box”.</p><p><em>Originally published at </em><a href="https://developer.forgerock.com/docs/platform/how-tos/enabling-sso-appauth-sdk-ios"><em>https://developer.forgerock.com</em></a><em> on September 24, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6176b6c88d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve Security of Your OAuth 2.0 Client by Knowing its Audience]]></title>
            <link>https://medium.com/@konstantin.lapine/improve-security-of-your-oauth-2-0-client-by-knowing-its-audience-47887d62d4dc?source=rss-2bbad88d7d1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/47887d62d4dc</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[forgerock]]></category>
            <dc:creator><![CDATA[Konstantin Lapine]]></dc:creator>
            <pubDate>Thu, 05 Mar 2020 20:55:03 GMT</pubDate>
            <atom:updated>2024-01-04T07:11:23.642Z</atom:updated>
            <content:encoded><![CDATA[<h3>Improve the Security of Your OAuth 2.0 Client by Knowing its Audience</h3><figure><img alt="Silhouette of Audience in Theater" src="https://cdn-images-1.medium.com/max/1024/1*IDTL-bL-CyZTVWugVolvpQ.png" /></figure><p><a href="https://oauth.net/2/">OAuth 2.0</a> clients may work with more than one API. Leakage of access tokens at the <a href="https://tools.ietf.org/html/rfc6749#section-1.1">resource server</a> becomes an important consideration in that case. We will discuss a mitigation technique for this threat based on the use of<em> resource-specific</em> <a href="https://tools.ietf.org/html/rfc6749#section-1.4">access tokens</a>. We will also look at an example of implementing this approach in the <a href="https://nodejs.org/">Node.js</a> environment. Basic knowledge of the OAuth 2.0 framework will be helpful to and expected of the reader.</p><h3>Contents</h3><ul><li><a href="#0273">Server-side OAuth 2.0 Client</a></li><li><a href="#218a">Compromised Resource Server</a></li><li><a href="#51d1">Mitigation Techniques</a></li><li><a href="#f050">Implementing Resource-Specific Access Tokens</a></li><li><a href="#d3ab">Relying on Refresh Tokens</a></li><li><a href="#271d">Conclusion</a></li></ul><h3>Server-side OAuth 2.0 Client</h3><p><a href="#9e27">Back to Contents</a></p><p>A server-side web application acting as an OAuth 2.0 <a href="https://tools.ietf.org/html/rfc6749#section-1.1">client</a> is different from such a client in a single-page or a native application in two important ways:</p><ul><li>The client can run entirely in a secure server environment and have its secrets inaccessible to the end user.<br> <br>This qualifies it for a <a href="https://tools.ietf.org/html/rfc6749#section-2.1">confidential</a> OAuth 2.0 client, which can authenticate to the <a href="https://tools.ietf.org/html/rfc6749#section-1.1">authorization server</a> with safely kept credentials, and therefore, cannot be easily impersonated at the <a href="https://tools.ietf.org/html/rfc6749#section-3">token endpoint</a>.<br> <br>It also means that the tokens received by the client from the <a href="https://tools.ietf.org/html/rfc6749#section-1.1">authorization server</a> can be requested <em>and used</em> over a secure back channel and never be exposed to the front end. It is possible that only results of the calls made to protected APIs will be shared with the user interface.<br> <br>Hence, besides the client itself and the server it runs on, an access token issued by the authorization server is exposed to only one other party where it can potentially leak — the protected API it was sent to, the <a href="https://tools.ietf.org/html/rfc6749#section-1.1">resource server</a> in OAuth 2.0 terms.</li><li>The user data can be processed in the absence of the end user.<br><br>In the most common application of OAuth 2.0 the <a href="https://tools.ietf.org/html/rfc6749#section-1.1">resource owner</a> is the end user. A browser-based application cannot function when the user is offline. While a native application might be able to perform some activities when the user is not around, it is likely to be limited in what it can do and for how long, especially in the mobile environment. A server-side web application, like one that can be built with Node.js, may stay active regardless of the user’s presence, and may need access to their resources to react to changes in the data, or to use it in long-running data processing tasks, as an example. <br> <br>Often, an OAuth 2.0 client would use <a href="https://tools.ietf.org/html/rfc6749#section-1.5">refresh tokens</a> as a reliable way to ensure its continuous access to the user’s resources.</li></ul><h3>Compromised Resource Server</h3><p><a href="#9e27">Back to Contents</a></p><p>OAuth 2.0 adopted the idea of an unbounded bearer access token, which meant that a client application does not have to authenticate to the resource server, and no cryptography is required on the client side. This allowed for relatively simple OAuth 2.0 client implementations, but the down side has been that a lost or stolen access token grants the same access to a malicious party as it would do to a legitimate client.</p><p>As a result, in all parts of an OAuth 2.0 implementation, care should be taken to prevent leakage of access tokens into the hands of an unauthorized party.</p><p>In the server-side OAuth 2.0 client model described here, the authorization server, the client, and the resource servers communicate mostly over a secure back channel, and the access tokens may only leak during the transport or in the server environment itself.</p><blockquote><em>The only recommended </em>interactive<em> OAuth 2.0 flow, performed in the front channel on behalf of a specific user, is the </em><a href="https://tools.ietf.org/html/rfc6749#section-1.3.1"><em>authorization code grant</em></a><em>, in which the client software receives a code to be exchanged for an access token, and optionally, for a refresh token at the authorization server token endpoint. Because the code exchange is done via the secure back channel, a server-side confidential client is not susceptible to the attacks resulting in access token loss at the token endpoint — due to the client’s ability to authenticate to the authorization server.</em></blockquote><p>The standard remedies for protecting server environment from breaches apply here, and they are not OAuth 2.0 specific. There are, however, OAuth 2.0-specific measures to limit the extent of damage resulting from leakage of an access token due to a compromised or otherwise malicious resource server.</p><p>The resource server considerations come from the fact that the access tokens it receives may be valid for accessing other APIs in deployments with multiple resource servers. Then, a malicious party in control of one of the resource servers may be able to replay the token on another.</p><blockquote><em>An authorization server acting as an </em><a href="https://openid.net/specs/openid-connect-core-1_0.html#Terminology"><em>OpenID provider</em></a><em> may expose the resource owner profile information over the </em><a href="https://openid.net/specs/openid-connect-core-1_0.html#UserInfo"><em>UserInfo Endpoint</em></a><em> and in this way, introduce an additional instance of a resource server.</em></blockquote><p>The extent of the authorization associated with an access token is defined in its scope, which is normally expressed via a set of space-delimited string values. These values are interpreted by the resource server, and may be presented in an understandable way to the resource owner — for authorization. In the most common OAuth 2.0 use, the resource owner is a user, and the client is an application developed by a <em>third party</em>, the entity which does not initially have access to the user’s data. An action is typically required from the user to give their consent for authorizing the third-party client with the scopes it needs. Authorizing all the scopes that the client currently needs in a single request will likely constitute for a better user experience, because trips to the authorization server and back in the front channel may interrupt the user’s activities and should probably be minimized.</p><blockquote><em>A </em>first-party<em> application, managed by the same business entity as the one that controls the authorization system and maintains access to the user data, may not need to ask its users for explicit authorization consent; such an application may rely solely on the user’s authentication. However, one can argue that OAuth 2.0 mostly aims to help with the business expansion by allowing third-party clients to access the first-party APIs.</em></blockquote><p>Thus, initial authorization by the resource owner may result in a super-charged access token, which can be replayed at different resource servers.</p><h3>Mitigation Techniques</h3><p><a href="#9e27">Back to Contents</a></p><p>The <a href="https://tools.ietf.org/html/draft-ietf-oauth-security-topics-14">OAuth 2.0 Security Best Current Practices</a> (BCP) suggests three techniques to limit the damage that may result from access tokens leaked at a resource server:</p><ul><li><a href="https://tools.ietf.org/html/draft-ietf-oauth-security-topics-14#section-4.8.1.1.1">Metadata</a> about legitimate resource servers.<br> <br>Providing information about safe-to-visit resource servers implies that the client limits its activities to the servers in a white list.<br> <br>PROS<br>- Is simple to implement.<br> <br>CONS<br>- Relies exclusively on the client implementation; cannot not be enforced otherwise.<br>- Does not help with the case of a legitimate resource server being compromised.<br>- Is not described in the currently accepted OAuth 2.0 standards.</li><li><a href="https://tools.ietf.org/html/draft-ietf-oauth-security-topics-14#section-4.8.1.1.2">Sender-Constrained Access Tokens</a>.<br> <br>PROS<br>- The recommended by OAuth 2.0 Security BCP implementation of sender-constrained tokens is based on the existing TLS technology.<br>- May be able to prevent replay of stolen access tokens on the compromised resource server itself.<br> <br>CONS<br>- Moves away from the idea of unbounded bearer access token and brings additional complexity back to the client.<br>- With the currently accepted OAuth 2.0 standards, it is not recommended for use in public clients. This may limit widespread adoption of the technique.</li><li><a href="https://tools.ietf.org/html/draft-ietf-oauth-security-topics-14#section-4.8.1.1.3">Audience Restricted Access Tokens</a>.<br> <br>PROS<br>- Relatively easy to adopt by OAuth 2.0 clients; does not require cryptography on the client side.<br>- Can be implemented with a standard OAuth 2.0 parameter, the <a href="https://tools.ietf.org/html/rfc6749#section-3.3">scope</a> — by utilizing resource-specific scope values.<br>- Allows a client to use access tokens of different format, content, and life span when accessing multiple resources.<br>- Can be independently implemented in an OAuth 2.0 client, and supported by the resource server and the authorization server.<br> <br>CONS<br>- Does not prevent access token replay by a different sender on the resource server the token was issued and restricted to.</li></ul><p>One may conclude that the metadata approach is not robust enough to render serious security benefits.</p><p>The sender-constrained access tokens can provide the best security, but may require the most effort in the client implementation. The technique recommended by the BCP, <a href="https://tools.ietf.org/html/rfc8705">OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens</a>, need to be supported by authorization and resource servers and the other sender-constraining specifications are still in the draft stage. This probably means they are likely to be deployed as needed and not adopted universally for some time.</p><p>On the other hand, making use of resource-specific access tokens gives both security and functional advantages. In its simplest form, audience restriction does not need to be accommodated by the authorization server or the resource server; the client may “simply” maintain separate access tokens associated with resource-specific scopes that do not overlap. One step further, the resource server can support audience restriction by accepting only access tokens with a unique and specific to this resource server scope. Further yet, authorization server can issue access tokens specific to a respective resource. The client may indicate what resource it needs the access token for via a unique and specific to the resource scope, or with the help of the <a href="https://tools.ietf.org/html/rfc8707">Resource Indicators for OAuth 2.0</a>, if they are supported by the authorization server.</p><p>Limiting the audience and the scope of an access token to a single resource server has been recommended from the start by the <a href="https://tools.ietf.org/html/rfc6750#section-5.2">OAuth 2.0 Bearer Token Usage</a> RFC, and the recommendation was inherited by the <a href="https://openid.net/specs/openid-connect-core-1_0.html#AccessTokenRedirect">OpenID Connect Core</a> specification. Expressing a resource with a scope value allows resource-specific access tokens to operate in the environment already described by the widely accepted OAuth standards.</p><blockquote><em>Outside of specifications developed by the OAuth working group of the Internet Engineering Task Force (IETF), techniques like </em><a href="https://research.google/pubs/pub41892/"><em>Google Macaroons</em></a><em> may be employed to communicate restrictions applied to an access token.</em></blockquote><p>The resource specificity, therefore, seems to be the most generic solution that can be commonly applied among OAuth 2.0 clients to mitigate damage from access tokens leakage at a malicious or a compromised resource server. In addition, maintaining separate access tokens for multiple resources allows a client to adopt various token requirements for different resource servers. This strategy can also provide privacy benefits, for the information associated with an access token will not be shared between resources.</p><h3>Implementing Resource-Specific Access Tokens</h3><p><a href="#9e27">Back to Contents</a></p><p>Maintaining resource specificity for the purposes of audience restriction, utilizing diverse access tokens, and preserving privacy does not necessarily require any cryptography in the client. It does, however, add complexity to its code because of the need to track, renew, and apply different access tokens for multiple resources.</p><blockquote><em>The </em><a href="https://tools.ietf.org/html/draft-ietf-oauth-token-binding-08"><em>OAuth 2.0 Token Binding</em></a><em> technique features separate access tokens for multiple resource servers as well.</em></blockquote><p>To help with its implementation, adoption of resource-specific access tokens in a Node.js client has been demonstrated in an open source library, the <a href="https://www.npmjs.com/package/openid-client-helper">openid-client-helper</a> NPM package. This library has an easy to use interface for building an OAuth 2.0 client extended to an OIDC <a href="https://openid.net/specs/openid-connect-core-1_0.html#Terminology">relying party</a> that will be able to:</p><ul><li>Perform common tasks associated with the authorization code grant.</li><li>Automatically obtain and refresh resource-specific access tokens for registered resource servers.</li><li>Automatically include the appropriate access tokens in requests made to protected resources.</li></ul><p>Besides a simple use case example included with the library, there is also the <a href="https://github.com/ForgeRock/exampleOAuth2Clients/tree/master/node-openid-client">openid-client-helper example</a> project on GitHub, which shows comprehensively how to use this library in a Node.js application. <a href="https://github.com/ForgeRock/forgeops">ForgeRock Identity Platform</a> furnishes authorization and resource server components in that example, but any other provider supporting OAuth 2.0 and OIDC could be used.</p><blockquote><em>While the openid-client-helper library has methods and middleware for authorizing and deauthorizing the client, its unique feature is ability to maintain and apply access tokens minted for a specific resource. The actual authorization may be performed with an external tool. For instance, a </em><a href="https://github.com/jaredhanson/passport"><em>Passport.js</em></a><em> strategy may be employed for obtaining initial authorization data, as demonstrated in </em><a href="https://github.com/ForgeRock/exampleOAuth2Clients/tree/master/node-passport-openidconnect"><em>another Node.js OAuth 2.0 client example</em></a><em>.</em></blockquote><h3>Relying on Refresh Tokens</h3><p><a href="#9e27">Back to Contents</a></p><p>The openid-client-helper library uses a <a href="https://tools.ietf.org/html/rfc6749#section-1.5">refresh token</a> for getting resource-specific access tokens after the initial authorization by the resource owner.</p><p>This is possible because the refresh token is associated with all the scope values (and optionally, all <a href="https://tools.ietf.org/html/rfc8707#section-2">resource indicators</a>) that had been authorized. Then, the refresh token can be exchanged for an access token associated with a selected subset of the authorized parameters. In addition, if supported by the authorization server, the resource-specific access tokens can be of different format, content, and expiration.</p><p>There may already be reasons for an OAuth 2.0 client to employ refresh tokens, in which case, relying on their presence is not an additional requirement:</p><ul><li>An OAuth 2.0 client can use a refresh token to reauthorize itself, even when the resource owner is not actively using the application. This allows the client to offer functionality based on the user’s data in an ongoing basis, which many server-side client applications are designed to accomplish.</li><li>Short-lived access tokens are considered by the OAuth 2.0 Security BCP as a <a href="https://tools.ietf.org/html/draft-ietf-oauth-security-topics-14#section-4.12">security advantage provided by refresh tokens</a>. Reauthorization with a refresh token can be performed frequently via the back channel without breaking the user experience or relying on the saved user’s consent.</li></ul><blockquote><em>The security benefits of short-lived access tokens may be limited, because loss of a “short-lived” access token in the context of an automated attack may still present a substantial danger. Nevertheless, a short life span is a desirable characteristic of an access token in many situations, since it provides an equivalent to a prompt revocation. This is particularly valuable if the authorization server issues stateless access tokens, which cannot normally be revoked at all.</em></blockquote><p>Requesting access tokens for each resource server individually could be, therefore, an additional application of refresh tokens.</p><h3>Conclusion</h3><p><a href="#9e27">Back to Contents</a></p><p>In OAuth 2.0 deployments with multiple resource servers, use of resource-specific access tokens provides security and functional benefits.</p><p>ForgeRock supplies a library for building an OAuth 2.0 client in the Node.js environment, the <a href="https://www.npmjs.com/package/openid-client-helper">openid-client-helper</a> NPM package, which can automatically obtain, renew, and apply resource-specific access tokens. In deployments with multiple resource servers, this allows for improved security via the audience restricted access tokens, as described in the OAuth 2.0 Security BCP.</p><p>An example of putting this library in use can be found at the <a href="https://github.com/ForgeRock/exampleOAuth2Clients/tree/master/node-openid-client">openid-client-helper example</a> GitHub project.</p><p><em>Originally published at </em><a href="https://developer.forgerock.com/docs/platform/how-tos/improving-security-oauth-20-clients-nodejs"><em>https://developer.forgerock.com</em></a><em> on January 17, 2020.</em></p><p>I would like to thank <a href="https://medium.com/u/ae730c274a1">Aaron Parecki</a> for maintaining <a href="https://oauth.net/2/">https://oauth.net/2/</a>. This site is a convenient entry point for those interested in learning OAuth 2.0 and an easy reference to provide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47887d62d4dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>