ForgeRock Developer Experience

Use centralized login

Applies to:

  • ForgeRock SDK for Android

  • ForgeRock SDK for iOS

  • ForgeRock SDK for JavaScript

The following diagram shows a sample OAuth 2.0 flow that the ForgeRock SDK uses for your native app:

OAuth 2.0 for Native Apps

Note that the SDKs also support OAuth 2.0 security with PKCE.

Set up centralized login in Android apps

This section describes how to configure your ForgeRock Android SDK application to use centralized login by leveraging the AppAuth library:

  1. Add the build dependency to the build.gradle file:

    implementation 'net.openid:appauth:0.11.1'
  2. Configure the app to allow the AppAuth library to capture authorization redirects.

    Add the custom scheme your app will use to your build.gradle file:

    android.defaultConfig.manifestPlaceholders = [
        'appAuthRedirectScheme': 'com.forgerock.android'
    ]
  3. When using a custom scheme, you can configure AppAuth to capture all redirects using this custom scheme through a manifest placeholder.

    1. Configure the redirect URI by adding an <intent-filter> for AppAuth.RedirectUriReceiverActivity to your AndroidManifest.xml:

      <activity
         android:name="net.openid.appauth.RedirectUriReceiverActivity"
         tools:node="replace">
          <intent-filter>
             <action android:name="android.intent.action.VIEW"/>
             <category android:name="android.intent.category.DEFAULT"/>
             <category android:name="android.intent.category.BROWSABLE"/>
             <data android:scheme="com.forgerock.android"/>
          </intent-filter>
      </activity>
    2. Add the following to the strings.xml file:

      <string name="forgerock_oauth_redirect_uri" translatable="false">com.forgerock.android:/oauth2redirect</string>
    3. In the Identity Cloud admin UI, update the Application Sign-in-URLs to match the value:

      com.forgerock.android

    For more information, refer to Capturing the authorization redirect.

  4. For Android 11 or higher, add the following to the AndroidManfest.xml file:

    <queries>
         <intent>
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.BROWSABLE" />
             <data android:scheme="com.forgerock.android" />
         </intent>
     </queries>

    For more information, refer to Open URLs in a browser or other app.

  5. Configure your application to use browser mode:

    // Use FRUser.browser() to enable browser mode:
    FRUser.browser().login(context, new FRListener<FRUser>());
    
    // Use standard SDK interface to retrieve an AccessToken:
    FRUser.getCurrentUser().getAccessToken()
    
    // Use standard SDK interface to logout a user:
    FRUser.getCurrentUser().logout()

    The SDK uses the OAuth 2.0 parameters you configured in your application.

    You can amend the example code above to customize the integration with AppAuth; for example, adding OAuth 2.0 or OpenID Connect parameters, and browser colors:

     FRUser.browser().appAuthConfigurer()
         .authorizationRequest(r -> {
             // Add a login hint parameter about the user:
             r.setLoginHint("demo@example.com");
             // Request that the user re-authenticates:
             r.setPrompt("login");
         })
         .customTabsIntent(t -> {
             // Customize the browser:
             t.setShowTitle(true);
             t.setToolbarColor(getResources().getColor(R.color.colorAccent));
         }).done()
         .login(this, new FRListener<FRUser>() {
             @Override
             public void onSuccess(FRUser result) {
                 //success
             }
    
             @Override
             public void onException(Exception e) {
                 //fail
             }
         });

Set up centralized login in iOS apps

This section describes how to configure your ForgeRock iOS SDK application to use centralized login:

  1. Configure a custom URL type, for example frauth, so that users can be redirected to your application:

    1. In Xcode, in the Project Navigator, double-click your application to open the Project pane.

    2. On the Info tab, in the URL Types panel, configure your custom URL scheme:

      Custom URL Scheme
    3. Add the custom URL scheme to the Redirection URIs property of your OAuth 2.0 client:

      OAuth 2.0 Redirection URI
    4. Update your application to call the validateBrowserLogin() function:

      1. In your AppDelegate.swift file, call the validateBrowserLogin() function:

        AppDelegate.swift
        class AppDelegate: UIResponder, UIApplicationDelegate {
        
          func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
            // Parse and validate URL, extract authorization code, and continue the flow:
            Browser.validateBrowserLogin(url)
          }
        }
      2. If your application is using SceneDelegate, in your SceneDelegate.swift file call the validateBrowserLogin() function:

        SceneDelegate.swift
        class SceneDelegate: UIResponder, UIWindowSceneDelegate {
        
          func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
            if let url = URLContexts.first?.url {
              Browser.validateBrowserLogin(url)
            }
          }
        }
  2. To enable centralized login, add code similar to the following to your app:

    //  BrowserBuilder
    let browserBuilder = FRUser.browser()
    browserBuilder.set(presentingViewController: self)
    browserBuilder.set(browserType: .authSession)
    browserBuilder.setCustomParam(key: "custom_key", value: "custom_val")
    
    //  Browser
    let browser = browserBuilder.build()
    
    // Login
    browser.login{ (user, error) in
      if let error = error {
        // Handle error
      }
      else if let user = user {
        // Handle authenticated status
      }
    }

    You can specify what type of browser the client iOS device opens to handle centralized login by using the browserType parameter.

    Each browser has slightly different characteristics, which make them suitable to different scenarios, as outlined in this table:

    browserType Characteristics

    .authSession

    Opens a web authentication session browser.

    Designed specifically for authentication sessions, however it prompts the user before opening the browser with a modal that asks them to confirm the domain is allowed to authenticate them.

    This is the default option in the ForgeRock SDK for iOS.

    .ephemeralAuthSession

    Opens a web authentication session browser, but enables the prefersEphemeralWebBrowserSession parameter.

    This browser type does not prompt the user before opening the browser with a modal.

    The difference between this and .authSession is that the browser does not include any existing data such as cookies in the request, and also discards any data obtained during the browser session. This means that an ephemeralAuthSession is not suitable when you require single sign-on (SSO) between your iOS apps.

    Use this browser type when you do not want the user’s existing sessions to affect the authentication.

    .nativeBrowserApp

    Opens the installed browser that is marked as the default by the user. Often Safari.

    The browser opens without any interaction from the user. However, the browser does display a modal when returning to your application.

    .sfViewController

    Opens a Safari view controller browser.

    Your client app is not able to interact with the pages in the sfViewController or access the data or browsing history.

    The view controller opens within your app without any interaction from the user. As the user does not leave your app, the view controller does not need to display a warning modal when authentication is complete and control returns to your application.

Set up centralized login in JavaScript apps

This section describes how to configure your ForgeRok JavaScript SDK application with centralized login:

  1. To initiate authentication by redirecting to the centralized login UI, add a login property that specifies how authentication happens in your app:

    const tokens = TokenManager.getTokens({
      forceRenew: false, // Immediately return stored tokens, if they exist
      login: 'redirect' // Redirect to AM or the web app that handles authentication
    });

    Supported values are as follows:

    Setting Description

    redirect

    Your app uses a redirect to ForgeRock® Access Management (AM), or another web application, to handle authentication.

    embedded

    Your app handles authentication natively, using SDK functionality.

    If you do not specify a value, embedded is assumed, for backwards-compatibility.

  2. When the user is returned to your app, complete the OAuth 2.0 flow by passing in the code and state values that were returned.

    Use the query property to complete the flow:

    const tokens = TokenManager.getTokens({
      query: {
        code: 'lFJQYdoQG1u7nUm8 ... ', // Authorization code from redirect URL
        state: 'MTY2NDkxNTQ2Nde3D ... ', // State from redirect URL
      },
    });