Last updated

Ionic Capacitor quickstart

This guide is a walkthrough on how to integrate Frontegg’s authentication magic into your app using the Frontegg Ionic Capacitor (Angular)) SDK. Whether you need to add secure sign-ups, logins, multi-factor authentication, or even social logins, this guide has you covered with simple, step-by-step instructions to get things rolling in no time.


Prerequisites

Frontegg Hosted Login is required, and setting a custom domain is highly recommended.
iOS ≥ 14
Android ≥ 26


Prepare Frontegg workspace

Navigate to Frontegg Portal Settings, If you don't have application
follow the integration steps after signing up. Copy FronteggDomain to future steps from Frontegg Portal Domain


frontegg-domain

Setup hosted login

  • Navigate to Login Method Settings
  • Toggle Hosted login method for iOS:
    • Add {{IOS_BUNDLE_IDENTIFIER}}://{{FRONTEGG_BASE_URL}}/ios/oauth/callback
  • Toggle Hosted login method for Android:
    • Add {{ANDROID_PACKAGE_NAME}}://{{FRONTEGG_BASE_URL}}/android/oauth/callback (without assetlinks)
    • Add https://{{FRONTEGG_BASE_URL}}/{{ANDROID_PACKAGE_NAME}}/android/oauth/callback (required for assetlinks)
  • Replace IOS_BUNDLE_IDENTIFIER with your application identifier
  • Replace FRONTEGG_BASE_URL with your Frontegg base url, without https, i.e FronteggDomain.
  • Replace ANDROID_PACKAGE_NAME with your android package name

Add Frontegg package to the project

Add capacitor to the ionic project if it does not exist:

ionic integrations enable capacitor

Configure your application

  1. Create or Modify your capacitor.config.ts file:
import { CapacitorConfig } from "@capacitor/cli";

const config: CapacitorConfig = {
  appId: "{YOUR_APPLICATION_ID}",
  appName: "{YOUR_APPLICATION_NAME}",
  webDir: "www",
  server: {
    androidScheme: "https",
  },
  ios: {
    path: "ios",
  },
  android: {
    path: "android",
  },

  plugins: {
    FronteggNative: {
      baseUrl: "https://{FRONTEGG_DOMAIN_HOST.com}",
      clientId: "{FRONTEGG_CLIENT_ID}",
    },
  },
};

export default config;

  1. Add the iOS and Android projects to your ionic app by running the following commands:

NOTE: skip the command if you already have the project added.

ionic capacitor add android
ionic capacitor add ios

Setup iOS project

  1. Create Frontegg plist file, to setup your SwiftUI application to communicate with Frontegg.

Open the ios folder created by capacitor, and run this command:

ionic capacitor open ios

or open the Xcode manually.

  1. Create a new file named Frontegg.plist under your root project directory, this file will store values to be used as variables by Frontegg SDK:
<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
   <plist version="1.0">
   <dict>
       <key>lateInit</key>
       <true/>
   </dict>
   </plist>

  1. Enable CODE_SIGNING_ALLOWED in the Podfile under /ios/App folder.

To handle Login with magic link and other authentication methods that require to open the app with a URL, you have to add the following code to the AppDelegate.swift file.


import UIKit
import Capacitor
import FronteggSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    /*
     * Called when the app was launched with a url. Feel free to add additional processing here,
     * but if you want the App API to support tracking app url opens, make sure to keep this call
     */
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        
        if(FronteggAuth.shared.handleOpenUrl(url)){
            return true
        }
        
        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }
    
    /*
     * Called when the app was launched with an activity, including Universal Links.
     * Feel free to add additional processing here, but if you want the App API to support
     * tracking app url opens, make sure to keep this call
     */
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        
        if let url = userActivity.webpageURL {
            if(FronteggAuth.shared.handleOpenUrl(url)){
                return true
            }
        }
        return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
    }
}

Configure iOS associated domain

Configuring your iOS associated domain is required for Magic Link authentication / Reset Password / Activate Account.

In order to add your iOS associated domain to your Frontegg application, you will need to update in each of your
integrated Frontegg Environments the iOS associated domain that you would like to use with that Environment. Send a POST request to https://api.frontegg.com/vendors/resources/associated-domains/v1/ios with the following payload:

{
    "appId":[YOUR_ASSOCIATED_DOMAIN]
}

In order to use our API’s, follow this guide to generate a vendor token.

Setup Android project

  1. Set minimum sdk version - open root gradle file atandroid/variables.gradle and modify the minSdkVersion to 26.
ext {
 minSdkVersion = 26
 ...
}

  1. Configure build config fields - To set up your Android application on to communicate with Frontegg, you have to add buildConfigField property the gradle android/app/build.gradle. This property will store frontegg hostname (without https) and client id from previous step:


def fronteggDomain = "FRONTEGG_DOMAIN_HOST.com" // without protocol https://
def fronteggClientId = "FRONTEGG_CLIENT_ID"

android {
    defaultConfig {

        manifestPlaceholders = [
                "package_name" : applicationId,
                "frontegg_domain" : fronteggDomain,
                "frontegg_client_id": fronteggClientId
        ]
    }
}

Add bundleConfig=true if not exists inside the android section inside the app gradle android/app/build.gradle

android {
  buildFeatures {
    buildConfig = true
  }
}

  1. Add permissions to AndroidManifest.xml - Add INTERNET permission to the app's manifest file.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

  1. Configure Android AssetLinks for Magic Link authentication / Reset Password / Activate Account / login with external IdPs.

To add your AssetLinks to your Frontegg application, you will need to update in each of your integrated Frontegg
Environments the AssetLinks that you would like to use with that Environment. Send a POST request to https://api.frontegg.com/vendors/resources/associated-domains/v1/android with the following payload:

{
    "packageName": "YOUR_APPLICATION_PACKAGE_NAME",
    "sha256CertFingerprints": ["YOUR_KEYSTORE_CERT_FINGERPRINTS"]
}

Each Android app has multiple certificate fingerprint, to get your DEBUG sha256CertFingerprint you have to run the below command. For Debug mode, run the following command and copy the SHA-256 value:

NOTE: make sure to choose the Variant and Config equals to debug

./gradlew signingReport

###################
#  Example Output:
###################

#  Variant: debug
#  Config: debug
#  Store: /Users/davidfrontegg/.android/debug.keystore
#  Alias: AndroidDebugKey
#  MD5: 25:F5:99:23:FC:12:CA:10:8C:43:F4:02:7D:AD:DC:B6
#  SHA1: FC:3C:88:D6:BF:4E:62:2E:F0:24:1D:DB:D7:15:36:D6:3E:14:84:50
#  SHA-256: D9:6B:4A:FD:62:45:81:65:98:4D:5C:8C:A0:68:7B:7B:A5:31:BD:2B:9B:48:D9:CF:20:AE:56:FD:90:C1:C5:EE
#  Valid until: Tuesday, 18 June 2052

For Release mode, Extract the SHA256 using keytool from your Release keystore file:

keytool -list -v -keystore /PATH/file.jks -alias YourAlias -storepass *** -keypass ***

Enabling chrome custom tabs for social login

To enable social login via Chrome Custom Tabs in Android application, modify your capacitor.config.ts file and set the useChromeCustomTabs flag to true . By default, the SDK uses the Chrome browser for social login.

import { CapacitorConfig } from "@capacitor/cli";

const config: CapacitorConfig = {
  appId: "{YOUR_APPLICATION_ID}",
  appName: "{YOUR_APPLICATION_NAME}",
  webDir: "www",
  server: {
    androidScheme: "https",
  },
  ios: {
    path: "ios",
  },
  android: {
    path: "android",
  },

  plugins: {
    FronteggNative: {
      baseUrl: "https://{FRONTEGG_DOMAIN_HOST.com}",
      clientId: "{FRONTEGG_CLIENT_ID}",

      useChromeCustomTabs: true,
    },
  },
};

Multi-region support

This guide outlines the steps to configure your Ionic application to support multiple regions.

  1. Add region to your Frontegg configuration in capacitor.config.ts file.

