Flutter身份验证插件auth_flutter的使用

Flutter身份验证插件auth_flutter的使用

auth_flutter 是一个用于原生 Auth-Core 库(适用于 Android 和 iOS)的 Flutter 插件。

安装

首先,在 pubspec.yaml 文件中添加 auth_flutter 作为依赖项。

Android

在项目的 local.properties 文件中添加 TekoGoogleRegistryToken

// android/local.properties

TekoGoogleRegistry.password=<your-token>

在项目 build.gradle 文件中添加以下代码:

allprojects {
  repositories {
    ...

    Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream())

    maven {
      setUrl("https://asia-southeast1-maven.pkg.dev/teko-development/teko-mobile-sdks")

      authentication {
        basic(BasicAuthentication)
      }

      credentials {
        username = "_json_key_base64"
        password = properties.getProperty('TekoGoogleRegistry.password')
      }
    }
  }
}

iOS

设置 GitHub 访问令牌以访问 Teko iOS 框架:

  1. 打开终端并输入:
    touch /.bash_profile; open /.bash_profile
    
    这将打开一个文本编辑器。
  2. 添加一行:
    export GITHUB_USER_TOKEN="<your-token>"
    
  3. 保存文件并返回到终端:
    source ~/.bash_profile
    

库的使用

获取身份验证实例

静态方法:TerraAuth.getInstance(String appName) → Future

应该在应用程序初始化阶段调用,并且必须在成功初始化 TerraApp 后调用。

检查登录状态

方法:isAuthorized() -> Future<Result<bool, Exception>>

检查当前应用是否已授权。

获取访问令牌

方法:getAccessToken() -> Future<Result<IamToken, Exception>>

获取保存的访问令牌。

刷新令牌

方法:refreshToken() -> Future<Result<IamToken, Exception>>

刷新当前令牌(应在当前令牌过期后调用)。如果成功,则返回新的访问令牌。

交换令牌

方法:exchangeToken() -> Future<Result<IdToken, Exception>>

从在 IAM 控制台设置的 iamAudience 创建一个新的 id-token。

请求一次性密码 (OTP)

方法:requestOtp() -> Future<Result<Object, Exception>>

请求向特定电话号码发送 OTP 以便登录。

使用凭证登录

方法:loginWithCredential(LoginCredential credential) -> Future<Result<bool, Exception>>

有六种类型的凭证:

  • AppleCredential(应从 AppleProvider.createCredential(String accessToken) 创建)
  • FacebookCredential(应从 FacebookProvider.createCredential(String accessToken) 创建)
  • GoogleCredential(应从 GoogleProvider.createCredential(String accessToken) 创建)
  • PhoneOtpCredential(应从 PhoneOtpProvider.createCredential(String phoneNumber, String otp) 创建)
  • UsernamePasswordCredential(应从 UsernamePasswordProvider.createCredential(String username, String password) 创建)
  • CustomCredential(应从 CustomProvider.createCredential(String idToken) 创建)

直接使用 Google 登录

方法:loginWithGoogle() -> Future<Result<bool, Exception>>

直接使用 Facebook 登录

方法:loginWithFacebook() -> Future<Result<bool, Exception>>

直接使用 Apple 登录

方法:loginWithApple() -> Future<Result<bool, Exception>>

注销

方法:logout() -> Future<Result<bool, Exception>>

执行注销操作。

示例代码

import 'dart:async';

import 'package:auth_flutter/provider/custom_token_provider.dart';
import 'package:auth_flutter/provider/phone_otp_provider.dart';
import 'package:auth_flutter/provider/username_password_provider.dart';
import 'package:auth_flutter/terra_auth.dart';
import 'package:flutter/material.dart';

