Skip to content

React Native library implementing Azure AD OAuth2 API

License

Notifications You must be signed in to change notification settings

kiskolabs/react-native-azure-auth

 
 

Repository files navigation

react-native-azure-auth

CircleCI

React Native library implementing Azure AD OAuth2 API

The library uses the latest V2.0 version of the Azure AD endponts and provides token cache functionality. react-native-azure-auth implements authentication flow using fetch API and native components. The OpenID connect and autorization_code grant are implemented.

Installation

Install react-native-azure-auth using npm

npm install react-native-azure-auth --save

Or via yarn (recommended)

yarn add react-native-azure-auth

then you need to link the native module in react-native-azure-auth

react-native link react-native-azure-auth

From version 1.1 the library uses extracted version of AsyncStorage, so you should link it too:

react-native link @react-native-community/async-storage

App Registration

First, you will need to register your application with Microsoft Azure Portal. This will give you an Application ID for your application, as well as enable it to receive tokens.

  1. Sign in to the Microsoft Azure Portal.
  2. First you need to find the App Registration Service. You could just type in the service name in the search bar on the middle top of the window and select it or do like following:
    1. Click on All services in the left panel
    2. Then select from the shown in bold categories the Identity
    3. Click on the star sign near the App registration service name to add it to favorites
    4. Now you can easily access the service using the left portal panel
  3. After selecting App registration service click New registration
  4. Enter a friendly name for the application
  5. Select account type that should be supported by your app. The default choice "Accounts in any organizational directory and personal Microsoft accounts" is the widest one.
  6. Now you need to add Redirect URI
    1. Select Public client (mobile & desktop) from dropdown
    2. Type in the URI. See the URI format in the section below.
  7. Click Register to create the app registration record.
  8. Find the Application (client) ID value in Overview section, copy and save the value in a safe location.
  9. You don't need to set API Permissions. It is meant for admin consent only.
  10. Now select Authentication from the left menu
  11. Select checkboxes Access tockens and ID tokens in the Implicit grant section.
  12. Click Save button above to save changes.

Callback URL(s)

Callback URLs are the URIs that Azure AD invokes after the authentication process. Azure routes your application back to this URI and appends additional parameters to it, including a token. Since callback URLs can be manipulated, you will need to add your application's URL to your apps's registered Redirect-URIs. This will enable Azure to recognize these URLs as valid. If omitted, authentication will not be successful.

iOS - default redirect URI structure
{YOUR_BUNDLE_IDENTIFIER}://${YOUR_BUNDLE_IDENTIFIER}/ios/callback
Android - default redirect URI structure
{YOUR_APP_PACKAGE_NAME}://{YOUR_APP_PACKAGE_NAME}/android/callback

Note: Be aware of allowed characters for the scheme part of URI. According to RFC 2396 (Section 3.1):

scheme = alpha *( alpha | digit | "+" | "-" | "." )

As you can see, allowed in identifier and package name underscore (_) character is not allowed in the URI scheme!

App Configuration

Android config

In the file android/app/src/main/AndroidManifest.xml you must make sure the MainActivity of the app has a launchMode value of singleTask and that it has the following 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:pathPrefix="/${applicationId}/android/callback"
        android:scheme="${applicationId}" />
</intent-filter>

The applicationId here should be the same as your app package name, and not the ID from MS App Portal.

You would have the following MainActivity configuration:

<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:launchMode="singleTask"
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>
<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:pathPrefix="/${applicationId}/android/callback"
        android:scheme="${applicationId}" />
</intent-filter>
</activity>

For more info please read react native docs

iOS config

Inside the ios folder find the file AppDelegate.[swift|m] add the following to it

#import <React/RCTLinkingManager.h>

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}

Inside the ios folder open the Info.plist and locate the value for CFBundleIdentifier, e.g.

<key>CFBundleIdentifier</key>
<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>

The value org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) is the default for apps created with React Native CLI, you may have a different value.

It is advisable to replace it with your own meaningfull ID in reverse DNS format. e.g. com.my-domain.native-app

and then register a URL type entry using the value of CFBundleIdentifier as the value of CFBundleURLSchemes

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>None</string>
        <key>CFBundleURLName</key>
        <string>AzureAuth</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
        </array>
    </dict>
</array>

Attention: The <string> value for CFBundleURLSchemes key should be the literal value of the Bundle Identifier with no $ variables, for example: com.my-domain.native-app

For more info please read react native docs

Usage

import AzureAuth from 'react-native-azure-auth';

const azureAuth = new AzureAuth({
    clientId: 'YOUR_CLIENT_ID'
});

Authorization with user interaction

    try {
      let tokens = await azureAuth.webAuth.authorize({scope: 'openid profile User.Read Mail.Read' })
      this.setState({ accessToken: tokens.accessToken });
      let info = await azureAuth.auth.msGraphRequest({token: tokens.accessToken, path: '/me'})
      this.setState({ user: info.displayName, userId: tokens.userId })
    } catch (error) {
      console.log(error)
    }

Silent authorization

    try {
        // Try to get cached token or refresh an expired ones
        let tokens = await azureAuth.auth.acquireTokenSilent({scope: 'Mail.Read', userId: this.state.userId})
        if (!tokens) {
            // No cached tokens or the requested scope defines new not yet consented permissions
            // Open a window for user interaction
            tokens = await azureAuth.webAuth.authorize({scope: 'Mail.Read'})
        }
        let mails = await azureAuth.auth.msGraphRequest({token: tokens.accessToken, path: '/me/mailFolders/Inbox/messages'})
    } catch (error) {
      console.log(error)
    }

Usage example

You can consult a tiny sample project react-native-azure-auth-sample for usage example

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker.

Author

Vladimir Murin

Credits

This project was originally inspired by https://github.com/auth0/react-native-auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

React Native library implementing Azure AD OAuth2 API

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 86.6%
  • Objective-C 6.8%
  • Java 5.8%
  • Ruby 0.8%