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

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

重要公告

对于任何问题,请在 GitHub 上打开一个 issue,我们将尽力在时间允许的情况下进行审查。

版本 2.0.0

此包提供“原样”服务。不幸的是,我们没有资源提供免费支持、帮助或审查任何 PR。请随意 fork 或以任何方式使用此包。对于付费支持选项,请发送电子邮件至 info@muljin.com

版本 2.0.0+ 已迁移到可空类型(nullable),并且不会再有非可空类型的版本。请确保您使用的所有包都支持可空类型,并且已更新到最新的稳定 Flutter 版本。

升级指南

要将旧项目升级到 V2,请确保执行以下操作:

  • 更新 Gradle 到 3.6.0+
  • 更新 Kotlin 到 1.4.31 或更高版本(可能适用于较低版本的 1.4.0+,但未经过测试)
  • msal_default_config.json 文件更新为此仓库中的最新可用版本。
  • 更新 Flutter 到最新版本。

版本 1.0.0+ 警告

版本 1.0.0 使用更新后的 MSAL 库并迁移到 Android-X。1.0.0 不兼容旧版本。仅在准备好迁移您的 Android 应用程序并更改构造函数调用时才更新到 1.0.+。

不建议使用 login.microsoftonline.com 权限和端点,因为它们似乎正在被弃用,并且由于域相同而无法分离保存的密码。新的权限模板是:

https://<tenant>.b2clogin.com/tfp/<tenant>.onmicrosoft.com/<user-flow>

例如:

https://msalfluttertest.b2clogin.com/tfp/msalfluttertest.onmicrosoft.com/B2C_1_sisu

MSAL Wrapper Library for Flutter

请注意,该产品处于非常早期的 alpha 发布阶段,可能会发生变化和出现错误。

Microsoft Authentication Library Flutter Wrapper 是一个包装器,它使用 Android 和 iOS 的 MSAL 库。当前仅支持公共客户端应用程序功能,使用隐式工作流。如果您需要额外的功能,请告诉我。

设置

Flutter

首先设置 Azure AD B2C 租户和移动客户端(如果尚未完成),详细说明可以在 Azure AD B2C 文档 中找到。

在您的 Flutter 应用程序中导入 msal_flutter 包,将其添加到 pubspec.yaml 文件的依赖项列表中:

dependencies:
    msal_flutter: ^1.0.0+2

Android (Kotlin)

确保您使用的是 Kotlin 1.4.31 或更高版本。为此,请转到应用的 android 文件夹,打开 build.gradle 文件,并在 buildscript:ext.kotlin_version 下将版本更改为 1.4.31 或更高版本。

步骤 1:确保您的 AndroidManifest.xml 包含互联网权限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

步骤 2:在 AndroidManifest.xml 文件中添加以下 intent 过滤器,替换 <YOUR-CLIENT-ID> 为您的 Azure B2C 应用程序的客户端 ID。

<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:scheme="msal<YOUR-CLIENT-ID>"
            android:host="auth" />
    </intent-filter>
</activity>

步骤 3:将 msal_default_config.json 文件从仓库复制到您的 Flutter 应用程序的 android/src/main/res/raw 文件夹中。

默认重定向 URL 是 msal<YOUR-CLIENT-ID>://auth,但如果更改了重定向 URL,则必须在步骤 2 的活动意图过滤器中也进行更改。

步骤 4:最低 SDK 版本必须至少为 21。如果从默认的 16 版本开始,请更改 android/app/build.gradle 文件中的 minSdkVersion

iOS (Swift)

步骤 1:将回调的 URL 方案添加到 Info.plist 文件中,替换 <YOUR-CLIENT-ID> 为您的 Azure B2C 应用程序的客户端 ID。

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>msauth.[BUNDLE-ID]</string>
        </array>
    </dict>
</array>

步骤 2:添加 LSApplicationQueriesSchemes 以允许调用 Microsoft Authenticator(如果已安装)。

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>msauthv2</string>
    <string>msauthv3</string>
</array>

步骤 3:在 Xcode 中打开应用的 iOS 项目,点击 Runner 应用以打开配置,在 Capabilities 中展开 Keychain Sharing 并添加 keychain 组 com.microsoft.adalcache

