Flutter AWS Cognito身份认证插件amazon_cognito_identity_dart_2的使用
Flutter AWS Cognito身份认证插件amazon_cognito_identity_dart_2的使用
简介
amazon_cognito_identity_dart_2
是一个非官方的Amazon Cognito Identity SDK,专门为Dart编写。它基于 amazon-cognito-identity-js
开发,并且支持Flutter应用程序中的Cognito用户池和身份验证功能。
注意: 官方推荐使用 Amplify Flutter 来进行AWS服务集成。
使用方法
初始化CognitoUserPool
import 'package:amazon_cognito_identity_dart_2/cognito.dart';
final userPool = CognitoUserPool(
'ap-southeast-1_xxxxxxxxx', // User Pool ID
'xxxxxxxxxxxxxxxxxxxxxxxxxx', // Client ID
);
注册用户
final userAttributes = [
AttributeArg(name: 'first_name', value: 'Jimmy'),
AttributeArg(name: 'last_name', value: 'Wong'),
];
var data;
try {
data = await userPool.signUp(
'email@inspire.my',
'Password001',
userAttributes: userAttributes,
);
} catch (e) {
print(e);
}
确认注册
final cognitoUser = CognitoUser('email@inspire.my', userPool);
bool registrationConfirmed = false;
try {
registrationConfirmed = await cognitoUser.confirmRegistration('123456');
} catch (e) {
print(e);
}
print(registrationConfirmed);
用户登录
final authDetails = AuthenticationDetails(
username: 'email@inspire.my',
password: 'Password001',
);
CognitoUserSession session;
try {
session = await cognitoUser.authenticateUser(authDetails);
} catch (e) {
print(e);
}
print(session.getAccessToken().getJwtToken());
获取用户属性
List<CognitoUserAttribute> attributes;
try {
attributes = await cognitoUser.getUserAttributes();
} catch (e) {
print(e);
}
attributes.forEach((attribute) {
print('attribute ${attribute.getName()} has value ${attribute.getValue()}');
});
修改密码
bool passwordChanged = false;
try {
passwordChanged = await cognitoUser.changePassword(
'oldPassword',
'newPassword',
);
} catch (e) {
print(e);
}
print(passwordChanged);
忘记密码流程
var data;
try {
data = await cognitoUser.forgotPassword();
} catch (e) {
print(e);
}
print('Code sent to $data');
// 提示用户输入验证码...
bool passwordConfirmed = false;
try {
passwordConfirmed = await cognitoUser.confirmPassword(
'123456', 'newPassword');
} catch (e) {
print(e);
}
print(passwordConfirmed);
注销用户
await cognitoUser.signOut();
全局注销(无效化所有已发令牌)
await cognitoUser.globalSignOut();
示例项目
完整示例代码可以在 GitHub仓库 中找到。以下是一个简单的Flutter应用示例:
import 'package:flutter/material.dart';
import 'package:amazon_cognito_identity_dart_2/cognito.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final userPool = CognitoUserPool(
'ap-southeast-1_xxxxxxxxx', // User Pool ID
'xxxxxxxxxxxxxxxxxxxxxxxxxx', // Client ID
);
Future<void> _login() async {
final cognitoUser = CognitoUser('email@inspire.my', userPool);
final authDetails = AuthenticationDetails(
username: 'email@inspire.my',
password: 'Password001',
);
try {
final session = await cognitoUser.authenticateUser(authDetails);
print('Login successful: ${session.getAccessToken().getJwtToken()}');
} catch (e) {
print('Login failed: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _login,
child: Text('Login'),
),
],
),
),
);
}
}
这个示例展示了如何创建一个简单的登录按钮,点击后会尝试使用提供的用户名和密码进行登录,并打印出成功或失败的信息。
其他特性
- 获取AWS凭证:可以使用此库为经过身份验证的用户提供AWS凭证。
- 签名请求:支持对S3、API Gateway等服务的签名请求。
- 自定义存储:允许使用自定义存储机制来保存用户会话信息。
- Facebook登录:可以通过Facebook OAuth获取AWS凭证。
- 客户端密钥:从版本
0.1.9
开始支持客户端密钥配置。
希望这些信息能够帮助你更好地理解和使用 amazon_cognito_identity_dart_2
插件!如果你有任何问题或需要进一步的帮助,请随时提问。
更多关于Flutter AWS Cognito身份认证插件amazon_cognito_identity_dart_2的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter AWS Cognito身份认证插件amazon_cognito_identity_dart_2的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter项目中,使用amazon_cognito_identity_dart_2
插件可以方便地集成AWS Cognito进行身份认证。以下是一个基本的示例代码,展示如何在Flutter应用中配置和使用该插件进行用户注册、登录和获取用户信息。
首先,确保你已经在pubspec.yaml
文件中添加了amazon_cognito_identity_dart_2
依赖:
dependencies:
flutter:
sdk: flutter
amazon_cognito_identity_dart_2: ^最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,是具体的代码实现。以下是一个基本的Flutter应用,包括用户注册、登录和获取用户信息的页面。
1. 配置AWS Cognito
在AWS管理控制台中配置Cognito用户池,并获取必要的配置信息,如PoolId
、ClientId
、Region
等。
2. 初始化插件
在你的Flutter项目中,创建一个服务文件(例如auth_service.dart
)来管理Cognito认证逻辑:
import 'package:amazon_cognito_identity_dart_2/amazon_cognito_identity_dart_2.dart';
import 'package:flutter/services.dart';
class AuthService {
late CognitoUserPool userPool;
late CognitoUser currentUser;
AuthService(String poolId, String clientId, String region) {
var config = CognitoUserPoolConfiguration(
userPoolId: poolId,
clientId: clientId,
region: region
);
userPool = CognitoUserPool(config);
}
Future<void> signUp(String username, String password, Map<String, String> attributes) async {
try {
var attributesMap = new HashMap<String, AttributeType>();
attributes.forEach((key, value) {
attributesMap[key] = AttributeType(value: value);
});
await userPool.signUp(username, password, attributesMap, null);
} catch (e) {
print("SignUp error: $e");
}
}
Future<void> confirmSignUp(String username, String confirmationCode, Map<String, String> attributes) async {
try {
var user = await userPool.getUser(username);
await user.confirmSignUp(confirmationCode, attributes);
currentUser = user;
} catch (e) {
print("ConfirmSignUp error: $e");
}
}
Future<void> signIn(String username, String password) async {
try {
currentUser = await userPool.signIn(username, password, null);
} catch (e) {
print("SignIn error: $e");
}
}
Future<Map<String, dynamic>> getUserAttributes() async {
if (currentUser != null) {
try {
var attributes = await currentUser.getUserAttributes();
Map<String, dynamic> userAttributes = {};
attributes.forEach((attr) {
userAttributes[attr.name] = attr.value;
});
return userAttributes;
} catch (e) {
print("GetUserAttributes error: $e");
}
}
return {};
}
Future<void> signOut() async {
if (currentUser != null) {
await currentUser.signOut();
currentUser = null;
}
}
}
3. 使用服务进行注册、登录和获取用户信息
在你的主应用文件(例如main.dart
)中,使用上述服务:
import 'package:flutter/material.dart';
import 'auth_service.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
late AuthService authService;
@override
Widget build(BuildContext context) {
String poolId = '你的PoolId';
String clientId = '你的ClientId';
String region = '你的Region';
authService = AuthService(poolId, clientId, region);
return MaterialApp(
title: 'Flutter Cognito Auth Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: AuthScreen(),
);
}
}
class AuthScreen extends StatefulWidget {
@override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
final TextEditingController _usernameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _confirmationCodeController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
void _signUp() async {
Map<String, String> attributes = {
'email': _emailController.text,
};
await widget.authService.signUp(_usernameController.text, _passwordController.text, attributes);
}
void _confirmSignUp() async {
Map<String, String> attributes = {}; // 可根据需要添加其他属性
await widget.authService.confirmSignUp(_usernameController.text, _confirmationCodeController.text, attributes);
}
void _signIn() async {
await widget.authService.signIn(_usernameController.text, _passwordController.text);
}
void _getUserAttributes() async {
var attributes = await widget.authService.getUserAttributes();
print('User Attributes: $attributes');
}
void _signOut() async {
await widget.authService.signOut();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Cognito Auth Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _usernameController,
decoration: InputDecoration(labelText: 'Username'),
),
TextField(
controller: _passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
),
TextField(
controller: _confirmationCodeController,
decoration: InputDecoration(labelText: 'Confirmation Code'),
),
TextField(
controller: _emailController,
decoration: InputDecoration(labelText: 'Email'),
),
SizedBox(height: 20),
ElevatedButton(onPressed: _signUp, child: Text('Sign Up')),
ElevatedButton(onPressed: _confirmSignUp, child: Text('Confirm Sign Up')),
ElevatedButton(onPressed: _signIn, child: Text('Sign In')),
ElevatedButton(onPressed: _getUserAttributes, child: Text('Get User Attributes')),
ElevatedButton(onPressed: _signOut, child: Text('Sign Out')),
],
),
),
);
}
}
注意事项
- 安全性:在实际应用中,不要将敏感信息(如用户名、密码等)硬编码在客户端代码中。考虑使用安全的存储机制。
- 错误处理:上述示例中的错误处理较为简单,实际应用中应增加更详细的错误处理和用户反馈。
- UI设计:上述示例的UI设计较为基础,可以根据需要进行优化和美化。
通过上述步骤,你应该能够在Flutter应用中成功集成AWS Cognito进行身份认证。