Flutter身份验证插件netlify_auth的使用

Flutter身份验证插件netlify_auth的使用

gotrue-dart library

这是用于Netlify身份验证服务的Dart客户端库。它允许您创建和认证用户,并为注册、密码恢复、登录和注销等功能构建UI。

您可以在此处试用方法:示例站点


安装

要使用此插件,请在pubspec.yaml文件中添加netlify_auth作为依赖项:

$ flutter pub add netlify_auth

使用

首先,导入netlify_auth包并初始化GoTrue实例:

import 'package:netlify_auth/netlify_auth.dart';

// 实例化带有GoTrueInit配置的GoTrue认证客户端
GoTrue auth = GoTrue(
  GoTrueInit(
    APIUrl: 'https://brave-colden-1959c1.netlify.app/.netlify/identity', // 替换为您的Netlify站点的API URL
    setCookie: true, // 设置为true以实现“记住我”功能
  ),
);

GoTrue配置

APIUrl

GoTrue端点的绝对路径。要找到APIUrl,请转到Netlify站点仪表板中的Identity页面。

audience(可选)

audience是预定义的JWT负载声明之一。这是一个可选属性,默认为空。如果您正在托管自己的身份服务并希望支持多租户,则需要audience来分离用户。

setCookie(可选)

默认值为false。如果希望实现“记住我”功能,请将其设置为true


认证示例

创建新用户

通过指定电子邮件和密码创建新用户:

auth.signup(email, password);

示例用法:

auth
  .signup(email, password)
  .then(response => debugPrint("Confirmation email sent"))
  .catchError(error => debugPrint("It's an error"));

示例响应对象:

User (
  id: 'example-id',
  aud: '',
  role: '',
  email: 'example@example.com',
  confirmation_sent_at: '2018-04-27T22:36:59.636416916Z',
  app_metadata: { provider: 'email' },
  user_metadata: null,
  created_at: '2018-04-27T22:36:59.632133283Z',
  updated_at: '2018-04-27T22:37:00.061039863Z'
)

确保在Netlify仪表板中的Identity settings下的Registration preferences设置为Open

如果Registration preferences设置为Invite only,您会收到如下错误消息:

{code: 403, msg: 'Signups not allowed for this instance'}

确认新用户注册

通过唯一的确认令牌确认用户注册:

auth.confirm(confirmationLink);

当新用户注册时,如果未启用Autoconfirm,系统会向用户发送一封包含确认链接的邮件。

邮件中有一个链接,写着“确认您的电子邮件地址”。当用户点击该链接时,会重定向到站点,并在URL中包含一个片段标识符#confirmation_token=Iyo9xHvsGVbW-9A9v4sDmQ

如果要确认用户,请使用auth.confirm(confirmationLink)

示例用法:

auth
  .confirm(confirmationLink)
  .then((response) {
    debugPrint("Confirmation email sent"));
  })
  .catchError((e) {
    debugPrint(e.toString());
  });

检查已确认的用户

检查用户的确认状态并返回布尔值:

user.isConfirmed

示例用法:

if (user.isConfirmed) {
    Navigator.push(context,
        MaterialPageRoute(
            builder: (context) => const Dashboard()));
} else {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => const ConfirmationPage()));
}

用户登录

通过指定的电子邮件和密码处理用户登录:

auth.login(email, password)

示例用法:

auth
  .login(email.value, password.value)
  .then(response => showMessage("Success! Response: " , form))
  .catchError(error => showMessage("Failed"));

示例响应对象:

User(
    api: {
      "apiURL": "https://example.netlify.com/.netlify/identity",
      "_sameOrigin": true,
      "defaultHeaders": {}
    },
    url: "https://example.netlify.com/.netlify/identity",
    toke: Token(
      access_token: "example-jwt-token",
      token_type: "bearer",
      expires_in: 3600,
      refresh_token: "example-refresh_token",
      expires_at: 1526062471000
    ),
    id: "example-id",
    aud: "",
    role: "",
    email: "example@netlify.com",
    confirmed_at: "2018-05-04T23:57:17Z",
    app_metadata: {
      "provider": "email"
    },
    user_metadata: {},
    created_at: "2018-05-04T23:57:17Z",
    updated_at: "2018-05-04T23:57:17Z"
  
)

请求密码恢复邮件

通过指定电子邮件地址发送密码恢复请求:

auth.requestPasswordRecovery(email)

示例用法:

auth
  .requestPasswordRecovery(email)
  .then(response => debugPrint("Recovery email sent"))
  .catchError(error => debugPrint("Error sending recovery mail"));

示例响应对象:

{}

恢复用户账户

通过恢复令牌恢复用户账户:

auth.recover(recoveryLink)

示例用法:

auth
  .recover(recoveryLink)
  .then(response =>
    debugPrint("Logged in as %s")
  )
  .catchError(error => debugPrint("Failed to verify recovery token"));

示例响应对象:

User(
    api: {
      "apiURL": "https://example.netlify.com/.netlify/identity",
      "_sameOrigin": true,
      "defaultHeaders": {}
    },
    url: "https://example.netlify.com/.netlify/identity",
    toke: Token(
      access_token: "example-jwt-token",
      token_type: "bearer",
      expires_in: 3600,
      refresh_token: "example-refresh_token",
      expires_at: 1526062471000
    ),
    id: "example-id",
    aud: "",
    role: "",
    email: "example@netlify.com",
    confirmed_at: "2018-05-04T23:57:17Z",
    app_metadata: {
      "provider": "email"
    },
    user_metadata: {},
    created_at: "2018-05-04T23:57:17Z",
    updated_at: "2018-05-04T23:57:17Z"
  
)