void main() {
  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> {
  static const _appName = "Test";
  late TerraAuth _terraAuth;
  final _phoneController = TextEditingController();
  final _otpController = TextEditingController();
  final _messangerKey = GlobalKey<ScaffoldMessengerState>();

  final _phoneVerifyController = TextEditingController();
  final _otpVerifyController = TextEditingController();

  final _emailController = TextEditingController();
  final _otpEmailController = TextEditingController();

  [@override](/user/override)
  void initState() {
    super.initState();
    _phoneController.text = "0374264438";
    initPlatformState();
  }

  // 平台消息是异步的,因此我们初始化在一个异步方法中。
  Future<void> initPlatformState() async {
    _terraAuth = await TerraAuth.getInstance(_appName);
  }

  [@override](/user/override)
  void dispose() {
    _phoneController.dispose();
    _otpController.dispose();
    _phoneVerifyController.dispose();
    _otpVerifyController.dispose();
    _emailController.dispose();
    _otpEmailController.dispose();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      scaffoldMessengerKey: _messangerKey,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(8),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.loginWithGoogle();
                          showToast("登录结果: ${result.isSuccess}");
                        },
                        child: const Text("Google 登录")),
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.loginWithFacebook();
                          showToast("登录结果: ${result.isSuccess}");
                        },
                        child: const Text("Facebook 登录")),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.loginWithApple();
                          showToast("登录结果: ${result.isSuccess}");
                        },
                        child: const Text("Apple 登录")),
                    ElevatedButton(
                        onPressed: () async {
                          final credential = UsernamePasswordProvider.createCredential(
                              "trung.cs@teko.vn", "trung123456");
                          final result = await _terraAuth.loginWithCredential(credential);
                          showToast("登录结果: ${result.isSuccess}");
                        },
                        child: const Text("用户名登录")),
                  ],
                ),
                ElevatedButton(
                    onPressed: () async {
                      final credential = CustomProvider.createCredential("idToken");
                      final result = await _terraAuth.loginWithCredential(credential);
                      showToast("登录结果: ${result.isSuccess}");
                    },
                    child: const Text("自定义凭证登录")),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Flexible(
                        flex: 1,
                        child: TextFormField(
                          controller: _phoneController,
                          decoration: const InputDecoration(
                            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 12),
                            hintText: "电话号码",
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(5.0)),
                                borderSide: BorderSide(color: Colors.blue)),
                          ),
                        )),
                    const SizedBox(
                      width: 12,
                    ),
                    Flexible(
                      flex: 1,
                      child: TextFormField(
                        controller: _otpController,
                        decoration: const InputDecoration(
                          contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 12),
                          hintText: "OTP",
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.all(Radius.circular(5.0)),
                              borderSide: BorderSide(color: Colors.blue)),
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.requestOtp(_phoneController.text.trim());
                          showToast("OTP 结果: ${result.isSuccess}");
                        },
                        child: const Text("请求 OTP")),
                    ElevatedButton(
                        onPressed: () async {
                          final credential = PhoneOtpProvider.createCredential(
                              _phoneController.text.trim(), _otpController.text.trim());
                          final result = await _terraAuth.loginWithCredential(credential);
                          showToast("登录结果: ${result.isSuccess}");
                        },
                        child: const Text("使用 OTP 登录")),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.isAuthorized();
                          showToast("已授权: ${result.getOrNull() ?? false}");
                        },
                        child: const Text("检查授权状态")),
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.logout();
                          showToast("登出: ${result.isSuccess}");
                        },
                        child: const Text("登出")),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.getAccessToken();
                          showToast(
                              "结果: ${result.isSuccess} ${result.getOrNull()?.accessToken}");
                        },
                        child: const Text("访问令牌")),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.refreshToken();
                          showToast(
                              "结果: ${result.isSuccess} ${result.getOrNull()?.accessToken}");
                        },
                        child: const Text("刷新令牌")),
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth
                              .exchangeToken("loyalty:61e08dde-9cf4-11eb-a8b3-0242ac130003");
                          showToast("结果: ${result.isSuccess} ${result.getOrNull()?.idToken}");
                        },
                        child: const Text("交换令牌")),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.getUserInfo();
                          showToast("用户: ${result.getOrNull()?.email ?? false}");
                        },
                        child: const Text("获取用户信息")),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Flexible(
                        flex: 1,
                        child: TextFormField(
                          controller: _phoneVerifyController,
                          decoration: const InputDecoration(
                            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 12),
                            hintText: "验证电话",
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(5.0)),
                                borderSide: BorderSide(color: Colors.blue)),
                          ),
                        )),
                    const SizedBox(
                      width: 12,
                    ),
                    Flexible(
                      flex: 1,
                      child: TextFormField(
                        controller: _otpVerifyController,
                        decoration: const InputDecoration(
                          contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 12),
                          hintText: "验证码",
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.all(Radius.circular(5.0)),
                              borderSide: BorderSide(color: Colors.blue)),
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.verifyPhone(_phoneVerifyController.text);
                          showToast("验证: ${result.isSuccess}");
                        },
                        child: const Text("验证电话")),
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.confirmPhone(
                              _phoneVerifyController.text, _otpVerifyController.text);
                          showToast("确认: ${result.isSuccess}");
                        },
                        child: const Text("确认电话")),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Flexible(
                        flex: 1,
                        child: TextFormField(
                          controller: _emailController,
                          decoration: const InputDecoration(
                            hintText: "验证邮箱",
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(5.0)),
                                borderSide: BorderSide(color: Colors.blue)),
                            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 12),
                          ),
                        )),
                    const SizedBox(
                      width: 12,
                    ),
                    Flexible(
                      flex: 1,
                      child: TextFormField(
                        controller: _otpEmailController,
                        decoration: const InputDecoration(
                          hintText: "验证邮箱",
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.all(Radius.circular(5.0)),
                              borderSide: BorderSide(color: Colors.blue)),
                          contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 12),
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.verifyEmail(_emailController.text);
                          showToast("验证: ${result.isSuccess}");
                        },
                        child: const Text("验证邮箱")),
                    ElevatedButton(
                        onPressed: () async {
                          final result = await _terraAuth.confirmEmail(
                              _emailController.text, _otpEmailController.text);
                          showToast("确认: ${result.isSuccess}");
                        },
                        child: const Text("确认邮箱")),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void showToast(String message) {
    _messangerKey.currentState!.showSnackBar(SnackBar(content: Text(message)));
  }
}

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

