Flutter微软认证登录插件msal_auth的使用
Flutter微软认证登录插件msal_auth的使用
MSAL Auth 🔒
Microsoft Authentication Library (MSAL) 为Flutter提供了一种在Android和iOS设备上使用本地MSAL库进行微软认证的方式。这个插件非常简单易用。
平台支持
Android | iOS | macOS |
---|---|---|
SDK 21+ | 14+ | 10.15+ |
功能 🚀
- 支持设置以下代理(认证中间件):
- Microsoft Authenticator App
- 浏览器
- 应用内WebView
- 单账户和多账户模式支持
- 支持不同的身份提供商(authority):
- AAD (Microsoft Entra ID)
- B2C (Business to customer)
- 支持交互式和静默获取令牌
- 可以设置登录提示和提示类型
- 完整的认证结果包含账户信息
创建应用在Azure Portal中
为了在Flutter中实现MSAL,首先需要在Azure Portal中创建一个应用并配置特定平台的设置。
- 登录Azure Portal并注册新应用。
- 填写应用名称、选择支持的账户类型并注册。
- 记录下
Application (client) ID
和Directory (tenant) ID
。 - 添加平台配置(Android/iOS/macOS)。
Android Setup - Azure portal
对于Android,您需要提供package name
和release signature hash
。可以通过以下命令生成签名hash:
keytool -exportcert -alias androidreleasekey -keystore app/upload-keystore.jks | openssl sha1 -binary | openssl base64
iOS/macOS Setup - Azure portal
只需提供iOS/macOS应用的Bundle ID
,重定向URI将由系统自动生成。
配置平台
Android Configuration
创建MSAL配置JSON
在项目的/assets
文件夹中创建msal_config.json
文件,并从默认MSAL配置文件复制内容。
- 设置
redirect_uri
:格式为msauth://<APP_PACKAGE_NAME>/<BASE64_ENCODED_PACKAGE_SIGNATURE>
- JSON中不需要包含
client_id
和redirect_uri
,它们将在创建公共客户端应用程序时通过Dart代码添加。
设置账户模式
单账户模式:
"account_mode": "SINGLE"
多账户模式:
"account_mode": "MULTIPLE"
设置Authority
根据需求配置Authority,请参考文档。
设置Broker(可选)
- 使用Microsoft Authenticator App进行认证:
"broker_redirect_uri_registered": true
- 使用浏览器认证:
"broker_redirect_uri_registered": false, "authorization_user_agent": "BROWSER"
- 使用WebView认证:
"broker_redirect_uri_registered": false, "authorization_user_agent": "WEBVIEW"
在AndroidManifest.xml中添加BrowserTabActivity
如果使用浏览器认证,需在AndroidManifest.xml
文件中的<application>
标签内添加:
<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>
iOS Configuration
Info.plist修改
- 添加重定向URI scheme:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>msauth.$(PRODUCT_BUNDLE_IDENTIFIER)</string> </array> </dict> </array>
- 允许调用Microsoft Authenticator应用:
<key>LSApplicationQueriesSchemes</key> <array> <string>msauthv2</string> <string>msauthv3</string> </array>
处理回调
在AppDelegate.swift
或SceneDelegate.swift
中处理登录成功的回调:
// 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)
}
// 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)
}
macOS Configuration
- 添加新的密钥链组
com.microsoft.identity.universalstorage
到项目功能。 - 如果遇到
NSPOSIXErrorDomain
错误,需在DebugProfile.entitlements
文件中添加网络权限:<key>com.apple.security.network.client</key> <true/>
代码实现 👨💻
创建公共客户端应用程序
final msalAuth = await SingleAccountPca.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 only for iOS platform.
broker: Broker.msAuthenticator,
),
);
获取Token(登录微软账户)
final authResult = await publicClientApplication.acquireToken(
scopes: ['https://graph.microsoft.com/user.read'],
prompt: Prompt.login,
loginHint: '<Email Id / Username / Unique Identifier>'
);
log('Auth result: ${authResult.toJson()}');
静默获取Token 🔇
if (expiresOn.isBefore(DateTime.now())) {
final authResult = await publicClientApplication.acquireTokenSilent(
scopes: [],
identifier: 'Account Identifier, required for multiple account mode',
);
log('Auth result: ${authResult.toJson()}');
// Store new value of "expiresOn" or entire "authResult" object.
}
异常处理 🚨
所有MSAL异常都可以在Dart侧捕获并处理。
示例应用 📱
查看示例代码,它展示了如何使用环境变量来配置应用的不同环境,并实现了所有特性。
更多关于Flutter微软认证登录插件msal_auth的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter微软认证登录插件msal_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用msal_auth
插件来实现微软认证登录的示例代码。这个插件允许你通过Microsoft Authentication Library (MSAL)进行认证,以访问Microsoft的API和服务。
首先,你需要在你的Flutter项目中添加msal_auth
依赖。在你的pubspec.yaml
文件中添加以下依赖:
dependencies:
flutter:
sdk: flutter
msal_auth: ^最新版本号 # 请替换为当前可用的最新版本号
然后运行flutter pub get
来安装依赖。
接下来,你需要配置你的应用以使用MSAL。这通常包括在Azure门户中注册你的应用,并获取客户端ID和重定向URI。
以下是一个基本的示例代码,展示如何使用msal_auth
进行微软认证登录:
import 'package:flutter/material.dart';
import 'package:msal_auth/msal_auth.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Microsoft Auth Example'),
),
body: Center(
child: MicrosoftAuthButton(),
),
),
);
}
}
class MicrosoftAuthButton extends StatefulWidget {
@override
_MicrosoftAuthButtonState createState() => _MicrosoftAuthButtonState();
}
class _MicrosoftAuthButtonState extends State<MicrosoftAuthButton> {
String? accessToken;
String? userId;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () async {
try {
// 配置MSAL参数
final msalConfig = MsalConfig(
clientId: '你的客户端ID', // 替换为你的客户端ID
tenantId: '你的租户ID', // 替换为你的租户ID,或使用'common'或'consumers'等
redirectUri: '你的重定向URI', // 替换为你的重定向URI
scopes: ['User.Read'], // 请求的权限范围
);
// 初始化MSAL
final msal = MsalAuth(config: msalConfig);
// 执行登录
final result = await msal.login();
if (result != null && result.accessToken != null) {
setState(() {
accessToken = result.accessToken;
userId = result.userId;
});
// 显示登录结果
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('登录成功! Access Token: ${accessToken!.substring(0, 10)}...'),
duration: Duration(seconds: 5),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('登录失败'),
duration: Duration(seconds: 3),
),
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('发生错误: ${e.message}'),
duration: Duration(seconds: 5),
),
);
}
},
child: Text('登录到Microsoft'),
);
}
}
在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个按钮用于触发微软认证登录。用户点击按钮后,将启动MSAL认证流程,并在成功登录后显示访问令牌的前几位字符。
请注意:
- 你需要替换
clientId
、tenantId
和redirectUri
为你自己的值。 scopes
字段定义了你的应用请求的权限范围,这里我们请求了User.Read
权限,用于读取用户的基本信息。
确保你已经在Azure门户中正确配置了你的应用,并且这些值与你在代码中使用的值相匹配。此外,你可能还需要处理令牌刷新和存储等问题,这取决于你的具体需求。