Flutter身份验证插件flutter_auth0_client的使用

Flutter身份验证插件flutter_auth0_client的使用

简介

flutter_auth0 是一个非官方的 Auth0 SDK,适用于 Flutter 应用程序。

开始使用

iOS

  1. 在 iOS 目录下运行 pod install
  2. info.plist 文件中添加以下内容:
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>None</string>
        <key>CFBundleURLName</key>
        <string>auth0</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
        </array>
    </dict>
</array>

Android

main/res/values/strings.xml 文件中添加以下内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="com_auth0_client_id">
    <your auth0 client id>
  </string>
  <string name="com_auth0_domain">
      <your auth0 domain>
  </string>
</resources>

build.gradle 文件中添加以下配置:

application {
    defaultConfig {
        manifestPlaceholders += [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "<your scheme>"]
    }
}

建议你的 Scheme 使用应用的包名(例如 com.example...),这在 Android 中是必需的。

Web

index.html 文件中添加以下内容:

<script src="https://cdn.auth0.com/js/auth0-spa-js/1.12/auth0-spa-js.production.js"></script>

注意:Web 仅返回访问令牌。

登录

通过调用 FlutterAuth0.login 方法来启动登录过程。示例如下:

final Auth0Credentials credentials = await FlutterAuth0.login(
    clientId: "{YOUR AUTH0 CLIENT ID}",
    domain: "{YOUR AUTH0 DOMAIN}",
    scope: "{SCOPES}",
    scheme: "{SCHEME}" // required for android
);

在 Web 上,这将打开一个弹出窗口。TODO: 需要为 Web 添加重定向功能。

示例代码

以下是一个完整的示例代码,展示了如何在 Flutter 应用中使用 flutter_auth0_client 插件进行身份验证:

import 'package:flutter/material.dart';
import 'package:flutter_auth0_client/flutter_auth0_client.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

void main() async {
  await dotenv.load(); // 加载环境变量
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Auth0Credentials? _credentials;

  [@override](/user/override)
  void initState() {
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    final client = FlutterAuth0Client(
        clientId: dotenv.env["AUTH0_CLIENT_ID"]!, // 从环境变量中获取客户端ID
        domain: dotenv.env["AUTH0_DOMAIN"]!, // 从环境变量中获取域
        scope: "openid offline_access", // 设置作用域
        scheme: dotenv.env['AUTH0_SCHEME']); // 设置scheme(仅限Android)

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'), // 应用程序标题
        ),
        body: Center(
          child: Column(
            children: [
              ElevatedButton(
                  onPressed: () async { // 按钮点击事件
                    final credentials = await client.login(); // 调用登录方法
                    setState(() {
                      _credentials = credentials; // 更新状态
                    });
                  },
                  child: const Text("登录")), // 按钮文本
              Text(_credentials?.accessToken ?? '') // 显示访问令牌
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter身份验证插件flutter_auth0_client的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter身份验证插件flutter_auth0_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用flutter_auth0_client插件进行身份验证的示例代码。这个插件允许你使用Auth0进行身份验证和授权。

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

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

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

配置Auth0

在开始编写代码之前,请确保你已经在Auth0仪表盘上创建了一个应用,并获取了以下信息:

  • Domain
  • Client ID
  • Client Secret(如果你需要它,例如在后端API中使用)

初始化Auth0客户端

在你的Flutter应用中,创建一个Auth0客户端实例。这通常在应用的入口文件(如main.dart)中完成。

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final Auth0Client auth0 = Auth0Client(
    domain: 'YOUR_AUTH0_DOMAIN',
    clientId: 'YOUR_CLIENT_ID',
    redirectUri: Uri.parse('YOUR_REDIRECT_URI')  // 例如: Uri.parse('com.example.app:///callback')
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AuthScreen(auth0: auth0),
    );
  }
}

登录和注销

在你的AuthScreen组件中,你可以添加登录和注销按钮。

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

class AuthScreen extends StatefulWidget {
  final Auth0Client auth0;

  AuthScreen({required this.auth0});

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

class _AuthScreenState extends State<AuthScreen> {
  late AuthCredentials? credentials;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Auth0 Authentication'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            if (credentials == null) {
              ElevatedButton(
                onPressed: () async {
                  try {
                    final result = await widget.auth0.webAuthenticate();
                    if (result.isAuthenticated) {
                      setState(() {
                        credentials = result.credentials;
                      });
                      // 处理登录后的逻辑,例如保存到本地或导航到其他页面
                    }
                  } catch (e) {
                    // 处理错误
                    print('Authentication error: $e');
                  }
                },
                child: Text('Login'),
              ),
            } else {
              Text('User is authenticated'),
              ElevatedButton(
                onPressed: () async {
                  try {
                    await widget.auth0.logout();
                    setState(() {
                      credentials = null;
                    });
                    // 处理注销后的逻辑,例如返回到登录页面
                  } catch (e) {
                    // 处理错误
                    print('Logout error: $e');
                  }
                },
                child: Text('Logout'),
              ),
            },
          ],
        ),
      ),
    );
  }
}

处理回调

由于flutter_auth0_client使用了基于Web的认证流程,你需要处理重定向回调。在你的AndroidManifest.xmlInfo.plist中配置回调URI。

Android (AndroidManifest.xml)

<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="com.example.app" android:host="callback" />
</intent-filter>

iOS (Info.plist)

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>com.example.app</string>
        </array>
    </dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>auth0</string>
</array>

此外,你需要在你的应用启动时处理回调URI。这通常在你的main.dart文件中完成:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final auth0 = Auth0Client(
    domain: 'YOUR_AUTH0_DOMAIN',
    clientId: 'YOUR_CLIENT_ID',
    redirectUri: Uri.parse('YOUR_REDIRECT_URI')
  );

  // 处理回调URI
  final result = await auth0.handleAuthenticationResponse();
  if (result?.isAuthenticated == true) {
    // 用户已经通过身份验证,保存凭证
    // 例如: 将凭证保存到本地存储
  }

  runApp(MyApp(auth0: auth0));
}

这个示例代码展示了如何在Flutter应用中使用flutter_auth0_client插件进行基本的身份验证。你可以根据需要进行扩展和修改,例如添加错误处理、用户信息获取等。

回到顶部