获取当前用户

当用户登录时,获取当前用户对象:

final user = auth.currentUser();

示例响应对象:

User(
    api: {
      "apiURL": "https://example.netlify.com/.netlify/identity",
      "_sameOrigin": true,
      "defaultHeaders": {}
    },
    url: "https://example.netlify.com/.netlify/identity",
    toke: Token(
      access_token: "example-jwt-token",
      token_type: "bearer",
      expires_in: 3600,
      refresh_token: "example-refresh_token",
      expires_at: 1526062471000
    ),
    id: "example-id",
    aud: "",
    role: "",
    email: "example@netlify.com",
    confirmed_at: "2018-05-04T23:57:17Z",
    app_metadata: {
      "provider": "email"
    },
    user_metadata: {},
    created_at: "2018-05-04T23:57:17Z",
    updated_at: "2018-05-04T23:57:17Z"
)

更新用户

通过指定属性更新用户对象:

user.update(attributes)

示例用法:

const user = auth.currentUser();

user
  .update({ email: "example@example.com", password: "password" })
  .then(user => debugPrint("Updated user"))
  .catchError((error) {
    debugPrint("Failed to update user");
    rethrow;
  );

示例响应对象:

User(
    api: {
      "apiURL": "https://example.netlify.com/.netlify/identity",
      "_sameOrigin": true,
      "defaultHeaders": {}
    },
    url: "https://example.netlify.com/.netlify/identity",
    toke: Token(
      access_token: "example-jwt-token",
      token_type: "bearer",
      expires_in: 3600,
      refresh_token: "example-refresh_token",
      expires_at: 1526062471000
    ),
    id: "example-id",
    aud: "",
    role: "",
    email: "example@netlify.com",
    confirmed_at: "2018-05-04T23:57:17Z",
    app_metadata: {
      "provider": "email"
    },
    user_metadata: {},
    created_at: "2018-05-04T23:57:17Z",
    updated_at: "2018-05-04T23:57:17Z"
  
)

获取JWT令牌

从当前登录的用户检索JWT令牌:

user.jwt()

示例用法:

const user = auth.currentUser();
const jwt = user.jwt();
jwt
  .then(response => debugPrint("This is a JWT token"))
  .catchError((error) {
    debugPrint("Error fetching JWT token");
    rethrow;
  });

示例响应对象:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MjUyMTk4MTYsInN1YiI6ImE5NG.98YDkB6B9JbBlDlqqef2nme2tkAnsi30QVys9aevdCw debugger eval code:1:43

注销用户

移除用户的当前会话并注销用户:

user.logout()

示例用法:

const user = auth.currentUser();
user
  .logout()
  .then(response => debugPrint("User logged out"))
  .catchError((error){
    debugPrint("Failed to logout user");
    rethrow;
  });

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

1 回复

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


netlify_auth 是一个用于在 Flutter 应用中集成 Netlify 身份验证的插件。它允许你轻松地与 Netlify 的身份验证服务进行交互,从而实现用户登录、注册、注销等功能。以下是如何在 Flutter 项目中使用 netlify_auth 插件的步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  netlify_auth: ^0.1.0  # 请确认使用最新版本

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

2. 配置 Netlify 身份验证

在 Netlify 控制台中,确保你已经启用了身份验证功能,并且配置了相应的身份提供者(如 GitHub、Google、GitLab 等)。你还需要在 Netlify 中设置回调 URL,以便在用户完成身份验证后重定向回你的 Flutter 应用。

3. 初始化 netlify_auth

在你的 Flutter 应用中,初始化 netlify_auth 插件。通常,你可以在 main.dart 文件中进行初始化:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await NetlifyAuth.init(
    siteId: 'YOUR_NETLIFY_SITE_ID',  // 你的 Netlify Site ID
    baseUrl: 'https://YOUR_NETLIFY_SITE_URL',  // 你的 Netlify 站点 URL
  );
  runApp(MyApp());
}

4. 实现登录功能

在你的应用中,你可以使用 NetlifyAuth.signInWithProvider 方法来启动登录流程。例如,使用 GitHub 作为身份提供者:

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

class LoginPage extends StatelessWidget {
  Future<void> _signInWithGitHub(BuildContext context) async {
    try {
      final user = await NetlifyAuth.signInWithProvider(NetlifyProvider.github);
      print('User: ${user.email}');
      // 登录成功后的操作,例如导航到主页
      Navigator.pushReplacementNamed(context, '/home');
    } catch (e) {
      print('Error: $e');
      // 处理登录失败的情况
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () => _signInWithGitHub(context),
          child: Text('Sign in with GitHub'),
        ),
      ),
    );
  }
}

5. 处理用户会话

你可以使用 NetlifyAuth.currentUser 方法来获取当前登录的用户信息,并在应用启动时检查用户是否已经登录:

class HomePage extends StatelessWidget {
  Future<void> _checkUserSession(BuildContext context) async {
    final user = await NetlifyAuth.currentUser;
    if (user == null) {
      Navigator.pushReplacementNamed(context, '/login');
    } else {
      print('User: ${user.email}');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    _checkUserSession(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: Text('Welcome!'),
      ),
    );
  }
}

6. 实现注销功能

你可以使用 NetlifyAuth.signOut 方法来注销当前用户:

class ProfilePage extends StatelessWidget {
  Future<void> _signOut(BuildContext context) async {
    await NetlifyAuth.signOut();
    Navigator.pushReplacementNamed(context, '/login');
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Profile'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () => _signOut(context),
          child: Text('Sign Out'),
        ),
      ),
    );
  }
}
回到顶部