msal_auth 2.1.1 msal_auth: ^2.1.1 copied to clipboard
A comprehensive Flutter plugin for managing Microsoft authentication using the native Microsoft Authentication Library (MSAL).
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 🚀 #
- Option to set one of the following Middleware:
- MS Authenticator App
- Browser
- In-App WebView
- Supports authentication against Entra ID (formerly Azure Active Directory)/Microsoft Account tenants as well as Azure Active Directory (AD) B2C tenants
- Get auth token silently
- Get auth token interactive
- Logout
- Auth Token information
- Microsoft User information
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 #
-
First of all, You need to Sign up and create an app on Azure Portal.
-
To create the app, Search for
App registrations
, click on it and go toNew registration
. -
Fill the
Name
and selectSupported account types
and register it. -
Your application is created now and you should see the
Application (client) ID
andDirectory (tenant) ID
. Those values are required in Dart code. -
Now You need to add
Android
andiOS
platform specific configuration in Azure portal. to do that, go toManage > Authentication > Add platform
.
Android Setup - Azure portal #
- For Android, You need to provide
package name
and releasesignature hash
.-
To generate a signature hash in Flutter, use the below command:
keytool -exportcert -alias androidreleasekey -keystore app/upload-keystore.jks | openssl sha1 -binary | openssl base64
-
Make sure you have release
keystore
file placed inside/app
folder. -
Only one signature hash is required because it maps with
AndroidManifest.xml
.
-
iOS Setup - Azure portal #
-
For iOS, You need to provide only
Bundle ID
.Redirect URI
will be generated automatically by system.
That's it for the Azure portal configuration.
Please follow the platform configuration ⬇️ before jump to the Dart
code.
Android Configuration #
- This plugin supports fully customization as you can give configuration
JSON
that will be used in authentication. - Follow the below steps to complete Android configuration.
Creating MSAL Config JSON #
-
Create one
msal_config.json
in/assets
folder and copy the JSON from Microsoft default configuration file. -
Now add the
redirect_uri
in the above created JSON as below:"redirect_uri": "msauth://<APP_PACKAGE_NAME>/<BASE64_ENCODED_PACKAGE_SIGNATURE>",
-
You can directly copy the
Redirect URI
from Azure portal.
Setup authentication middleware (Optional) #
-
Set broker authentication (authenticate user by Microsoft Authenticator App)
"broker_redirect_uri_registered": true
- If Authenticator app is not installed on a device,
authorization_user_agent
will be used as a auth middleware.
- If Authenticator app is not installed on a device,
-
Authenticate using Browser
"broker_redirect_uri_registered": false, "authorization_user_agent": "BROWSER"
-
Authenticate using WebView
"broker_redirect_uri_registered": false, "authorization_user_agent": "WEBVIEW"
-
To learn more about configuring JSON, follow Android MSAL configuration.
Add Activity in AndroidManifest.xml #
-
Add another activity inside
<application>
tag. -
This is only needed if you want to use
Browser
as a auth middleware.<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:host="com.example.msal_auth_example" android:path="/<BASE64_ENCODED_PACKAGE_SIGNATURE>" android:scheme="msauth" /> </intent-filter> </activity>
-
Replace
host
by your app's package name andpath
by thebase64
signature hash that is generated above.
iOS Configuration #
- Add a new keychain group
com.microsoft.adalcache
to your project capabilities.
Info.plist
Modification #
-
Add your application's redirect URI scheme to your
Info.plist
file:<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>msauth.$(PRODUCT_BUNDLE_IDENTIFIER)</string> </array> </dict> </array>
-
Add
LSApplicationQueriesSchemes
to allow making call to Microsoft Authenticator app if installed.<key>LSApplicationQueriesSchemes</key> <array> <string>msauthv2</string> <string>msauthv3</string> </array>
Handle callback
from MSAL #
- Your app needs to handle login success callback if app uses Microsoft Authenticator app OR
Safari Browser
as a authentication middleware.WebView
does not require it.
AppDelegate.swift
import MSAL
override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String)
}
-
See
AppDelegate.swift
for more clarity. -
If you adopted
UISceneDelegate
on iOS 13+, MSAL callback needs to be placed into the appropriate delegate method ofUISceneDelegate
instead ofAppDelegate
.
SceneDelegate.swift
import MSAL
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let urlContext = URLContexts.first else {
return
}
let url = urlContext.url
let sourceApp = urlContext.options.sourceApplication
MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: sourceApp)
}
- See more info on iOS MSAL configuration.
Code Implementation 👨💻 #
- This section contains writing
Dart
code to setup aMSAL
application inFlutter
and get auth token.
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,
),
);
-
To modify value of
authority
iniOS
, follow Configure iOS authority. -
in
iOS
, if middleware isAuthMiddleware.msAuthenticator
andAuthenticator
app is not installed on a device, It will useSafari Browser
for authentication. -
By default login will be attempted against an Entra ID (formerly Azure Active Directory) tenant which also supports Microsoft Account logins. To login to an Azure AD B2C tenant instead, set the
tenantType
value toTenantType.azureADB2C
.
Get Auth Token (Login to Microsoft account) #
- This code is responsible to open Microsoft login page in given middleware and provide token on successful login.
final user = await msalAuth.acquireToken();
log('User data: ${user?.toJson()}');
Get Auth Token by Silent Call 🔇 (When expired) #
- Before using auth token, You must check for the token expiry time. You can do it by accessing
tokenExpiresOn
property fromMsalUser
object.
if (msalUser.tokenExpiresOn <= DateTime.now().millisecondsSinceEpoch) {
final user = await msalAuth.acquireTokenSilent();
log('User data: ${user?.toJson()}');
}
- This will generate a new token without opening Microsoft login page. However, this method can open the login page if
MSALUiRequiredException
occurs. - You can learn more about MSAL exceptions.
Follow example
code for more details on implementation.