nayanAubie / msal_auth

A new Flutter plugin for Azure AD authentication.
MIT License
5 stars 8 forks source link

MSAL Auth

Microsoft Authentication πŸ” Library for Flutter.

msal_auth plugin provides Microsoft authentication in Android and iOS devices using native MSAL library. This is very straightforward and easy to use.

Features πŸš€


To implement MSAL in Flutter, You need to setup an app in Azure Portal and required some of the platform specific configurations.

➑ Follow the step-by-step guide below ⬇️

Create an App in Azure Portal

Android Setup - Azure portal

iOS Setup - Azure portal

That's it for the Azure portal configuration.


Please follow the platform configuration ⬇️ before jump to the Dart code.

Android Configuration

Creating MSAL Config JSON

Setup authentication middleware (Optional)

Add Activity in AndroidManifest.xml

iOS Configuration

Info.plist Modification

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
        <string>msauth.$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    </array>
  </dict>
</array>

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>msauthv2</string>
  <string>msauthv3</string>
</array>

Code Implementation πŸ‘¨β€πŸ’»

Setup MSAL Application

final msalAuth = await MsalAuth.createPublicClientApplication(
  clientId: '<MICROSOFT_CLIENT_ID>',
  scopes: <String>[
    'https://graph.microsoft.com/user.read',
    // Add other scopes here if required.
  ],
  loginHint: '<EMAIL ID (Optional)>'
  androidConfig: AndroidConfig(
    configFilePath: 'assets/msal_config.json',
    tenantId: '<MICROSOFT_TENANT_ID (Optional)>',
  ),
  iosConfig: IosConfig(
    authority: 'https://login.microsoftonline.com/<MICROSOFT_TENANT_ID>/oauth2/v2.0/authorize',
    // Change auth middleware if you need.
    authMiddleware: AuthMiddleware.msAuthenticator,
    tenantType: TenantType.entraIDAndMicrosoftAccount,
  ),
);

Get Auth Token (Login to Microsoft account)

final user = await msalAuth.acquireToken();
log('User data: ${user?.toJson()}');

Get Auth Token by Silent Call πŸ”‡ (When expired)

if (msalUser.tokenExpiresOn <= DateTime.now().millisecondsSinceEpoch) {
  final user = await msalAuth.acquireTokenSilent();
  log('User data: ${user?.toJson()}');
}

Follow example code for more details on implementation.