Flutter微软认证登录插件flutter_msal_mobile的使用

Flutter微软认证登录插件flutter_msal_mobile的使用

项目需求

  • Flutter 版本大于 3.7.0
  • Android 最小SDK版本至少为 24
  • iOS 版本至少为 14.0

如果您的 minSdkVersion 低于 24,可能会出现问题。Android MSAL SDK 依赖于 opentelemetry-bom:1.18.0,该库要求最小 Android SDK 版本为 24。尽管设置为低于 24 的版本可能仍然可以工作,但可能会导致错误。因此,建议将 minSdkVersion 设置为 24 或更高。

安装

pubspec.yaml 文件中添加以下内容,或者运行 dart pub add flutter_msal_mobile

dependencies:
  flutter_msal_mobile: ^[version]

Android 设置

该包支持单账户模式和多账户模式,并自动根据用户配置进行选择。单账户模式适用于需要一个活跃用户的应用,而多账户模式允许在有效令牌的情况下无缝切换账户。重新认证仅在访问令牌和刷新令牌都已过期时才需要。

优化多账户模式:

  • 使用刷新令牌:确保令牌更新以避免中断。
  • 调整令牌生命周期:在 Azure AD 中配置较长的生命周期以简化账户切换。

Android 设置步骤:

  1. 打开 <android > app > src > main > AndroidManifest.xml
  2. 添加 BrowserTabActivity 到您的 AndroidManifest.xml 文件。
    • [your-base64-signature-hash] 应替换为您在 Azure 应用注册时生成的基础64签名哈希。
    • [your-package-name] 应替换为您在 Azure 应用注册时设置的 Android 包名。
<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="[your-package-name]"
            android:path="/[your-base64-signature-hash]"
            android:scheme="msauth" />
    </intent-filter>
</activity>
  1. 确保您的 Android 应用具有互联网访问权限,在 <application> 上方添加以下内容:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  1. 在您的 Flutter 项目中创建一个新的 JSON 文件,并填充由 Azure 在添加 Android 平台到应用注册时生成的配置。文件名称和位置可以自定义,例如 <assets/auth_config.json>。默认配置应如下所示:
{
  "client_id" : "00000000-0000-0000-0000-000000000000",
  "authorization_user_agent" : "DEFAULT",
  "redirect_uri" : "msauth://[your-package-name]/[my-url-encoded-base64-signature-hash]",
  "authorities" : [
    {
      "type": "AAD",
      "audience": {
       "type": "AzureADMultipleOrgs",
       "tenant_id": "organizations"
      }
    }
  ]
}
  1. 将 JSON 资源文件添加到 pubspec.yaml 文件中:
assets:
    - assets/auth_config.json

iOS 设置

  1. auth_config.json 文件中添加 ios_redirect_uri 值。
{
  "client_id" : "<app-registration-client-id>",
  "authorization_user_agent" : "DEFAULT",
  "redirect_uri" : "msauth://<your-package-name>/<url-encoded-package-signature-hash>",
  "ios_redirect_uri": "msauth.<your-ios-bundle-identifier>://auth",
  "account_mode": "SINGLE",
  "authorities" : [
    {
      "type": "AAD",
      "audience": {
       "type": "AzureADMyOrg",
       "tenant_id": "organizations"
      }
    }
  ],
  "logging": {
    "pii_enabled": false
  }
}
  1. 将 iOS 平台目标版本设置为 14.0 或更高版本,通过打开 Xcode 中的 Runner.xcodeproj 文件的属性窗口来实现。
  2. 在“签名和功能”部分,添加“密钥链共享”功能。
  3. 添加 com.microsoft.adalcache 作为密钥链组。
  4. Info.plist 文件中添加以下内容(右键点击文件并以源代码形式打开),并将 [your-bundle-identifier] 替换为在 iOS 平台设置期间识别的 iOS bundle 标识符。
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>msauth.[your-bundle-identifier]</string>
        </array>
    </dict>
</array>
  1. Info.plist 文件中添加以下内容,以启用 Microsoft Authenticator 的使用(如果可用):
<array>
    <string>msauthv2</string>
    <string>msauthv3</string>