步骤 4:在 AppDelegate.swift 中导入 MSAL 库。

import MSAL

步骤 5:将以下函数添加到 AppDelegate 类中。

override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {    
    guard let sourceApplication = options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String else {
        return false
    }  
    return MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: sourceApplication)
}

如何使用

步骤 1:在 Flutter 中导入包

import 'package:msal_flutter/msal_flutter.dart';

步骤 2:使用静态工厂方法 createPublicClientApplication 异步创建对象的新实例,提供客户端 ID 和可选的授权。

带有默认授权:

var pca = await PublicClientApplication.createPublicClientApplication("YOUR-CLIENT-ID");

指定授权:

var pca = await PublicClientApplication.createPublicClientApplication("YOUR-CLIENT-ID", authority: "https://<tenant>.b2clogin.com/tfp/<tenant>.onmicrosoft.com/<user-flow>");

步骤 3:通过调用 acquireToken 函数获取交互式令牌,传递您希望获取令牌的作用域。

示例代码:

try{
   String token = await pca.acquireToken(["https://msalfluttertest.onmicrosoft.com/msalbackend/user_impersonation"]);
} on MsalException {
   // 错误处理逻辑
}

步骤 4:要静默获取令牌,调用 acquireTokenSilent 函数。

示例代码:

try{
    String token = await pca.acquireTokenSilent(["https://msalfluttertest.onmicrosoft.com/msalbackend/user_impersonation"]);
} on MsalException{
    // 错误处理逻辑
}

步骤 5:注销用户

示例代码:

try{
    await pca.logout();
} on MsalException{
    // 错误处理逻辑
}

示例 Demo

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:msal_flutter/msal_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static const String _authority =
      "https://msalfluttertest.b2clogin.com/tfp/3fab2993-1fec-4a8c-a6d8-2bfea01e64ea/B2C_1_phonesisu";
  static const String _redirectUri = "msauth.com.muljin.msalflutterv2://auth";
  static const String _clientId = "c3aab3bb-dd2e-4bb5-8768-38f032570a71";
  String _output = 'NONE';

  PublicClientApplication? pca;

  Future<void> _acquireToken() async {
    if (pca == null) {
      pca = await PublicClientApplication.createPublicClientApplication(
          _clientId,
          authority: _authority,
          iosRedirectUri: _redirectUri);
    }

    String res;
    try {
      res = await pca!.acquireToken(
          ["https://msalfluttertest.onmicrosoft.com/msaltesterapi/All"]);
    } on MsalUserCancelledException {
      res = "User cancelled";
    } on MsalNoAccountException {
      res = "no account";
    } on MsalInvalidConfigurationException {
      res = "invalid config";
    } on MsalInvalidScopeException {
      res = "Invalid scope";
    } on MsalException {
      res = "Error getting token. Unspecified reason";
    }

    setState(() {
      _output = res;
    });
  }

  Future<void> _acquireTokenSilently() async {
    if (pca == null) {
      pca = await PublicClientApplication.createPublicClientApplication(
          _clientId,
          redirectUri: _redirectUri,
          authority: _authority);
    }

    String res;
    try {
      res = await pca!.acquireTokenSilent(
          ["https://msalfluttertest.onmicrosoft.com/msaltesterapi/All"]);
    } on MsalUserCancelledException {
      res = "User cancelled";
    } on MsalNoAccountException {
      res = "no account";
    } on MsalInvalidConfigurationException {
      res = "invalid config";
    } on MsalInvalidScopeException {
      res = "Invalid scope";
    } on MsalException {
      res = "Error getting token silently!";
    }

    setState(() {
      _output = res;
    });
  }

  Future _logout() async {
    if (pca == null) {
      pca = await PublicClientApplication.createPublicClientApplication(
          _clientId,
          authority: _authority);
    }

    String res;
    try {
      await pca!.logout();
      res = "Account removed";
    } on MsalException {
      res = "Error signing out";
    } on PlatformException catch (e) {
      res = "some other exception ${e.toString()}";
    }

    setState(() {
      _output = res;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              ElevatedButton(
                onPressed: _acquireToken,
                child: Text('AcquireToken()'),
              ),
              ElevatedButton(
                  onPressed: _acquireTokenSilently,
                  child: Text('AcquireTokenSilently()')),
              ElevatedButton(onPressed: _logout, child: Text('Logout')),
              Text(_output),
            ],
          ),
        ),
      ),
    );
  }
}

