msal_auth는 네이티브 Microsoft 인증 라이브러리(MSAL)를 사용하여 크로스 플랫폼 앱에서 원활한 Microsoft 인증을 가능하게 하는 Flutter 플러그인입니다. Android, iOS, macOS를 지원하며 Microsoft 계정, Azure AD 및 개인 Microsoft 계정을 사용한 안전한 로그인을 제공합니다. 이 플러그인은 토큰 획득, 세션 관리, 계정 선택을 플랫폼 고유의 흐름을 통해 처리하여 일관되고 안전한 사용자 경험을 보장합니다. MSAL의 강력한 보안 기능(토큰 캐싱 및 갱신 메커니즘 등)과 직접 통합되어 있습니다. 개발자는 최소한의 부가 코드로 인증 워크플로우를 쉽게 구현할 수 있습니다.
사용 사례
기업 앱에서 Microsoft 계정 로그인 통합
내부 도구에 대한 Azure AD 인증 활성화
생산성 앱에서 다중 계정 시나리오 지원
Microsoft Graph API에 대한 액세스 보호
Microsoft 서비스 간 단일 로그인 구현
주요 기능
모든 지원되는 플랫폼에서의 네이티브 MSAL 통합
보안 토큰 캐싱 및 새로 고침
다양한 계정 유형(업무, 학교, 개인) 지원
내장된 계정 선택 UI
API 호출을 위한 자동 토큰 획득
다중 플랫폼 일관성
적합한 대상
기업 모바일 애플리케이션
내부 비즈니스 도구
Azure AD 통합이 필요한 앱
Microsoft ID 생태계를 사용하는 개발자
보안 및 네이티브 인증이 필요한 프로젝트
고려 사항
Azure Portal에서 앱 등록을 구성해야 합니다
Microsoft ID 공급자에 한정
iOS 및 안드로이드용 플랫폼별 설정 필요
일부 범위에 대해 추가 권한이 필요할 수 있습니다
원본 MSAL SDK에 의존하며 버전 제약 조건이 있을 수 있습니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
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.
Platform Support
Android
SDK 21+
CocoaPods
iOS
macOS
16+
11+
Swift Package Manager (SPM)
iOS
macOS
16+
11+
Note The minimum iOS and macOS versions may differ between CocoaPods and Swift Package Manager (SPM), as these requirements are determined by the MSAL native Swift library and are not requirements of this Flutter plugin.
Features 🚀
Option to set one of the following broker (Authentication middleware):
MS Authenticator App
Browser
In-App WebView
Single & Multiple account mode support
Supports different identity providers (authority):
AAD (Microsoft Entra ID)
B2C (Business to customer)
Acquire token interactively & silently
Option to set login hint & prompt type in acquiring token
Complete authentication result with account information
Check shared device mode status
To implement MSAL in Flutter, you first need to set up an app in the Azure Portal and configure certain platform-specific settings.
➡ Follow the step-by-step guide below ⬇️
Create an App in Azure Portal
First, sign up and create an app on the Azure Portal.
To create the app, search for App registrations, click on it, and navigate to New registration.
Fill in the Name field, select the Supported account types, and register the app.
Once the application is created, you will see the Application (client) ID and Directory (tenant) ID. These values are required in your Dart code.
Next, you need to add platform-specific configurations for Android and iOS/macOS in the Azure Portal. To do this, navigate to Manage > Authentication > Add platform.
Android Setup - Azure portal
For Android, You need to provide package name and signature hash. To generate a signature hash in Flutter, use the below command from your project's android folder:
Ensure you have upload-keystore.jks file placed inside android/app folder. Follow the Flutter's documentation Build and release an Android app to create a release setup.
Register both signature hash in Azure's Android Platform configurations.
iOS/macOS Setup - Azure portal
You need to provide only Bundle ID of your iOS/macOS app. 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 offers full customization, allowing you to provide a configuration JSON file to be used during application creation & authentication.
Follow the steps below to complete the Android configuration.
Obtain the redirect_uri from the Azure Portal. This URI is required in the Android configuration when creating the public client application using Dart code.
The redirect URI typically follows this format for Android:
There is no need to include client_id and redirect_uri in this JSON, as they will be added programmatically by the Dart code when the public client application is created.
Setup Account Mode
To support single account mode in Android, declare the following in a configuration file:
"account_mode":"SINGLE"
For multiple mode:
"account_mode":"MULTIPLE"
Setup Authority
Follow the Android MSAL Authority documentation to configure it in various ways, depending on your application's requirements.
If you use Browser or Authenticator app for authentication, you must specify BrowserTabActivity within the <application> tag in your AndroidManifest.xml file.
Add a new keychain group com.microsoft.adalcache to your project capabilities.
Without this configuration, your app will not be able to open the Microsoft Authenticator app if specified in the broker. Additionally, the logout method will throw an exception because it will not be able to find the account in the cache.
Info.plist Modification
Add your application's redirect URI scheme to your Info.plist file:
Add LSApplicationQueriesSchemes to use the Microsoft Authenticator app as a broker for authentication. Not required when Safari Browser or WebView is used as a broker.
If you use Broker.msAuthenticator after declaring the above schemes but the Authenticator app is not installed on the iPhone, the authentication will fall back to using Safari Browser.
Handle callback from MSAL
Applicable only when using version 3.3.0 or earlier. Starting from version 3.4.0, callback handling is managed internally by the plugin, so no additional setup is required on the app side.
Your app needs to handle login success callback if app uses Microsoft Authenticator app OR Safari Browser for authentication. WebView does not require it.
Your app needs to handle the login success callback if it uses the Microsoft Authenticator app or Safari Browser for authentication. WebView does not require this callback.
Refer to the AppDelegate.swift file in the example app for more clarity.
If you adopted UISceneDelegate on iOS 13+, MSAL callback needs to be placed into the appropriate delegate method of UISceneDelegate instead of AppDelegate.
Add a new keychain group com.microsoft.identity.universalstorage to your project capabilities.
If you encounter the NSPOSIXErrorDomain error while using acquireToken in a macOS debug app, it indicates a missing network entitlement required for the app in debug mode. To fix this issue, add the following configuration to the DebugProfile.entitlements file:
This section covers how to write the Dart code to set up an MSAL application in Flutter and authenticate the user.
Create Public Client Application
Create the public client app based on your account mode. usually, it is a single account mode.
final msalAuth = awaitSingleAccountPca.create(
clientId: '<MICROSOFT_CLIENT_ID>',
androidConfig: AndroidConfig(
configFilePath: 'assets/msal_config.json',
redirectUri: '<Android Redirect URI>',
),
appleConfig: AppleConfig(
authority: '<Optional, but must be provided for b2c>',
// Change authority type to 'b2c' for business to customer flow.
authorityType: AuthorityType.aad,
// Change broker if you need. Applicable to both iOS and macOS.// Setting it to 'Broker.webView' / 'Broker.safariBrowser' disables the// Microsoft SSO extension and uses the web view instead — useful on// managed Macs where the broker cannot resolve the app's Team ID.
broker: Broker.msAuthenticator,
// Optional. Explicit redirect URI (e.g. 'msauth.<team-id>.<bundle-id>://auth').// When set, MSAL uses it directly instead of deriving the default redirect// and resolving the Apple Team ID via keychain — which fails on some managed// devices with "teamId is missing". Omit to keep the default behavior.
redirectUri: '<Optional Apple Redirect URI>',
),
);
By default, login will be attempted to AAD (Microsoft Entra ID). if you want to use B2C, set the authorityType to AuthorityType.b2c.
On iOS, if the broker is set to AuthMiddleware.msAuthenticator and the Authenticator app is not installed on the device, it will fall back to using Safari Browser for authentication.
Acquire Token (Login to Microsoft Account)
This method opens the Microsoft login page in the specified broker and provides the authentication result upon a successful login. The result includes the accessToken.
final authResult = await publicClientApplication.acquireToken(
scopes: <String>[
'https://graph.microsoft.com/user.read',
// Add other scopes here if required.
],
// UI option for authentication, default is [Prompt.whenRequired]
prompt: Prompt.login,
// Provide 'loginHint' if you have.
loginHint: '<Email Id / Username / Unique Identifier>',
// Optional: Custom authority URL for B2C or different// tenant scenarios
authority: '<Authority URL>',
);
log('Auth result: ${authResult.toJson()}');
Acquire Token by Silent Call 🔇
Typically, this method should be called when the accessToken expires. It uses the refresh token from the cached account, performs authentication in the background, and returns the authentication result, similar to the acquireToken() method.
The app can store the expiresOn value of the AuthenticationResult in the preferences and check the following condition before using the accessToken:
if (expiresOn.isBefore(DateTime.now())) {
final authResult = await publicClientApplication.acquireTokenSilent(
scopes: <String>[], // List of string same as "acquireToken()"
identifier: 'Account Identifier, required for multiple account mode',
// Authority URL where you want to refresh tokens using// a different policy than the original authentication.// Required for B2C scenarios.
authority: '<Authority URL>',
);
log('Auth result: ${authResult.toJson()}');
// Store new value of "expiresOn" or entire "authResult" object.
}
This method can throw an MsalUiRequiredException if the refresh token has expired or does not exist. In this case, the acquireToken() method should typically be called to prompt the user for interactive authentication and obtain a new access token.
try {
acquireTokenSilent();
} onMsalExceptioncatch (e) {
if (e isMsalUiRequiredException) {
awaitacquireToken();
// Handle auth result
}
}
All other types of exceptions are optional to handle, depending on your use case.
Shared Device Mode Status
Indicates whether the device is configured by the administrator in Shared Device Mode. When enabled, the device is intended for use by multiple employees. Users can sign in to access work resources, and once they sign out after completing their shift or task, the device is immediately ready for the next employee.
All MSAL exceptions thrown by the Android and iOS/macOS platforms can be handled on the Dart side. You can manage them according to your use case, such as by logging the errors, displaying user-friendly messages, retrying the operation, or triggering specific app behaviors based on the type of exception.