Code Monkey home page Code Monkey logo

react-native-msal-plugin's Introduction

react-native-msal-plugin

ChangeLog

Wrapper around microsoft-authentication-library-for-objc library and microsoft-authentication-library-for-android

Tested on React Native 0.57.1

Based on bjartebore repo

npm version

Build status

npm install react-native-msal-plugin

or

yarn add react-native-msal-plugin

Link the library

react-native link react-native-msal-plugin

IOS Setup

Requirements

Install the required Pod

Install microsoft-authentication-library-for-objc with cocoapods

Create a Podfile in the ios project and add the following

platform :ios, '10'

target 'msalExample' do

  # Pods for msalExample
  pod 'MSAL', '~> 0.2'
end

Open Terminal in the same directory as the Podfile and run pod install

Add Url Scheme

Open the info.plist and add a url scheme that contains the callback url.

Make sure to replace [REPLACE_WITH_YOUR_APPLICATION_ID] with your own application id

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleTypeRole</key>
    <string>Editor</string>
    <key>CFBundleURLName</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>msal[REPLACE_WITH_YOUR_APPLICATION_ID]</string>
    </array>
  </dict>
</array>

Handle the redirection of the browser, Open the AppDelegate.m file and import msal.h

#import <MSAL/MSAL.h>

Then add this method

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  {

    [MSALPublicClientApplication handleMSALResponse:url];
    return YES;
  }

@end

The msal library uses ASWebAuthenticationsession for authentication on ios12 so you will have to add a new keychain group. to find out more read the docs https://github.com/AzureAD/microsoft-authentication-library-for-objc

alt text

Android Setup

Add Browser tab activity to your AndroidManifest.xml make sure to replace [REPLACE_WITH_YOUR_APPLICATION_ID] with your own application id

 <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    android:windowSoftInputMode="adjustResize">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
  </activity>
  <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

  <!-- Browser tab activity -->
  <activity
    android:name="com.microsoft.identity.client.BrowserTabActivity">
    <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="msal[REPLACE_WITH_YOUR_APPLICATION_ID]"
            android:host="auth" />
    </intent-filter>
 </activity>

Usage

Common endpoint

import MsalPlugin from "react-native-msal-plugin";

const authority = "https://login.microsoftonline.com/common";

const clientId = "ad04905f-6060-4bb0-9372-958afdb68574";

const scopes = ["User.Read"];

const extraQueryParameters = {
  exampleParamOne: "exampleParamOneValue",
  exampleParamTwo: "exampleParamTwoValue"
};

const login_hint = "[email protected]";

const authClient = new MsalPlugin(authority, clientId);

const forceTokenRefresh = false;

let tokenResult = {};

// acquire token
try {
  tokenResult = await this.authClient.acquireTokenAsync(
    scopes,
    extraQueryParameters,
    login_hint,
    MsalUIBehavior.SELECT_ACCOUNT
  );
  console.log("Store the token", tokenResult);
} catch (error) {
  console.log(error);
}

// acquire token silent
try {
  const silentTokenresult = await this.authClient.acquireTokenSilentAsync(
    scopes,
    tokenResult.userInfo.userIdentifier,
    forceTokenRefresh
  );
  console.log("Store the new token", silentTokenresult);
} catch (error) {
  console.log(error);
}

// sign out
try {
  await this.authClient.tokenCacheDelete();
} catch (error) {
  console.log(error);
}

Azure B2C endpoint

import MsalPlugin from "react-native-msal-plugin";

const authority = "https://{domain}.b2clogin.com/tfp/{domain}.onmicrosoft.com";

const applicationId = "{applicationId}";

const policies = {
  signUpSignInPolicy: "B2C_1_signup-signin-policy",
  passwordResetPolicy: "B2C_1_Password-reset-policy"
};

const scopes = ["https://{domain}.onmicrosoft.com/{app id}/user_impersonation"];

const extraQueryParameters = {
  exampleParamOne: "exampleParamOneValue",
  exampleParamTwo: "exampleParamTwoValue"
};

const login_hint = "[email protected]";

const authClient = new MsalPlugin(authority, applicationId, policies);

const forceTokenRefresh = false;

let tokenResult = {};

// acquire Token
try {
  tokenResult = await this.msalPlugin.acquireTokenAsync(
    scopes,
    extraQueryParameters,
    login_hint,
    MsalUIBehavior.SELECT_ACCOUNT
  );
  console.log("Store the token", tokenResult);
} catch (error) {
  console.log(error);
}

// acquire Token Silent
try {
  const silentTokenresult = await this.msalPlugin.acquireTokenSilentAsync(
    scopes,
    tokenResult.userInfo.userIdentifier,
    forceTokenRefresh
  );

  console.log("Store the new token", silentTokenresult);
} catch (error) {
  console.log(error);
}

// sign out
try {
  await this.authClient.tokenCacheDelete();
} catch (error) {
  console.log(error);
}

react-native-msal-plugin's People

Contributors

josmithua avatar rmcfarlane82 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.