Flutter认证授权插件unpub_auth的使用
Flutter认证授权插件unpub_auth的使用
unpub_auth
仅支持Dart 2.15及以上版本。
从Dart 2.15开始:
<code>accessToken</code>
只会发送到https://pub.dev 和 https://pub.dartlang.org。详情请查看 dart-lang/pub #3007。- 自Dart 2.15起,第三方pub的令牌存储在路径
<code>/Users/username/Library/Application Support/dart/pub-tokens.json</code>
(macOS)。
因此,自托管的pub服务器应具有自己的身份验证流程。默认情况下,unpub使用Google OAuth2。
- 执行
<code>unpub_auth login</code>
后,开发者登录<code>unpub_auth</code>
,将在本地生成<code>unpub-credentials.json</code>
文件。 - 在调用
<code>dart pub publish</code>
或<code>flutter pub publish</code>
之前,请先执行<code>unpub_auth get | dart pub token add <self-hosted-pub-server></code>
。 <code>unpub_auth get</code>
会刷新令牌,新的<code>accessToken</code>
将通过<code>dart pub token add <self-hosted-pub-server></code>
写入到<code>pub-tokens.json</code>
中。- 这样,你可以在
<code>dart pub publish</code>
和<code>flutter pub publish</code>
中始终使用有效的<code>accessToken</code>
。
使用概述
unpub 默认使用Google OAuth2。unpub_auth
的使用有两种常见情况:
-
本地登录并发布pub包:
- 第一次使用时,执行
<code>unpub_auth login</code>
,它将保存本地凭据。 - 在调用
<code>dart pub publish</code>
或<code>flutter pub publish</code>
之前,执行<code>unpub_auth get | dart pub token add <self-hosted-pub-server></code>
。
- 第一次使用时,执行
-
本地登录并在CI/CD中发布pub包:
- 在CI/CD设备上,可能没有机会执行
<code>unpub_auth login</code>
,因此可以使用<code>unpub_auth migrate</code>
来迁移凭据文件。 - 在本地设备上,第一次使用时执行
<code>unpub_auth login</code>
,它将保存本地凭据。 - 将第一步生成的凭据文件复制到CI/CD设备。
- 在CI/CD设备上,执行
<code>unpub_auth migrate <credentials-file-path></code>
,这样CI/CD设备将拥有相同的凭据文件。 - 在CI/CD设备上,在调用
<code>dart pub publish</code>
或<code>flutter pub publish</code>
之前,执行<code>unpub_auth get | dart pub token add <self-hosted-pub-server></code>
。
- 在CI/CD设备上,可能没有机会执行
Usage: unpub_auth <command> [arguments]
Available commands:
get 刷新并获取 accessToken。必须先登录。
login 在Google API上登录 unpub_auth。
logout 删除本地的凭据文件。
migrate <path> 从路径迁移已存在的凭据文件。
安装与运行
dart pub global activate unpub_auth # 激活命令行工具
卸载
dart pub global deactivate unpub_auth # 禁用命令行工具
获取令牌并导出到Dart客户端
unpub_auth get | dart pub token add <self-hosted-pub-server>
注意:在运行 <code>unpub_auth get</code>
之前,请确保已在终端中执行过 <code>unpub_auth login</code>
。
本地开发与调试
dart pub global activate --source path ./ # 激活命令行工具
unpub_auth # 运行它
更多关于Flutter认证授权插件unpub_auth的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter认证授权插件unpub_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
unpub_auth
是一个用于 Flutter 应用的认证和授权插件,通常用于在应用中处理用户登录、注册、权限管理等操作。它可以帮助开发者快速集成认证和授权功能,而不需要从头开始实现这些功能。
安装
首先,你需要在 pubspec.yaml
文件中添加 unpub_auth
插件的依赖:
dependencies:
flutter:
sdk: flutter
unpub_auth: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来安装依赖。
基本使用
1. 初始化插件
在使用 unpub_auth
之前,通常需要对其进行初始化。你可以在应用的 main.dart
文件中进行初始化:
import 'package:unpub_auth/unpub_auth.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化 unpub_auth
await UnpubAuth.initialize(
authUrl: 'https://your-auth-server.com',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'your-redirect-uri',
);
runApp(MyApp());
}
2. 用户登录
你可以使用 UnpubAuth
提供的 login
方法来处理用户登录:
Future<void> login() async {
try {
await UnpubAuth.login(
username: 'user@example.com',
password: 'password',
);
print('Login successful!');
} catch (e) {
print('Login failed: $e');
}
}
3. 用户注册
unpub_auth
也提供了用户注册的功能:
Future<void> register() async {
try {
await UnpubAuth.register(
email: 'user@example.com',
password: 'password',
username: 'username',
);
print('Registration successful!');
} catch (e) {
print('Registration failed: $e');
}
}
4. 检查用户是否已登录
你可以使用 UnpubAuth.isLoggedIn
来检查用户是否已经登录:
bool isLoggedIn = await UnpubAuth.isLoggedIn();
if (isLoggedIn) {
print('User is logged in');
} else {
print('User is not logged in');
}
5. 获取用户信息
登录成功后,你可以通过 UnpubAuth.getUserInfo
获取用户信息:
Map<String, dynamic> userInfo = await UnpubAuth.getUserInfo();
print('User info: $userInfo');
6. 用户登出
用户登出可以通过 UnpubAuth.logout
方法来实现:
Future<void> logout() async {
await UnpubAuth.logout();
print('User logged out');
}
高级用法
1. 自定义授权流程
unpub_auth
也支持自定义授权流程,你可以使用 UnpubAuth.authorize
方法来处理 OAuth2 授权流程:
Future<void> authorize() async {
final authResult = await UnpubAuth.authorize(
scopes: ['read', 'write'],
);
print('Authorization result: $authResult');
}
2. 刷新 Token
如果你的应用需要长时间保持用户登录状态,你可能需要定期刷新 Token。unpub_auth
提供了 refreshToken
方法:
Future<void> refreshToken() async {
try {
await UnpubAuth.refreshToken();
print('Token refreshed successfully');
} catch (e) {
print('Failed to refresh token: $e');
}
}
注意事项
- 安全性:确保你在生产环境中使用 HTTPS 来保护用户数据。
- 错误处理:在实际应用中,建议对所有的 API 调用进行错误处理,以便在出现问题时能够给出友好的提示。
- Token 管理:Token 是用户认证的关键,确保你的应用能够正确处理 Token 的存储和刷新。
示例应用
以下是一个简单的示例应用,展示了如何使用 unpub_auth
进行用户登录和登出:
import 'package:flutter/material.dart';
import 'package:unpub_auth/unpub_auth.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await UnpubAuth.initialize(
authUrl: 'https://your-auth-server.com',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'your-redirect-uri',
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: AuthScreen(),
);
}
}
class AuthScreen extends StatefulWidget {
[@override](/user/override)
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
bool _isLoggedIn = false;
[@override](/user/override)
void initState() {
super.initState();
_checkLoginStatus();
}
Future<void> _checkLoginStatus() async {
bool isLoggedIn = await UnpubAuth.isLoggedIn();
setState(() {
_isLoggedIn = isLoggedIn;
});
}
Future<void> _login() async {
try {
await UnpubAuth.login(
username: 'user@example.com',
password: 'password',
);
setState(() {
_isLoggedIn = true;
});
} catch (e) {
print('Login failed: $e');
}
}
Future<void> _logout() async {
await UnpubAuth.logout();
setState(() {
_isLoggedIn = false;
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Auth Demo'),
),
body: Center(
child: _isLoggedIn
? ElevatedButton(
onPressed: _logout,
child: Text('Logout'),
)
: ElevatedButton(
onPressed: _login,
child: Text('Login'),
),
),
);
}
}