Find example code in example/capacitor.config.ts file.

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  /*...*/
  plugins: {

    /*...*/

    FronteggNative: {
      
      /** Remove baseUrl and clientId from here */
      // baseUrl: 'https://{FRONTEGG_DOMAIN_HOST.com}',
      // clientId: '{FRONTEGG_CLIENT_ID}',
      
      regions: [ {
        key: 'REGION_1_KEY',
        baseUrl: 'https://region1.forntegg.com',
        clientId: 'REGION_1_CLIEND_ID',
      }, {
        key: 'REGION_2_KEY',
        baseUrl: 'https://region2.forntegg.com',
        clientId: 'REGION_2_CLIEND_ID',
      } ]
    }
  }
};

export default config;

  1. Create region guard service.

Create region guard service, this guard will prevent application init if region not selected, and checks if specific region selected by getting the native state from the Frontegg SDK. If the region not exists, the guard will redirect to region selector page.


Find example code in example/src/app/region.guard.ts file.

import { CanActivateFn, Router } from '@angular/router';
import { Inject, Injectable } from '@angular/core';
import { FronteggService } from '@frontegg/ionic-capacitor';

@Injectable({
  providedIn: 'root'
})
export class RegionGuard {
  constructor(@Inject('Frontegg') private fronteggService: FronteggService, private router: Router) {
    /**
     * Listens to $isAuthenticated changes
     * Reload the page to trigger canActivate function again
     */
    this.fronteggService.$selectedRegion.subscribe(async () => {
      window.location.reload()
    });
  }

  canActivate: CanActivateFn = async () => {
    const { isRegional } = await this.fronteggService.getConstants();
    const nativeState = await this.fronteggService.getNativeState()

    if (!isRegional || nativeState.selectedRegion != null) {
      /**
       * region already selected, activate navigation
       */
      return true
    }

    /**
     * region not selected, redirect to region selector page
     */
    return this.router.navigate([ '/select-region' ])
  }
}

  1. Add region guard to application router. Find example code in example/src/app/app-routing.module.ts file.
const routes: Routes = [
  {
    path: '',
    canActivate: [ RegionGuard ],
    children: [
      /**
       * Wrap all routes with region guard
       * to redirect to region selector page
       * if region not exists
       */
      {
        path: '',
        canActivate: [ AuthGuard ],
        loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
      },
    ]
  }, {
    /**
     * Add region selector page
     * to select region if not exists
     */
    path: 'select-region',
    component: SelectRegionComponent
  }
];

  1. Setup multi-region support for iOS Platform

The following guide outlines the steps to configure an iOS application to support multiple regions.

First, adjust your Frontegg.plist file for multiple regions:

  • Remove the existing baseUrl and clientId keys.
  • Add a new boolean property, lateInit, and set it to true.

Example Frontegg.plist structure:

<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  <plist version="1.0">
  <dict>  
    <key>lateInit</key>
    <true/>
  </dict>
  </plist>

Secondly, add associated domains for each region:

Configure the associated domains for each region in your application's settings. This step is crucial for correct API routing and authentication. Follow the guide Configure iOS Associated Domain to add your iOS associated domain to your Frontegg application.

  1. Setup multi-region support for Android Platform

The following guide outlines the steps to configure an Android application to support multiple regions.

First, modify the Build.gradle file

  • remove buildConfigFields from your build.gradle file: legacy
android {
  //  remove this lines:
  //  buildConfigField "String", 'FRONTEGG_DOMAIN', "\"$fronteggDomain\""
  //  buildConfigField "String", 'FRONTEGG_CLIENT_ID', "\"$fronteggClientId\""
}

Secondly, add AssetLinks for each region:

For each region, configuring your Android AssetLinks. This is vital for proper API routing and authentication. Follow the steps for configuring Android AssetLinks to add your Android domains to your Frontegg application.

Lastly, add intent-filter in Manifest.xml:

The first domain will be placed automatically in the AndroidManifest.xml file. For each additional region, you will
need to add an intent-filter. Replace ${FRONTEGG_DOMAIN_2} with the second domain from the previous step.

NOTE: if you are using Custom Chrome Tab you have to use android:name com.frontegg.android.HostedAuthActivity instead of com.frontegg.android.EmbeddedAuthActivity