1 回复

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


当然,以下是一个关于如何使用 auth_flutter 插件进行身份验证的示例代码。请注意,auth_flutter 并不是 Flutter 社区广泛认知的一个标准插件,这里假设你指的是一个通用的身份验证插件,例如 firebase_auth,这是 Flutter 社区中非常流行的一个用于 Firebase 身份验证的插件。如果你确实指的是另一个特定的 auth_flutter 插件,请确保替换为正确的包名并参考其官方文档。

以下是一个使用 firebase_auth 插件进行身份验证的示例:

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

    dependencies:
      flutter:
        sdk: flutter
      firebase_auth: ^3.3.5  # 请检查最新版本号
      google_sign_in: ^5.2.1  # 如果需要使用 Google 登录
    
  2. 配置 Firebase: 确保你已经在 Firebase 控制台中为你的应用配置了身份验证,并下载了 google-services.json(对于 Android)和 GoogleService-Info.plist(对于 iOS)文件,并将它们放置在相应的项目目录中。

  3. 初始化 Firebase: 在你的 main.dart 文件中初始化 Firebase:

    import 'package:flutter/material.dart';
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:google_sign_in/google_sign_in.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Auth Demo',
          home: AuthScreen(),
        );
      }
    }
    
  4. 创建登录屏幕: 创建一个简单的登录屏幕,允许用户使用 Google 登录:

    class AuthScreen extends StatefulWidget {
      @override
      _AuthScreenState createState() => _AuthScreenState();
    }
    
    class _AuthScreenState extends State<AuthScreen> {
      final FirebaseAuth _auth = FirebaseAuth.instance;
      final GoogleSignIn _googleSignIn = GoogleSignIn();
    
      Future<void> _signInWithGoogle() async {
        final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
    
        if (googleUser == null) return;
    
        final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
    
        final AuthCredential credential = GoogleAuthProvider.credential(
          accessToken: googleAuth.accessToken,
          idToken: googleAuth.idToken,
        );
    
        try {
          final UserCredential authResult = await _auth.signInWithCredential(credential);
          User? user = authResult.user;
    
          // 在这里处理用户信息,例如保存到本地或导航到主页
          print('User ${user!.displayName} (${user.email}) signed in with Google.');
        } catch (e) {
          print(e.toString());
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Sign In'),
          ),
          body: Center(
            child: ElevatedButton(
              onPressed: _signInWithGoogle,
              child: Text('Sign in with Google'),
            ),
          ),
        );
      }
    }
    
  5. 处理用户登出: 如果你还想添加登出功能,可以在你的 AuthScreen 类中添加一个登出按钮:

    Future<void> _signOut() async {
      await _auth.signOut();
      await _googleSignIn.signOut();
    
      // 导航回登录屏幕或显示消息
      print('User signed out.');
    }
    
    // 在 Scaffold 的 body 中添加登出按钮
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ElevatedButton(
            onPressed: _signInWithGoogle,
            child: Text('Sign in with Google'),
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: _signOut,
            child: Text('Sign Out'),
          ),
        ],
      ),
    ),
    

请注意,这里的代码示例使用了 Google 登录作为身份验证方式。firebase_auth 插件还支持其他多种身份验证方式,如电子邮件/密码、电话认证、GitHub、Twitter 等。你可以根据需求参考 Firebase 的官方文档来集成其他身份验证方式。

回到顶部