</array>

使用

导入 flutter_msal_mobile 包:

import 'package:flutter_msal_mobile/flutter_msal_mobile.dart';

初始化 MSAL,将 [clientId], [scopes], [tenantId], [authority] 替换为您自己的值。

FlutterMsal.init(
  clientId: [clientId],
  scopes: [scopes],
  androidConfig: AndroidConfig(
    configFilePath: 'assets/msal_config.json',
    tenantId: [tenantId],
  ),
  iosConfig: IosConfig(authority: [authority]),
)

API

获取令牌

await msal.acquireToken().then((MsalUser result) {
    print('access token (truncated): ${result.accessToken}');
})

静默获取令牌

await msal.acquireTokenSilent().then((MsalUser result) {
    print('access token (truncated): ${result.accessToken}');
})

注销

await msal.signOut()

错误处理

该包提供了一组自定义异常以简化与 MSAL 认证相关的错误处理。您可能会遇到的主要异常类型包括:

  • MsalException: 一般认证错误的异常。
  • MsalUserCanceledException: 当用户取消认证过程时抛出。
  • MsalUiRequiredException: 表示需要 UI 提示才能完成认证。

为了有效地处理这些异常,您可以在代码中使用 catchError 块,如下所示:

await msal.acquireToken().then((MsalUser user) {
    if (user != null) {
        print('current account id: ${result.oid}');
    }
}).catchError((exception) {
    if (exception is MsalUserCanceledException) {
        print('User cancelled the request: ${exception.errorMessage}');
    } else if (exception is MsalUiRequiredException) {
        print('UI prompt required to acquire token: ${exception.errorMessage}');
    } else if (exception is MsalException) {
        print('General MSAL error: ${exception.errorMessage}');
    } else {
        print('An unexpected exception occurred.');
    }
});

更多关于Flutter微软认证登录插件flutter_msal_mobile的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter微软认证登录插件flutter_msal_mobile的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_msal_mobile 是一个用于在 Flutter 应用中集成微软认证登录 (Microsoft Authentication Library, MSAL) 的插件。它允许你使用 Azure Active Directory (Azure AD) 进行用户身份验证和授权。

以下是使用 flutter_msal_mobile 插件的基本步骤:

1. 添加依赖

首先,在你的 pubspec.yaml 文件中添加 flutter_msal_mobile 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_msal_mobile: ^1.0.0  # 使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 配置 Azure AD 应用

在 Azure 门户中注册你的应用程序,并获取以下信息:

  • 客户端 ID (Client ID)
  • 租户 ID (Tenant ID)
  • 重定向 URI (Redirect URI)

3. 初始化 MSAL 客户端

在你的 Flutter 应用中初始化 MSAL 客户端:

import 'package:flutter_msal_mobile/flutter_msal_mobile.dart';

final msalClient = MSALMobile(
  clientId: 'YOUR_CLIENT_ID',
  authority: 'https://login.microsoftonline.com/YOUR_TENANT_ID',
  redirectUri: 'YOUR_REDIRECT_URI',
);

4. 登录

使用 acquireToken 方法进行用户登录:

try {
  final result = await msalClient.acquireToken(
    scopes: ['user.read'], // 请求的权限范围
  );
  print('Access Token: ${result.accessToken}');
} catch (e) {
  print('Error: $e');
}

5. 处理登录结果

acquireToken 方法会返回一个 MSALResult 对象,其中包含访问令牌、用户信息等。

print('Access Token: ${result.accessToken}');
print('ID Token: ${result.idToken}');
print('User Name: ${result.account?.username}');

6. 注销

使用 signOut 方法注销用户:

await msalClient.signOut();

7. 处理回调

确保在 AndroidManifest.xmlInfo.plist 中正确配置了重定向 URI。

Android

AndroidManifest.xml 中添加以下内容:

<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="YOUR_REDIRECT_URI_HOST" android:scheme="msauth" />
    </intent-filter>
</activity>

iOS

Info.plist 中添加以下内容:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>msauth.$(PRODUCT_BUNDLE_IDENTIFIER)</string>
        </array>
    </dict>
</array>
回到顶部