<application>
    <activity android:exported="true" android:name="com.frontegg.android.EmbeddedAuthActivity"
              tools:node="merge">
        <intent-filter android:autoVerify="true">
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="https" />
            <!-- DO NOT COMBINE THE FOLLOWING LINES INTO ONE LINE OR SPLIT TO MULTIPLE -->
            <data android:host="${FRONTEGG_DOMAIN_2}"
                  android:pathPrefix="/oauth/account/activate" />
            <data android:host="${FRONTEGG_DOMAIN_2}"
                  android:pathPrefix="/oauth/account/invitation/accept" />
            <data android:host="${FRONTEGG_DOMAIN_2}"
                  android:pathPrefix="/oauth/account/reset-password" />
            <data android:host="${FRONTEGG_DOMAIN_2}"
                  android:pathPrefix="/oauth/account/login/magic-link" />
        </intent-filter>
    </activity>

    <activity android:exported="true" android:name="com.frontegg.android.AuthenticationActivity"
              tools:node="merge">
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <!-- DONT NOT COMBINE THE FOLLOWING LINES INTO ONE LINE-->
                <data
                    android:host="${FRONTEGG_DOMAIN_2}"
                    android:pathPrefix="/oauth/account/redirect/android/${package_name}"
                    android:scheme="https" />
            </intent-filter>
            <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:host="${FRONTEGG_DOMAIN_2}"
                    android:scheme="${package_name}" />
            </intent-filter>
    </activity>
</application>

Multi-apps support

Prerequisites

The use of this feature requires minimum @frontegg/ionic@2.0.8


This guide outlines the steps to configure your application to support multiple applications.

Find example code in example/capacitor.config.ts file.

Add applicationId to your Frontegg configuration

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
/*...*/
plugins: {

    /*...*/

    FronteggNative: {
        baseUrl: 'https://{FRONTEGG_DOMAIN_HOST.com}',
        clientId: '{FRONTEGG_CLIENT_ID}',
        applicationId: '{FRONTEGG_APPLICATION_ID}',
    }
}
};

export default config;

Or add applicationId to the regions:


import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  /*...*/
  plugins: {

    /*...*/

    FronteggNative: {
      
      /** Remove baseUrl and clientId from here */
      // baseUrl: 'https://{FRONTEGG_DOMAIN_HOST.com}',
      // clientId: '{FRONTEGG_CLIENT_ID}',
      // applicationId: '{FRONTEGG_APPLICATION_ID}',
      
      regions: [ {
        key: 'REGION_1_KEY',
        baseUrl: 'https://region1.forntegg.com',
        clientId: 'REGION_1_CLIEND_ID', 
        applicationId: '{FRONTEGG_REGION_1_APPLICATION_ID}'
      }, {
        key: 'REGION_2_KEY',
        baseUrl: 'https://region2.forntegg.com',
        clientId: 'REGION_2_CLIEND_ID', 
        applicationId: '{FRONTEGG_REGION_2_APPLICATION_ID}',
      } ]
    }
  }
};

export default config;

Embedded webview vs hosted

Frontegg SDK supports two authentication methods:

  • Embedded Webview
  • Hosted Webview
    • iOS: ASWebAuthenticationSession
    • Android: By default, Frontegg SDK will use Embedded Webview.

Enable hosted webview in iOS platform

To use ASWebAuthenticationSession you have to set embeddedMode to NO in Frontegg.plist file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN">
<plist version="1.0">
    <dict>
        <key>lateInit</key>
        <true/>
        <!-- START -->
        <key>embeddedMode</key>
        <false/>
        <!-- END -->
    </dict>
</plist>

Enable hosted webview in Android platform

To use Custom Chrome Tab you have to set disable embedded activity by adding below code to
the application manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">
    <application>
        <!-- ... -->

        <activity android:name="com.frontegg.android.EmbeddedAuthActivity" tools:replace="android:enabled"
                  android:enabled="false"/>
        <activity android:name="com.frontegg.android.HostedAuthActivity" tools:replace="android:enabled"
                  android:enabled="true"/>

        <!-- ... -->
    </application>
</manifest>

Integrate Frontegg

Open the src/app/app.module.ts file and add the following line to the before @NgModule section:

import { FronteggService } from '@frontegg/ionic-capacitor';

@NgModule({
  // ...
  providers: [ {
    provide: 'Frontegg',
    useValue: new FronteggService(),
  } ]
  // ...
})

Protect application poutes

  1. Create AuthGuard file src/app/auth.guard.ts:
import { CanActivateFn } from '@angular/router';
   import { Inject, Injectable } from '@angular/core';
   import { FronteggService } from '@frontegg/ionic-capacitor';


   @Injectable({
     providedIn: 'root'
   })
   export class AuthGuard {

     constructor(@Inject('Frontegg') private fronteggService: FronteggService) {

       /**
        * Listens to $isAuthenticated changes
        * Reload the page to trigger canActivate function again
        */
       this.fronteggService.$isAuthenticated.subscribe(async () => {
         window.location.reload()
       });

      /**
        * Listens to application visibility changes
        * Reload the page to trigger canActivate
        * when application returns from login page without authentication
        */
       document.addEventListener('visibilitychange', () => {
         if (document.visibilityState === 'visible' && !this.fronteggService.getState().isAuthenticated) {
           window.location.reload()
         }
       });
     }

     /**
      * Wait for loader to finish
      * @private
      */
     private waitForLoader() {
       return new Promise((resolve) => {
         const unsubscribe = this.fronteggService.$isLoading
           .subscribe((isLoading) => {
             if (!isLoading) {
               resolve(true);
               unsubscribe();
             }
           });
       })
     }

     /**
      * Navigate to login page if user is not authenticated
      * @private
      */
     private async navigateToLoginIfNeeded(): Promise<boolean> {
       const { isAuthenticated } = this.fronteggService.getState();
       if (!isAuthenticated) {
         await this.fronteggService.login()
         return false /** prevent navigation */
       }
       return true /** activate navigation */
     }


     canActivate: CanActivateFn = () => {
       const { showLoader } = this.fronteggService.getState();

       if (!showLoader) {
         /**
          * if showLoader false
          * check if user is authenticated
          */
         return this.navigateToLoginIfNeeded()
       }

       /**
        * if showLoader true
        * wait for loader to finish and then
        * check if user is authenticated
        */
       return new Promise<boolean>(async (resolve) => {
         await this.waitForLoader()
         const activated = await this.navigateToLoginIfNeeded()
         resolve(activated)
       })
     }
   }

  1. Open the src/app-routing.module.ts file and add wrap the app routes with loadChildren and apply CanActivate guard:
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  {
    path: '',
    canActivate: [ AuthGuard ],
    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
  },
];

Get logged in user

Find full example under the sample repo files.

import { Inject } from '@angular/core';
import { FronteggService, FronteggState } from '@frontegg/ionic-capacitor';

@Component({
  /** .... */
})
export class MyPage implements OnInit {

  constructor(private ngZone: NgZone, @Inject('Frontegg') private fronteggService: FronteggService) {
  }

  user: FronteggState['user'] = null
  accessToken: string | null = null

  ngOnInit() {
    const { user, accessToken } = this.fronteggService.getState();
    this.user = user;
    this.user = accessToken;

    this.fronteggService.$user.subscribe((user) => {
      console.log('change user', user)
      this.ngZone.run(() => this.user = user)
    })
    this.fronteggService.$accessToken.subscribe((accessToken) => {
      console.log('change accessToken', accessToken)
      this.ngZone.run(() => this.accessToken = accessToken)
    })
  }
}

Switch user's tenant

Find full example under the sample repo files.

import { Inject } from '@angular/core';
import { FronteggService, FronteggState } from '@frontegg/ionic-capacitor';

@Component({
  /** .... */
})
export class MyPage implements OnInit {

  constructor(private ngZone: NgZone, @Inject('Frontegg') private fronteggService: FronteggService) {
  }

  user: FronteggState['user'] = null
  accessToken: string | null = null

  ngOnInit() {
    const { user } = this.fronteggService.getState();
    this.user = user;
    this.fronteggService.$user.subscribe((user) => {
      this.ngZone.run(() => this.user = user)
    })
  }


  switchTenant(tenantId: string) {
    this.fronteggService.switchTenant(tenantId)
  }
}