Flutter登录认证修复插件simple_auth_flutter_login_fix的使用
Flutter登录认证修复插件simple_auth_flutter_login_fix的使用

大多数应用都需要调用API。每个API都需要身份验证,但没有开发者愿意处理身份验证。Simple Auth将身份验证嵌入到API中,这样你就无需再处理它。
这是Clancey.SimpleAuth的Dart端口的一个Flutter适配器,来自项目:Clancey.SimpleAuth。
网络/API部分(包括生成器)基于Chopper by Hadrien Lejard。
iOS:
Android:
支持的提供者
当前内置的提供者
- Azure Active Directory
- Amazon
- Dropbox
- Github
- Microsoft Live Connect
- Keycloak
- 以及任何标准的OAuth2/基本认证服务器。
使用方法
var api = new simpleAuth.GoogleApi(
"google", "client_id", clientSecret: "clientSecret",
scopes: [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile"
]);
var request = new Request(HttpMethod.Get, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json");
var userInfo = await api.send<UserInfo>(request);
就这样!如果用户未登录,系统会自动提示登录。如果用户的凭据是从之前的会话缓存的,API调用将继续进行!过期的令牌甚至可以自动刷新。
Flutter设置
导入以下包:
import 'package:simple_auth/simple_auth.dart';
import 'package:simple_auth_flutter/simple_auth_flutter.dart';
在main.dart
中调用:
SimpleAuthFlutter.init();
现在simple_auth可以自动呈现您的登录界面了。
重定向
Google需要以下重定向:com.googleusercontent.apps.YOUR_CLIENT_ID
Simple Auth默认使用iOS上的SFSafari,在Android上使用Chrome Tab。
这意味着正常的HTTP重定向无法工作。你需要为你的应用程序注册一个自定义方案作为重定向。对于大多数提供者,你可以创建任意的内容。例如:com.myapp.foo:/redirct
Android清单文件
然后在你的Android清单文件中添加以下内容:
<activity android:name="clancey.simpleauth.simpleauthflutter.SimpleAuthCallbackActivity" >
<intent-filter android:label="simple_auth">
<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.myapp.foo" />
</intent-filter>
</activity>
iOS
在iOS上,你需要在AppDelegate中添加以下内容:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
return [SimpleAuthFlutterPlugin checkUrl:url];
}
对于iOS 11及以上版本,你不需要做其他操作。对于旧版本的iOS,需要在info.plist
中添加以下内容:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>com.myapp.foo</string>
</array>
<key>CFBundleURLName</key>
<string>myappredirect</string>
</dict>
</array>
注意:如果你想避免Apple强制的用户同意对话框(例如“‘foo’ 想要使用 ‘bar.com’ 登录”),添加上述行并设置FooAuthenticator.useSSO = false;
,这将不使用SFAuthenticationSession。这是Keycloak提供者的默认行为。
序列化
JSON对象会自动序列化,如果你符合JsonSerializable
接口。
如果你使用生成器并且你的对象有工厂方法factory JsonSerializable.fromJson(Map<String, dynamic> json)
,那么你的API调用将会自动序列化/反序列化。
或者,你可以传递自己的Converter
给API并自行处理转换。
生成器
Dart
pub run build_runner build
Flutter
flutter packages pub run build_runner build
在pubspec.yaml
中添加以下内容:
dev_dependencies:
simple_auth_generator:
build_runner: ^0.8.0
生成器不是必需的,但它会让事情变得神奇!
@GoogleApiDeclaration("GoogleTestApi","client_id",clientSecret: "client_secret", scopes: ["TestScope", "Scope2"])
abstract class GoogleTestDefinition {
@Get(url: "https://www.googleapis.com/oauth2/v1/userinfo?alt=json")
Future<Response<GoogleUser>> getCurrentUserInfo();
}
这将为你生成一个新的API,使用起来非常方便!
var api = new GoogleTestApi("google");
var user = await api.getCurrentUserInfo();
更多示例,请查看示例项目。
贡献者
- 感谢由@iqbalhood制作的logo。
待办事项
- 添加更多文档。
- 为Google添加原生Flutter提供者。
完整示例代码
import 'package:flutter/material.dart';
import 'package:simple_auth/simple_auth.dart' as simpleAuth;
import 'package:simple_auth_flutter/simple_auth_flutter.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// 应用程序根节点
[@override](/user/override)
Widget build(BuildContext context) {
SimpleAuthFlutter.init(context);
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, this.title}) : super(key: key);
final String? title;
[@override](/user/override)
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
final simpleAuth.GoogleApi googleApi = new simpleAuth.GoogleApi("google",
"992461286651-k3tsbcreniknqptanrugsetiimt0lkvo.apps.googleusercontent.com",
"redirecturl",
clientSecret: "avrYAIxweNZwcHpsBlIzTp04",
scopes: [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile"
]);
void _incrementCounter() async {
var profile = await googleApi.getUserProfile();
print(profile.name);
}
[@override](/user/override)
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title!),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
更多关于Flutter登录认证修复插件simple_auth_flutter_login_fix的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter登录认证修复插件simple_auth_flutter_login_fix的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
simple_auth_flutter_login_fix
是一个用于修复 Flutter 应用中登录认证问题的插件。它基于 simple_auth
插件,提供了一些额外的功能和修复,以简化登录认证流程。以下是如何使用 simple_auth_flutter_login_fix
插件的步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 simple_auth_flutter_login_fix
插件的依赖:
dependencies:
flutter:
sdk: flutter
simple_auth_flutter_login_fix: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来获取依赖。
2. 导入插件
在你的 Dart 文件中导入插件:
import 'package:simple_auth_flutter_login_fix/simple_auth_flutter_login_fix.dart';
3. 配置认证提供者
simple_auth_flutter_login_fix
支持多种认证提供者,如 Google、Facebook、Twitter 等。你需要根据你的需求配置相应的认证提供者。
例如,配置 Google 认证:
var googleApi = new simpleAuth.GoogleApi(
"google",
"YOUR_CLIENT_ID",
"YOUR_CLIENT_SECRET",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
redirectUrl: "YOUR_REDIRECT_URL");
4. 初始化认证管理器
创建一个 SimpleAuth
实例,并添加你配置的认证提供者:
var simpleAuth = SimpleAuth();
simpleAuth.addApi(googleApi);
5. 实现登录逻辑
使用 simpleAuth
实例来实现登录逻辑。例如,使用 Google 登录:
Future<void> loginWithGoogle() async {
try {
var user = await simpleAuth.authenticate(googleApi);
print("Logged in user: ${user.toJson()}");
} catch (e) {
print("Login failed: $e");
}
}
6. 处理登录结果
在登录成功后,你可以获取用户信息并进行相应的处理。例如,将用户信息保存到本地或跳转到主页面。
7. 处理注销逻辑
你还可以实现注销逻辑:
Future<void> logout() async {
await simpleAuth.logout(googleApi);
print("User logged out");
}
8. 处理认证回调
在 main.dart
中,确保你处理了认证回调:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
navigatorKey: SimpleAuthFlutterLoginFix.navigatorKey, // 处理认证回调
);
}
}