LogoLogo
English
English
  • Introduction
  • Integration
    • HTML5/JS
    • ReactJs
    • React Native
  • JWT Validation
Powered by GitBook
On this page
  • Acronyms and Terms
  • Summary
  • Integrate
Export as PDF
  1. Integration

React Native

This document describes how to integrate Galaxy ID for React Native.

Software Name: Galaxy ID

Software Version: 0.1

Acronyms and Terms

No.

Words

Descriptions

1

GID

Galaxy ID

2

SSO

Single Sign-On

4

Client

An application that integrates for GID

Summary

Galaxy ID is an SSO system. It provides endpoints that enable clients to authenticate and authorize in many places.

Integrate

Install

yarn add @react-keycloak/native
yarn add react-native-inappbrowser-reborn

or

npm install @react-keycloak/native
npm install react-native-inappbrowser-reborn --save

Setup Deep links (iOS)

To navigate back from webview to your app, you have to configure deep linking.

And in AppDelegate.m, add these lines:

#import <React/RCTLinkingManager.h>

......
......

// Deep linking
- (BOOL)application:(UIApplication *)application
   openURL:(NSURL *)url
   options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  return [RCTLinkingManager application:application openURL:url options:options];
}

N.B.: replace myapp with the name of your app

Setup Deep links (Android)

To configure the external linking in Android, you can create a new intent in the manifest.

The easiest way to do this is with the uri-scheme package:

npx uri-scheme add myapp --android

If you want to add it manually, open up YourApp/android/app/src/main/AndroidManifest.xml, and make the following adjustments:

  1. Add the new intent-filter inside the MainActivity entry with a VIEW type action:

<activity
    android:name=".MainActivity"
    android:launchMode="singleTask">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </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:scheme="myapp" />
    </intent-filter>
</activity>

N.B.: replace myapp with the name of your app

Setup RNKeycloak instance

Create a keycloak.ts file in the src folder of your project (where App.ts is located) with the following content:

import { RNKeycloak } from '@react-keycloak/native';

// Setup Keycloak instance as needed
// Pass initialization options as required
const keycloak = new RNKeycloak(<path to keycloak.json>);

export default keycloak;

keycloak.json (will be provided by admin):

{
  "realm": "demo",
  "auth-server-url": "https://gid-stg.demoapp.info/",
  "ssl-required": "external",
  "resource": "gid-client",
  "public-client": true,
  "confidential-port": 0
}

Setup ReactNativeKeycloakProvider

Wrap your App inside KeycloakProvider and pass the keycloak instance as prop

import { ReactNativeKeycloakProvider } from '@react-keycloak/native';

import keycloak from './keycloak';

// Wrap everything inside ReactNativeKeycloakProvider
const App = () => (
  <ReactNativeKeycloakProvider
    authClient={keycloak}
    initOptions={{
      redirectUri: 'myapp://Homepage',
      // if you need to customize "react-native-inappbrowser-reborn" View you can use the following attribute
      inAppBrowserOptions: {
        // For iOS check: https://github.com/proyecto26/react-native-inappbrowser#ios-options
        // For Android check: https://github.com/proyecto26/react-native-inappbrowser#android-options
      },
    }}
  >
    <Login />
  </ReactNativeKeycloakProvider>
);

export default App;

N.B. If you're using other providers (such as react-redux) it is recommended to place them inside ReactNativeKeycloakProvider.

ReactNativeKeycloakProvider automatically invokes keycloak.init() method when needed and supports the following props:

{
  onLoad: 'check-sso',
}
  • LoadingComponent, a component to be displayed while keycloak is being initialized, if not provided child components will be rendered immediately. Defaults to null

  • isLoadingCheck, an optional loading check function to customize LoadingComponent display condition. Return true to display LoadingComponent, false to hide it. Can be implemented as follows:

(keycloak) => !keycloak.authenticated;
  • onEvent, a handler function that receives events launched by keycloak, defaults to null. It can be implemented as follows:

(event, error) => {
  console.log('onKeycloakEvent', event, error);
};

Published events are:

  • onReady

  • onInitError

  • onAuthSuccess

  • onAuthError

  • onAuthRefreshSuccess

  • onAuthRefreshError

  • onTokenExpired

  • onAuthLogout

  • onTokens, a handler function that receives keycloak tokens as an object every time they change, defaults to null. Keycloak tokens are returned as follows:

{
  "idToken": string,
  "refreshToken": string,
  "token": string
}

Hook Usage

When a component requires access to Keycloak, you can use the useKeycloak Hook.

import { useKeycloak } from '@react-keycloak/native';

export default () => {
  // Using array destructuring
  const [keycloak, initialized] = useKeycloak();
  // or Object destructuring
  const { keycloak, initialized } = useKeycloak();

  // Here you can access all of keycloak methods and variables.
  // See https://www.keycloak.org/docs/latest/securing_apps/index.html#javascript-adapter-reference

  return (
    <View>
      <Text>
        {`User is ${!keycloak.authenticated ? 'NOT ' : ''}authenticated`}
      </Text>

      {!!keycloak.authenticated && (
        <Button onPress={() => keycloak.logout()} title="Logout" />
      )}
    </View>
  );
};

External Usage (Advanced)

If you need to access keycloak instance from non-React files (such as sagas, utils, providers ...), you can import the instance directly from the keycloak.ts file.

The instance will be initialized by react-keycloak but you'll need to be careful when using the instance and avoid setting/overriding any props, you can however freely access the exposed methods (such as refreshToken, login, etc...).

Get user information

  • With the access token, we can get user info with tokenParsed property: keycloak.tokenParsed (recommend).

  • With Rest API:

URL: <host>/realms/<realmName>/protocol/openid-connect/userinfo

Method: GET

Header: Authorization: Bearer <access token> (keycloak)

Example request:

curl --location --request GET 'https://gid-stg.demoapp.info/realms/demo/protocol/openid-connect/userinfo' \
--header 'Authorization: Bearer <access token>'

Example response:

{
    "sub": "3d83889f-297f-4283-8602-73c6b60630be",
    "email_verified": false,
    "name": "Duy Doan",
    "preferred_username": "+84391234567",
    "given_name": "Duy",
    "family_name": "Doan",
    "email": "duydoan@gmail.com"
}
PreviousReactJsNextJWT Validation

Last updated 2 years ago

Set launchMode of MainActivity to singleTask in order to receive intent on existing MainActivity (this is the default on all new projects, so you may not need to actually change anything!). It is useful if you want to perform navigation using a deep link you have been registered -

initConfig, contains the object to be passed to keycloak.init() method, by default the following is used, for more options see .

details
Keycloak docs
react-keycloak/react-native-keycloak: React Native components for Keycloak (github.com)