以上内容提供了完整的示例 demo 和详细的使用说明,希望能帮助您顺利集成微软认证登录功能到 Flutter 应用中。


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

1 回复

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


当然,以下是一个关于如何在Flutter应用中使用msal_flutter插件来实现微软认证登录的示例代码。msal_flutter是Microsoft Authentication Library(MSAL)的Flutter封装,用于在Flutter应用中实现Microsoft账户的认证。

首先,确保你已经在pubspec.yaml文件中添加了msal_flutter依赖:

dependencies:
  flutter:
    sdk: flutter
  msal_flutter: ^x.y.z  # 请替换为最新版本号

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

接下来,按照以下步骤配置和使用msal_flutter插件:

  1. 配置MSAL

在你的Flutter项目的根目录下创建一个assets文件夹(如果还没有的话),并在其中创建一个名为auth_config.json的文件。这个文件包含了MSAL的配置信息,比如客户端ID、重定向URI等。

auth_config.json示例:

{
  "client_id": "YOUR_CLIENT_ID",
  "redirect_uri": "YOUR_REDIRECT_URI",
  "authorities": [
    {
      "type": "AAD",
      "audience": {
        "type": "AzureADandPersonalMicrosoftAccount",
        "tenant_id": "common"
      }
    }
  ]
}

YOUR_CLIENT_IDYOUR_REDIRECT_URI替换为你从Azure门户获取的实际值。

  1. 加载配置并初始化MSAL

在你的Flutter应用的入口文件(通常是main.dart)中,加载auth_config.json并初始化MSAL:

import 'package:flutter/material.dart';
import 'package:msal_flutter/msal_flutter.dart';
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 加载auth配置
  String authConfigJson = await rootBundle.loadString('assets/auth_config.json');
  final Map<String, dynamic> authConfigMap = jsonDecode(authConfigJson);

  // 初始化MSAL
  final PublicClientApplication pca = PublicClientApplication(
    authConfigMap['client_id']!,
    authority: Authority(
      authConfigMap['authorities'][0]['type']!,
      authConfigMap['authorities'][0]['audience']!['tenant_id']!,
    ),
    redirectUri: authConfigMap['redirect_uri']!,
  );

  runApp(MyApp(pca: pca));
}

class MyApp extends StatelessWidget {
  final PublicClientApplication pca;

  MyApp({required this.pca});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('MSAL Flutter Example'),
        ),
        body: Center(
          child: LoginButton(pca: pca),
        ),
      ),
    );
  }
}
  1. 实现登录按钮

创建一个LoginButton组件来处理用户的登录:

import 'package:flutter/material.dart';
import 'package:msal_flutter/msal_flutter.dart';

class LoginButton extends StatefulWidget {
  final PublicClientApplication pca;

  LoginButton({required this.pca});

  @override
  _LoginButtonState createState() => _LoginButtonState();
}

class _LoginButtonState extends State<LoginButton> {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        try {
          final List<String> scopes = ['User.Read'];
          final AuthenticationResult result = await widget.pca.acquireTokenInteractive(scopes);
          print('Access Token: ${result.accessToken}');
        } catch (e) {
          print('Error: $e');
        }
      },
      child: Text('Login with Microsoft'),
    );
  }
}

以上代码展示了如何在Flutter应用中使用msal_flutter插件进行微软账户的认证登录。当用户点击登录按钮时,会弹出一个Microsoft的登录界面,用户完成登录后,你将获得一个包含访问令牌的AuthenticationResult对象。

请确保你已经在Azure门户中正确配置了你的应用,包括客户端ID、重定向URI和所需的权限。此外,根据你的应用需求,你可能还需要处理令牌刷新、用户会话管理等其他功能。

回到顶部