### Swift Example for MSAL Initialization Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/MANIFEST.md Example of initializing MSAL's PublicClientApplication in Swift for iOS/macOS, demonstrating configuration parameters. ```swift let authority = URL(string: "https://login.microsoftonline.com/YOUR_TENANT_ID")! let msalConfig = MSALConfiguration(clientId: "YOUR_CLIENT_ID", authority: authority) let pca = try MSALPublicClientApplication(configuration: msalConfig) ``` -------------------------------- ### Kotlin Example for MSAL Initialization Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/MANIFEST.md Example of initializing MSAL's PublicClientApplication in Kotlin for Android, showing configuration details. ```kotlin val authority = "https://login.microsoftonline.com/YOUR_TENANT_ID" val clientId = "YOUR_CLIENT_ID" val pca = PublicClientApplication.create(applicationContext, clientId, authority) ``` -------------------------------- ### AndroidConfig Usage Example Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/android-config.md Demonstrates how to create an AndroidConfig instance and use it to initialize a SingleAccountPca for Android. ```dart final androidConfig = AndroidConfig( configFilePath: 'assets/msal_config.json', redirectUri: 'msauth://com.example.app/signature_hash', ); final pca = await SingleAccountPca.create( clientId: 'your-client-id', androidConfig: androidConfig, ); ``` -------------------------------- ### Create and Use CustomWebViewConfig Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/custom-web-view-config.md Example of creating a CustomWebViewConfig instance and using it to acquire a token with custom WebView settings. ```dart final customWebViewConfig = CustomWebViewConfig( title: 'Sign In to Your Account', cancelButtonTitle: 'Close', showNavigationControls: true, ); final authResult = await publicClientApplication.acquireToken( scopes: ['https://graph.microsoft.com/user.read'], customWebViewConfig: customWebViewConfig, ); ``` -------------------------------- ### Run App in Debug Mode Source: https://github.com/nayanaubie/msal_auth/blob/main/example/README.md Execute this command from the example directory to run the app in debug mode. It loads environment variables from the .env file. ```sh flutter run --dart-define-from-file=.env ``` -------------------------------- ### AndroidConfig Usage Example Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/android-config.md Demonstrates how to create an AndroidConfig instance and use it when initializing a SingleAccountPca for MSAL authentication on Android. ```APIDOC ## Usage Example ```dart final androidConfig = AndroidConfig( configFilePath: 'assets/msal_config.json', redirectUri: 'msauth://com.example.app/signature_hash', ); final pca = await SingleAccountPca.create( clientId: 'your-client-id', androidConfig: androidConfig, ); ``` ``` -------------------------------- ### Run App in Release Mode Source: https://github.com/nayanaubie/msal_auth/blob/main/example/README.md Execute this command from the example directory to run the app in release mode. It loads environment variables from the .env file and enables release optimizations. ```sh flutter run --release --dart-define-from-file=.env ``` -------------------------------- ### Create PCA with B2C Authentication Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/apple-config.md Example of creating a SingleAccountPca for B2C authentication, requiring a specific authority URL. ```dart final appleConfig = AppleConfig( authority: 'https://your-tenant.b2clogin.com/your-tenant.onmicrosoft.com/b2c_1_signin', authorityType: AuthorityType.b2c, broker: Broker.msAuthenticator, ); final pca = await SingleAccountPca.create( clientId: 'your-client-id', appleConfig: appleConfig, ); ``` -------------------------------- ### Authorization Header Usage Example Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/authentication-result.md Demonstrates how to obtain the authorization header from an AuthenticationResult and use it in an HTTP GET request to Microsoft Graph. ```dart final header = authResult.authorizationHeader; // header = "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." // Use in HTTP request final response = await http.get( Uri.parse('https://graph.microsoft.com/v1.0/me'), headers: {'Authorization': header}, ); ``` -------------------------------- ### Create PCA with WebView Authentication Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/apple-config.md Example of creating a SingleAccountPca using WebView for authentication on iOS. ```dart final appleConfig = AppleConfig( authorityType: AuthorityType.aad, broker: Broker.webView, ); final pca = await SingleAccountPca.create( clientId: 'your-client-id', appleConfig: appleConfig, ); ``` -------------------------------- ### Environment Configuration (.env file) Source: https://github.com/nayanaubie/msal_auth/blob/main/example/README.md Create a .env file in the example folder to store Azure app credentials like client ID and authority URL. Use a B2C authority URL if your app uses the b2c flow. ```ini AAD_CLIENT_ID=your-apps-client-id AAD_APPLE_AUTHORITY=https://login.microsoftonline.com/common ``` -------------------------------- ### Generate Android Release Signature Hash Source: https://github.com/nayanaubie/msal_auth/blob/main/example/README.md Run this command from the example's android folder to generate the release signature hash. Ensure you have generated the keystore first. This is for release mode testing. ```Bash keytool -exportcert -alias upload -keystore app/upload-keystore.jks | openssl sha1 -binary | openssl base64 ``` -------------------------------- ### Authority Configuration Example Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Example of an authority configuration object within the MSAL JSON. It specifies the authority type and audience, including the tenant ID. ```json { "type": "AAD", "audience": { "type": "AzureADandPersonalMicrosoftAccount", "tenant_id": "common" } } ``` -------------------------------- ### Create PCA with AAD Authentication (Default) Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/apple-config.md Example of creating a SingleAccountPca using default AAD authority and MS Authenticator broker. ```dart final appleConfig = AppleConfig( authorityType: AuthorityType.aad, broker: Broker.msAuthenticator, ); final pca = await SingleAccountPca.create( clientId: 'your-client-id', appleConfig: appleConfig, ); ``` -------------------------------- ### Configure Broker Authentication (Authenticator App) Source: https://github.com/nayanaubie/msal_auth/blob/main/README.md Set broker authentication to use Microsoft Authenticator App. If the app is not installed, it falls back to the authorization_user_agent configuration. ```JSON "broker_redirect_uri_registered": true ``` -------------------------------- ### Generate Android Debug Signature Hash Source: https://github.com/nayanaubie/msal_auth/blob/main/example/README.md Run this command from the example's android folder to generate the debug signature hash required for setting up the Android redirect URL. This is for debug mode testing. ```Bash keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -storepass android -keypass android | openssl sha1 -binary | openssl base64 ``` -------------------------------- ### MSAL Configuration File Format (JSON) Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/android-config.md Example of the JSON configuration file format required for MSAL Android settings. It specifies account mode, broker settings, and authorities. Client ID and redirect URI are added programmatically. ```json { "account_mode": "SINGLE", "broker_redirect_uri_registered": true, "authorization_user_agent": "DEFAULT", "authorities": [ { "type": "AAD", "audience": { "type": "AzureADandPersonalMicrosoftAccount", "tenant_id": "common" } } ] } ``` -------------------------------- ### Check Token Expiration Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Provides an example of checking if a token is still valid before use. If expired, it shows how to initiate a silent refresh. ```dart if (authResult.expiresOn.isAfter(DateTime.now())) { // Token is valid, use it } else { // Token expired, refresh it final newResult = await pca.acquireTokenSilent(scopes: scopes); } ``` -------------------------------- ### List, Get, and Remove Accounts Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/README.md Retrieve a list of all cached accounts, fetch a specific account by its identifier, and remove an account from the cache. Acquires a token silently for a specific account. ```dart final accounts = await multipleAccountPca.getAccounts(); for (final account in accounts) { print('${account.name} (${account.username})'); } // Get specific account final account = await multipleAccountPca.getAccount( identifier: accounts[0].id, ); // Acquire token for account final result = await multipleAccountPca.acquireTokenSilent( scopes: scopes, identifier: account.id, ); // Remove account await multipleAccountPca.removeAccount(identifier: account.id); ``` -------------------------------- ### Account Constructor Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/account.md Initializes a new Account object with essential user information. ```APIDOC ## Account Constructor Initializes a new Account object with essential user information. ```dart Account({ required String id, required String? username, required String? name, }) ``` ### Parameters #### Path Parameters - **id** (String) - Required - Unique account identifier. For Microsoft Identity Platform, this is the OID of the account in its home tenant. - **username** (String?) - Required - Preferred username claim (usually email address or UPN). May be unavailable on B2C with external identity providers. - **name** (String?) - Required - User's display name from account claims. May be null if the user is registered without setting a name. ``` -------------------------------- ### Acquire Token and Make API Call Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/authentication-result.md Demonstrates how to acquire an authentication token, check its validity, and use it to make a secure API call to Microsoft Graph. Includes error handling for authentication failures. ```dart try { final authResult = await publicClientApplication.acquireToken( scopes: ['https://graph.microsoft.com/user.read'], ); // Check if token is still valid if (authResult.expiresOn.isAfter(DateTime.now())) { print('Token is valid'); print('Scope: ${authResult.scopes.join(", ")}'); } // Use the authorization header for API calls final headers = { 'Authorization': authResult.authorizationHeader, 'Content-Type': 'application/json', }; // Make API call to Microsoft Graph final response = await http.get( Uri.parse('https://graph.microsoft.com/v1.0/me'), headers: headers, ); print('User: ${authResult.account.username}'); print('Tenant: ${authResult.tenantId}'); } on MsalException catch (e) { print('Authentication failed: ${e.message}'); } ``` -------------------------------- ### Configure Multiple Environments Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Shows how to support multiple authority URLs for different environments (e.g., production and testing) by dynamically setting the authority based on an environment flag. ```dart final authority = isProduction ? 'https://login.microsoftonline.com/production-tenant-id' : 'https://login.microsoftonline.com/test-tenant-id'; final config = AppleConfig( authority: authority, authorityType: AuthorityType.aad, ); ``` -------------------------------- ### Get Current Account (Single Account Mode) Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/MANIFEST.md Retrieves the currently signed-in account in single-account mode. Returns null if no account is signed in. ```dart Account? get currentAccount; ``` -------------------------------- ### Create Single Account Public Client Application Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Use this factory method to initialize a single account public client application. It requires a client ID and platform-specific configurations. ```dart static Future create({ required String clientId, AndroidConfig? androidConfig, AppleConfig? appleConfig, }) ``` -------------------------------- ### Get a Specific Account Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/multiple-account-pca.md Retrieve a specific user account from the cache using its unique identifier. This is useful when you need to perform operations on a particular account. ```dart try { final account = await msalAuth.getAccount( identifier: 'account-id-from-previous-login', ); print('Account: ${account.username}'); } on MsalException catch (e) { print('Account not found: ${e.message}'); } ``` -------------------------------- ### acquireToken() Parameters Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Configuration parameters for interactive token acquisition. Requires a list of scopes and supports optional parameters for prompt behavior, login hint, authority, and custom web view. ```dart Future acquireToken({ required List scopes, Prompt prompt = Prompt.whenRequired, String? loginHint, String? authority, CustomWebViewConfig? customWebViewConfig, }) ``` -------------------------------- ### Create Multiple Account Public Client Application Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Use this factory method to initialize a multiple account public client application. It accepts the same parameters as `SingleAccountPca.create()`. ```dart static Future create({ required String clientId, AndroidConfig? androidConfig, AppleConfig? appleConfig, }) ``` -------------------------------- ### Get All Cached Accounts Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/multiple-account-pca.md Retrieve a list of all user accounts currently stored in the application's cache. This method returns an empty list if no accounts are found. ```dart try { final accounts = await msalAuth.getAccounts(); if (accounts.isEmpty) { print('No accounts cached'); } else { for (final account in accounts) { print('Account: ${account.username} (ID: ${account.id})'); } } } on MsalException catch (e) { print('Error retrieving accounts: ${e.message}'); } ``` -------------------------------- ### Account Constructor Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/account.md Initializes a new Account object with essential identifiers and user information. Required parameters are id, username, and name. ```dart Account({ required String id, required String? username, required String? name, }) ``` -------------------------------- ### Get Current Account (Single Account Mode) Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/account.md Retrieves the currently signed-in account in single account mode. Handles potential MsalException if no account is found. ```dart try { // Get the currently signed-in account final account = await singleAccountPca.currentAccount; print('Account ID: ${account.id}'); print('Username: ${account.username}'); print('Display Name: ${account.name}'); } on MsalException catch (e) { print('No account found: ${e.message}'); } ``` -------------------------------- ### Get Current Account Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/single-account-pca.md Retrieve the currently signed-in account using the currentAccount getter. This method returns the account details or throws an MsalException if no account is found. ```dart Future get currentAccount ``` ```dart try { final account = await msalAuth.currentAccount; print('Current user: ${account.username}'); print('Display name: ${account.name}'); } on MsalException catch (e) { print('No account found: ${e.message}'); } ``` -------------------------------- ### Android Keystore Configuration (key.properties) Source: https://github.com/nayanaubie/msal_auth/blob/main/example/README.md For release builds, place the upload-keystore.jks file in the android/app folder and specify its path in the storeFile property within key.properties. ```properties storeFile=./upload-keystore.jks ``` -------------------------------- ### PublicClientApplication Methods Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/README.md These methods are available on the base PublicClientApplication class and are inherited by SingleAccountPca and MultipleAccountPca. They handle the core token acquisition logic. ```APIDOC ## acquireToken ### Description Acquires a token interactively by opening a browser or broker. ### Method `acquireToken({scopes, prompt?, loginHint?, authority?, customWebViewConfig?})` ### Parameters - **scopes** (List) - Required - The scopes for which to request the token. - **prompt** (Prompt?) - Optional - The prompt behavior for the authentication request. - **loginHint** (String?) - Optional - A hint for the username to pre-fill. - **authority** (String?) - Optional - The authority to use for the authentication request. - **customWebViewConfig** (CustomWebViewConfig?) - Optional - Configuration for a custom web view. ### Returns `Future` - An object containing the access token and account information. ## acquireTokenSilent ### Description Acquires a token silently from the cache or by using a refresh token. ### Method `acquireTokenSilent({scopes, identifier?, authority?})` ### Parameters - **scopes** (List) - Required - The scopes for which to request the token. - **identifier** (String?) - Optional - The account identifier to use for silent acquisition. - **authority** (String?) - Optional - The authority to use for the authentication request. ### Returns `Future` - An object containing the access token and account information. ## isSharedDevice ### Description Checks if the device is in a shared device mode. ### Method `isSharedDevice()` ### Returns `Future` - True if the device is in shared mode, false otherwise. ``` -------------------------------- ### Handle MsalUnsupportedBrokerException on Android Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/errors.md Catch MsalUnsupportedBrokerException when an incompatible broker is detected. This allows for suggesting alternative solutions like installing Microsoft Authenticator or using browser authentication. ```dart try { final pca = await SingleAccountPca.create( clientId: clientId, androidConfig: androidConfig, ); } on MsalUnsupportedBrokerException catch (e) { print('Unsupported broker: ${e.activeBrokerPackageName}'); // Suggest installing Microsoft Authenticator // or reconfigure to use browser authentication } on MsalException catch (e) { print('Error: ${e.message}'); } ``` -------------------------------- ### CustomWebViewConfig Constructor Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/custom-web-view-config.md Initializes a new instance of the CustomWebViewConfig class with customizable properties for the WebView's appearance and behavior. ```APIDOC ## Constructor: CustomWebViewConfig ### Description Initializes a new instance of the CustomWebViewConfig class with customizable properties for the WebView's appearance and behavior. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | title | `String?` | No | null | Title of the WebView. For macOS, title of the authentication window. | | cancelButtonTitle | `String` | No | `'Cancel'` | Title of the cancel button (iOS only). | | showNavigationControls | `bool` | No | `false` | Whether to show navigation controls (iOS only). | ### Request Example ```dart final customWebViewConfig = CustomWebViewConfig( title: 'Sign In to Your Account', cancelButtonTitle: 'Close', showNavigationControls: true, ); ``` ### Response #### Success Response (200) N/A (Constructor) #### Response Example N/A (Constructor) ``` -------------------------------- ### Get Specific Account (Multiple Account Mode) Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/MANIFEST.md Retrieves a specific account from the cache based on its identifier. Use this when you need to perform operations on a particular user's session. ```dart Future getAccount(String accountId); ``` -------------------------------- ### Build Flutter APK with Environment Variables Source: https://github.com/nayanaubie/msal_auth/blob/main/example/README.md Use this command to build a release APK for Android, loading environment variables from a specified file. Ensure your `.env` file is correctly configured. ```sh flutter build apk --dart-define-from-file=.env ``` -------------------------------- ### Manage Accounts (Multiple Account Mode) Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/account.md Demonstrates listing all cached accounts, retrieving a specific account by ID, acquiring a token silently for an account, and removing an account in multiple account mode. Handles potential MsalException. ```dart try { // List all cached accounts final accounts = await multipleAccountPca.getAccounts(); for (final account in accounts) { print('${account.name} (${account.username})'); } // Get a specific account by ID final specificAccount = await multipleAccountPca.getAccount( identifier: accounts[0].id, ); // Acquire token for a specific account final result = await multipleAccountPca.acquireTokenSilent( scopes: ['https://graph.microsoft.com/user.read'], identifier: specificAccount.id, ); // Remove an account await multipleAccountPca.removeAccount( identifier: specificAccount.id, ); } on MsalException catch (e) { print('Error: ${e.message}'); } ``` -------------------------------- ### Handle MsalServerException on iOS/macOS Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/errors.md Catch MsalServerException when the server returns an error response. This example demonstrates logging the server error message and suggests implementing retry logic with exponential backoff. ```dart try { final result = await pca.acquireToken(scopes: scopes); } on MsalServerException catch (e) { print('Server error: ${e.message}'); // Retry with exponential backoff } on MsalException catch (e) { print('Error: ${e.message}'); } ``` -------------------------------- ### Catch Specific MSAL Exceptions Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/errors.md Always catch specific MSAL exceptions before generic MsalException to handle different error scenarios appropriately. This example shows handling UI required, user cancellation, and scope denial. ```dart try { final result = await pca.acquireToken(scopes: scopes); } on MsalUiRequiredException catch (e) { // Handle UI required await pca.acquireToken(scopes: scopes); } on MsalUserCancelException catch (e) { // User cancelled - just log print('Cancelled by user'); } on MsalDeclinedScopeException catch (e) { // Handle partial grant print('Some scopes were denied'); } on MsalException catch (e) { // Catch all other MSAL errors print('Authentication failed: ${e.message}'); } ``` -------------------------------- ### AndroidConfig Constructor Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/android-config.md Initializes an AndroidConfig object with the necessary configuration details for MSAL on Android. This includes the path to the configuration file and the application's redirect URI. ```APIDOC ## AndroidConfig Constructor ### Description Initializes an AndroidConfig object with the necessary configuration details for MSAL on Android. This includes the path to the configuration file and the application's redirect URI. ### Parameters #### Path Parameters - **configFilePath** (`String`) - Required - Asset path to the MSAL configuration JSON file. Typically `'assets/msal_config.json'`. - **redirectUri** (`String`) - Required - Redirect URI for the Android application. Available in Azure Portal authentication settings. Format: `msauth:///`. ``` -------------------------------- ### Configure WebView Authentication Source: https://github.com/nayanaubie/msal_auth/blob/main/README.md Set broker authentication to use WebView for authentication. This requires redirect URI registration to be false. ```JSON "broker_redirect_uri_registered": false, "authorization_user_agent": "WEBVIEW" ``` -------------------------------- ### Account Factory Methods Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/account.md Provides methods for creating Account objects from different data sources. ```APIDOC ## Factory Methods Provides methods for creating Account objects from different data sources. ### fromJson Creates an `Account` from a JSON map. ```dart factory Account.fromJson(Map json) ``` **Parameters**: `json` — Map containing account data **Returns**: `Account` instance ``` -------------------------------- ### Configure Browser Authentication Source: https://github.com/nayanaubie/msal_auth/blob/main/README.md Set broker authentication to use the browser for authentication. This requires redirect URI registration to be false. ```JSON "broker_redirect_uri_registered": false, "authorization_user_agent": "BROWSER" ``` -------------------------------- ### Info.plist Redirect URI Scheme Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Configuration for the Info.plist file to add the redirect URI scheme. This is necessary for handling authentication callbacks. ```plist CFBundleURLTypes CFBundleURLSchemes msauth.$(PRODUCT_BUNDLE_IDENTIFIER) ``` -------------------------------- ### iOS AppDelegate Configuration Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/MANIFEST.md Code snippet for the AppDelegate.swift file to handle authentication callbacks from MSAL. ```swift func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { MSALPublicClientApplication.handleMSALResponse(url) return true } ``` -------------------------------- ### MultipleAccountPca.create Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/multiple-account-pca.md Factory method to create and initialize a multiple account public client application. Configures the application with platform-specific settings and returns an instance ready for managing multiple user accounts. ```APIDOC ## MultipleAccountPca.create ### Description Factory method to create and initialize a multiple account public client application. This method configures the application with platform-specific settings and returns an instance ready for managing multiple user accounts. ### Method Factory ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **clientId** (`String`) - Required - Client ID (Application ID) from Azure App Registration. - **androidConfig** (`AndroidConfig?`) - Optional - Android-specific configuration. Required for Android platform. Includes config file path and redirect URI. - **appleConfig** (`AppleConfig?`) - Optional - iOS/macOS-specific configuration. Required for iOS and macOS platforms. ### Returns `Future` - Initialized MultipleAccountPca instance ready for authentication. ### Throws - `MsalPcaInitException` - If initialization fails - `PlatformException` - Converted to appropriate `MsalException` subclass ### Example ```dart final msalAuth = await MultipleAccountPca.create( clientId: '00000000-0000-0000-0000-000000000000', androidConfig: AndroidConfig( configFilePath: 'assets/msal_config.json', redirectUri: 'msauth://com.example.app/YOUR_BASE64_SIGNATURE', ), appleConfig: AppleConfig( authority: 'https://login.microsoftonline.com/common', authorityType: AuthorityType.aad, broker: Broker.msAuthenticator, ), ); ``` ``` -------------------------------- ### MSAL Configuration for WebView (msal_config.json) Source: https://github.com/nayanaubie/msal_auth/blob/main/example/README.md If using WebView for authentication, set 'authorization_user_agent' to 'WEBVIEW' and 'broker_redirect_uri_registered' to false in msal_config.json. ```json "authorization_user_agent": "WEBVIEW", "broker_redirect_uri_registered": false ``` -------------------------------- ### Handle MSAL Exceptions Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Demonstrates how to handle specific MSAL exceptions during token acquisition. This includes re-authentication scenarios and user cancellation. ```dart try { final result = await pca.acquireToken(scopes: scopes); } on MsalUiRequiredException { // Refresh token invalid, re-authenticate } on MsalUserCancelException { // User cancelled, handle gracefully } on MsalException { // Other MSAL errors } ``` -------------------------------- ### Create Single Account PCA Instance Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/README.md Initializes a SingleAccountPca instance with client ID and platform-specific configurations. Ensure the config file path and redirect URI are correctly set for Android. ```dart final msalAuth = await SingleAccountPca.create( clientId: 'your-client-id', androidConfig: AndroidConfig( configFilePath: 'assets/msal_config.json', redirectUri: 'msauth://com.example.app/signature', ), appleConfig: AppleConfig( authorityType: AuthorityType.aad, ), ); ``` -------------------------------- ### Android Redirect URI Configuration (.env file) Source: https://github.com/nayanaubie/msal_auth/blob/main/example/README.md Add the generated signature hash values to the relevant keys in the .env file for debug and release redirect URIs. If release mode is not required, use the debug redirect URI directly. ```ini AAD_DEBUG_ANDROID_REDIRECT_URI=debug-redirect-uri # Required only if you want to run the app in release mode AAD_RELEASE_ANDROID_REDIRECT_URI=release-redirect-uri ``` -------------------------------- ### SingleAccountPca.create Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/single-account-pca.md Factory method to create and initialize a single account public client application. This method configures the application with platform-specific settings and returns an instance ready for authentication operations. ```APIDOC ## SingleAccountPca.create ### Description Factory method to create and initialize a single account public client application. This method configures the application with platform-specific settings and returns an instance ready for authentication operations. ### Method `static Future create` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **clientId** (`String`) - Required - Client ID (Application ID) from Azure App Registration. - **androidConfig** (`AndroidConfig?`) - Optional - Android-specific configuration. Required for Android platform. Includes config file path and redirect URI. - **appleConfig** (`AppleConfig?`) - Optional - iOS/macOS-specific configuration. Required for iOS and macOS platforms. ### Returns `Future` — Initialized SingleAccountPca instance ready for authentication. ### Throws - `MsalPcaInitException` — If initialization fails - `PlatformException` — Converted to appropriate `MsalException` subclass ### Example ```dart final msalAuth = await SingleAccountPca.create( clientId: '00000000-0000-0000-0000-000000000000', androidConfig: AndroidConfig( configFilePath: 'assets/msal_config.json', redirectUri: 'msauth://com.example.app/YOUR_BASE64_SIGNATURE', ), appleConfig: AppleConfig( authority: 'https://login.microsoftonline.com/common', authorityType: AuthorityType.aad, broker: Broker.msAuthenticator, ), ); ``` ``` -------------------------------- ### Create Single Account PCA Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/MANIFEST.md Factory method to initialize the PublicClientApplication for single-account mode. This mode is suitable for applications where only one user is signed in at a time. ```dart static Future create(AuthConfig config); ``` -------------------------------- ### Create Multiple Account PCA Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/MANIFEST.md Factory method to initialize the PublicClientApplication for multiple-account mode. This mode supports multiple users signing in concurrently within the application. ```dart static Future create(AuthConfig config); ``` -------------------------------- ### Acquire Token Interactively Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/public-client-application.md Acquires an access token by opening the Microsoft login page. Use this when a valid token is not available in the cache or when a specific prompt is required. It skips the token cache lookup. ```dart Future acquireToken({ required List scopes, Prompt prompt = Prompt.whenRequired, String? loginHint, String? authority, CustomWebViewConfig? customWebViewConfig, }) ``` ```dart final authResult = await publicClientApplication.acquireToken( scopes: [ 'https://graph.microsoft.com/user.read', ], prompt: Prompt.login, loginHint: 'user@example.com', ); print('Access Token: ${authResult.accessToken}'); print('Expires On: ${authResult.expiresOn}'); ``` -------------------------------- ### AppleConfig Constructor Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/apple-config.md Initializes an AppleConfig object with settings for iOS and macOS MSAL authentication. Allows customization of the authority URL, authority type (AAD or B2C), and the authentication broker (e.g., MS Authenticator, Safari, WebView). ```APIDOC ## Constructor AppleConfig ### Description Initializes an `AppleConfig` object with platform-specific MSAL settings for iOS and macOS. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **authority** (`String?`) - Optional - Authority URL for the identity provider. Required when using B2C. - **authorityType** (`AuthorityType`) - Optional - Type of authority: AAD (Microsoft Entra ID) or B2C (Business-to-Consumer). Defaults to `AuthorityType.aad`. - **broker** (`Broker`) - Optional - Authentication middleware (broker). Only used on iOS. Defaults to `Broker.msAuthenticator`. ### Request Example ```dart final appleConfig = AppleConfig( authority: 'https://your-tenant.b2clogin.com/your-tenant.onmicrosoft.com/b2c_1_signin', authorityType: AuthorityType.b2c, broker: Broker.msAuthenticator, ); ``` ### Response None (Constructor) ``` -------------------------------- ### Request Specific Scopes Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Illustrates requesting minimal necessary scopes for a token acquisition. Avoid requesting overly broad permissions to enhance security. ```dart // ❌ Too broad final result = await pca.acquireToken( scopes: ['https://graph.microsoft.com/.default'], ); // ✓ Specific scopes final result = await pca.acquireToken( scopes: ['https://graph.microsoft.com/user.read'], ); ``` -------------------------------- ### AppleConfig Constructor Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/apple-config.md Initializes AppleConfig with optional authority, authority type, and broker settings. The authority is required for B2C. ```dart AppleConfig({ String? authority, AuthorityType authorityType = AuthorityType.aad, Broker broker = Broker.msAuthenticator, }) ``` -------------------------------- ### Create SingleAccountPca Instance Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/single-account-pca.md Use this factory method to create and initialize a SingleAccountPca instance. Platform-specific configurations for Android and Apple platforms are required. ```dart static Future create({ required String clientId, AndroidConfig? androidConfig, AppleConfig? appleConfig, }) ``` ```dart final msalAuth = await SingleAccountPca.create( clientId: '00000000-0000-0000-0000-000000000000', androidConfig: AndroidConfig( configFilePath: 'assets/msal_config.json', redirectUri: 'msauth://com.example.app/YOUR_BASE64_SIGNATURE', ), appleConfig: AppleConfig( authority: 'https://login.microsoftonline.com/common', authorityType: AuthorityType.aad, broker: Broker.msAuthenticator, ), ); ``` -------------------------------- ### Secure Client ID Storage Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Demonstrates the correct way to handle sensitive values like client IDs by loading them from secure storage instead of hardcoding. ```dart // ❌ Wrong const clientId = '00000000-0000-0000-0000-000000000000'; // ✓ Correct - load from config or secure storage final clientId = await getClientIdFromSecureStorage(); ``` -------------------------------- ### Authorization Header Usage Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/MANIFEST.md Demonstrates how to construct an 'Authorization' header using an access token obtained from MSAL. This is commonly used when making API calls to protected resources. ```dart final authResult = await pca.acquireTokenSilent(...); final String accessToken = authResult.accessToken; final Map headers = { 'Authorization': 'Bearer $accessToken', 'Content-Type': 'application/json', }; ``` -------------------------------- ### AndroidConfig Constructor Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/android-config.md Initializes an AndroidConfig object. Requires the asset path to the MSAL configuration JSON file and the application's redirect URI registered in Azure Portal. ```dart AndroidConfig({ required String configFilePath, required String redirectUri, }) ``` -------------------------------- ### Create MultipleAccountPca Instance Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/multiple-account-pca.md Use this factory method to create and initialize a MultipleAccountPca instance. Configure platform-specific settings like client ID and Android/Apple configurations. ```dart final msalAuth = await MultipleAccountPca.create( clientId: '00000000-0000-0000-0000-000000000000', androidConfig: AndroidConfig( configFilePath: 'assets/msal_config.json', redirectUri: 'msauth://com.example.app/YOUR_BASE64_SIGNATURE', ), appleConfig: AppleConfig( authority: 'https://login.microsoftonline.com/common', authorityType: AuthorityType.aad, broker: Broker.msAuthenticator, ), ); ``` -------------------------------- ### Factory Methods Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/authentication-result.md Provides methods for creating instances of AuthenticationResult from different sources. ```APIDOC ## Factory Methods ### fromJson #### Description Creates an `AuthenticationResult` from a JSON map. #### Parameters - **json** (Map) - Map containing authentication result data #### Returns - `AuthenticationResult` instance ``` -------------------------------- ### Configuration File Format Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/android-config.md Specifies the expected JSON format for the MSAL configuration file referenced by `configFilePath`, including essential fields like account mode, authority, and audience. ```APIDOC ## Configuration File Format The JSON configuration file referenced by `configFilePath` should follow Microsoft's default MSAL configuration format. At minimum, it should specify: ```json { "account_mode": "SINGLE", "broker_redirect_uri_registered": true, "authorization_user_agent": "DEFAULT", "authorities": [ { "type": "AAD", "audience": { "type": "AzureADandPersonalMicrosoftAccount", "tenant_id": "common" } } ] } ``` Note: The `client_id` and `redirect_uri` fields are added programmatically and should not be included in the JSON file. ``` -------------------------------- ### Handle MsalPcaInitException Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/errors.md Catch MsalPcaInitException if the Public Client Application was not properly initialized. This can occur if authentication methods are called before PCA creation completes. ```dart late SingleAccountPca pca; // Must initialize before use pca = await SingleAccountPca.create( clientId: clientId, androidConfig: androidConfig, appleConfig: appleConfig, ); try { final result = await pca.acquireToken(scopes: scopes); } on MsalPcaInitException catch (e) { print('PCA not initialized: ${e.message}'); } on MsalException catch (e) { print('Error: ${e.message}'); } ``` -------------------------------- ### Prompt Enum Options Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Defines the available options for the 'prompt' parameter in interactive token acquisition. Each option controls the UI prompt behavior during the authentication flow. ```dart enum Prompt { selectAccount, // Show account selection list login, // Always prompt for credentials consent, // Always show consent screen create, // Prompt to create new account whenRequired, // Prompt only if necessary (default) } ``` -------------------------------- ### Add LSApplicationQueriesSchemes to iOS Info.plist Source: https://github.com/nayanaubie/msal_auth/blob/main/README.md Add LSApplicationQueriesSchemes to Info.plist to enable the use of Microsoft Authenticator as a broker. This is not required for Safari Browser or WebView brokers. ```Plist LSApplicationQueriesSchemes msauthv2 msauthv3 ``` -------------------------------- ### iOS Info.plist Configuration Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/MANIFEST.md Key entries required in the Info.plist file for iOS to support MSAL authentication, such as URL schemes. ```xml CFBundleURLTypes CFBundleTypeRole Editor CFBundleURLName com.yourcompany.yourapp CFBundleURLSchemes msauth.com.yourcompany.yourapp ``` -------------------------------- ### Handle MsalProtectionPolicyRequiredException Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/errors.md Use this snippet when accessing Intune-protected resources. It catches the specific exception and suggests prompting the user to enroll their device in MDM before retrying authentication. ```dart try { final result = await pca.acquireToken(scopes: scopes); } on MsalProtectionPolicyRequiredException catch (e) { print('Protection policy required: ${e.message}'); // Prompt user to enroll device in MDM // Then retry authentication } on MsalException catch (e) { print('Error: ${e.message}'); } ``` -------------------------------- ### Prompt Enum for Interactive Token Acquisition Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/types.md Specifies UI options for interactive token acquisition. Use 'selectAccount' for account selection, 'login' to always prompt for credentials, 'consent' for consent screen, 'create' for new account creation, or 'whenRequired' for default behavior. ```dart enum Prompt { selectAccount, // Show account selection list login, // Always prompt for credentials consent, // Always show consent screen create, // Prompt to create new account whenRequired // Prompt only if needed (default) } ``` ```dart // Always show login prompt final result = await pca.acquireToken( scopes: ['https://graph.microsoft.com/user.read'], prompt: Prompt.login, ); ``` ```dart // Show account selection final result = await pca.acquireToken( scopes: ['https://graph.microsoft.com/user.read'], prompt: Prompt.selectAccount, ); ``` ```dart // Request new account creation final result = await pca.acquireToken( scopes: ['https://graph.microsoft.com/user.read'], prompt: Prompt.create, ); ``` -------------------------------- ### Handle MSAL Response in iOS Source: https://github.com/nayanaubie/msal_auth/blob/main/README.md Handles the MSAL authentication response from a URL context in an iOS application. Ensure MSAL is imported. ```swift import MSAL func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let urlContext = URLContexts.first else { return } let url = urlContext.url let sourceApp = urlContext.options.sourceApplication MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: sourceApp) } ``` -------------------------------- ### Create Single Account Public Client Application in Flutter Source: https://github.com/nayanaubie/msal_auth/blob/main/README.md Creates a public client application for single account mode in Flutter using MSAL. Requires client ID, redirect URI, and optionally authority type and broker configuration. ```dart final msalAuth = await SingleAccountPca.create( clientId: '', androidConfig: AndroidConfig( configFilePath: 'assets/msal_config.json', redirectUri: '', ), appleConfig: AppleConfig( authority: '', // Change authority type to 'b2c' for business to customer flow. authorityType: AuthorityType.aad, // Change broker if you need. Applicable only for iOS platform. broker: Broker.msAuthenticator, ), ); ``` -------------------------------- ### Handle MSAL Callback in AppDelegate.swift (iOS < 3.4.0) Source: https://github.com/nayanaubie/msal_auth/blob/main/README.md Implement the application:openURL:options: method in AppDelegate.swift to handle MSAL responses. This is applicable for MSAL versions 3.3.0 and earlier. ```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) } ``` -------------------------------- ### AuthenticationResult Constructor Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/authentication-result.md Constructs an AuthenticationResult object with all the necessary authentication details. ```APIDOC ## Constructor AuthenticationResult ### Description Initializes a new instance of the `AuthenticationResult` class. ### Parameters #### Required Parameters - **accessToken** (String) - The OAuth 2.0 access token to access protected resources. - **authenticationScheme** (String) - The authentication scheme (e.g., "Bearer", "PoP"). - **expiresOn** (DateTime) - Expiration time of the access token (UTC). Calculated from server response and current local time. - **idToken** (String?) - JWT-format ID token conforming to RFC-7519 and OpenID Connect Core specification. May be null. - **authority** (String) - Authority URL used in creating the application. - **tenantId** (String?) - Unique tenant identifier used in token acquisition. May be null if not returned by service. - **scopes** (List) - List of scopes granted by the service. - **correlationId** (String?) - Correlation ID used during the acquire token request. May be null. - **account** (Account) - Microsoft account details and user information. ``` -------------------------------- ### Android Configuration JSON Format Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/MANIFEST.md Reference for the JSON structure used to configure MSAL for Android. This includes parameters like client ID, authority, and redirect URI. ```json { "client_id": "YOUR_CLIENT_ID", "authority": "https://login.microsoftonline.com/YOUR_TENANT_ID", "redirect_uri": "msauth://YOUR_APP_PACKAGE_NAME/YOUR_SCHEME" } ``` -------------------------------- ### Acquire Token Interactively Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/README.md Acquires an access token interactively for the specified scopes. Handles potential MsalException by printing the error message. ```dart try { final result = await msalAuth.acquireToken( scopes: ['https://graph.microsoft.com/user.read'], ); print('Token: ${result.accessToken}'); } on MsalException catch (e) { print('Error: ${e.message}'); } ``` -------------------------------- ### Info.plist Microsoft Authenticator Broker Configuration Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Optional configuration for Info.plist to enable the Microsoft Authenticator broker. This involves adding specific application query schemes. ```plist LSApplicationQueriesSchemes msauthv2 msauthv3 ``` -------------------------------- ### iOS Broker Options Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Defines the available brokers for interactive authentication on iOS. Choose the appropriate broker based on the desired authentication flow and user experience. ```dart enum Broker { msAuthenticator, // Microsoft Authenticator app (with Safari fallback) safariBrowser, // Safari browser webView // In-app WebView } ``` -------------------------------- ### Handle MsalClientException Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/errors.md Use this snippet to catch general client-side library errors. It shows how to check the specific error code, such as 'device_network_not_available' or 'json_parse_failure', to provide user-friendly feedback. ```dart try { final result = await pca.acquireToken(scopes: scopes); } on MsalClientException catch (e) { print('Client error: ${e.errorCode}'); print('Message: ${e.message}'); switch (e.errorCode) { case 'device_network_not_available': print('Please check your internet connection'); case 'json_parse_failure': print('Configuration file is invalid'); default: print('Unexpected error'); } } on MsalException catch (e) { print('Error: ${e.message}'); } ``` -------------------------------- ### Android Manifest - BrowserTabActivity Configuration Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/configuration.md Required activity declaration in `AndroidManifest.xml` for handling browser authentication redirects. Ensure the `android:host` and `android:path` match your redirect URI. ```xml ``` -------------------------------- ### acquireToken Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/api-reference/public-client-application.md Acquires an access token interactively by opening the Microsoft login page. This method bypasses the token cache. ```APIDOC ## acquireToken ### Description Acquires an access token interactively. This method opens the Microsoft login page in the configured broker (Microsoft Authenticator, Safari Browser, or WebView) and returns the authentication result upon successful login. This flow skips the token cache lookup. ### Method POST (Implicit) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart final authResult = await publicClientApplication.acquireToken( scopes: [ 'https://graph.microsoft.com/user.read', ], prompt: Prompt.login, loginHint: 'user@example.com', ); print('Access Token: ${authResult.accessToken}'); print('Expires On: ${authResult.expiresOn}'); ``` ### Response #### Success Response `Future` - Authentication result containing access token, account information, and metadata. #### Response Example ```dart // Example AuthenticationResult object structure { "accessToken": "...", "expiresOn": "...", "account": { ... } } ``` ### Throws - `MsalUiRequiredException` — If UI is required but not available - `MsalUserCancelException` — If user cancels the authentication flow - `MsalServiceException` — If service communication fails - `MsalClientException` — If client-side error occurs - Other platform-specific exceptions ``` -------------------------------- ### AndroidConfig Source: https://github.com/nayanaubie/msal_auth/blob/main/_autodocs/types.md Platform-specific configuration for Android, including the configuration file path and redirect URI. ```APIDOC ## AndroidConfig ### Description Platform-specific configuration for Android. ### Properties - `configFilePath` (String) - Required - Asset path to MSAL JSON configuration. - `redirectUri` (String) - Required - OAuth redirect URI from Azure Portal. ```