Flutter OAuth2重定向回调插件oauth2_redirect_callback的使用
Flutter OAuth2重定向回调插件oauth2_redirect_callback的使用
简介
oauth2_redirect_callback
是一个用于简化 OAuth2 登录流程的 Flutter 插件。它通过弹窗与主窗口通信实现 OAuth2 登录,并使用 go_router
处理路由。该插件可以轻松集成到基于 oauth2_client
的应用中。
使用步骤
以下是一个完整的示例,展示如何在 Flutter 应用中使用 oauth2_redirect_callback
插件完成 OAuth2 登录。
1. 添加依赖
在 pubspec.yaml
文件中添加以下依赖:
dependencies:
flutter:
sdk: flutter
go_router: ^6.0.0
oauth2_client: ^0.8.0
oauth2_redirect_callback: ^0.1.0
然后运行 flutter pub get
安装依赖。
2. 配置路由和 OAuth2Helper
在 main.dart
中配置路由和 OAuth2Helper,确保支持 OAuth2 的授权码流程。
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:oauth2_client/oauth2_client.dart';
import 'package:oauth2_client/oauth2_helper.dart';
import 'package:oauth2_redirect_callback/oauth2_redirect_callback.dart';
import 'package:url_strategy/url_strategy.dart';
void main() {
// 设置路径 URL 策略
setPathUrlStrategy();
// 初始化应用
runApp(const MyApp());
}
// 创建 OAuth2Helper 实例
var oauth2helper = OAuth2Helper(OAuth2Client(
authorizeUrl: "https://idp.company.de/realms/master/protocol/openid-connect/auth",
tokenUrl: "https://idp.company.de/realms/master/protocol/openid-connect/token",
redirectUri: "$windowOrigin/oauth2/callback",
customUriScheme: "com.example.application:/oauth2redirect",
), clientId: "yourClientId");
// 配置路由
final GoRouter _router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) {
return const MyHomePage(title: "OAuth2 Example");
},
routes: [
GoRoute(
path: 'oauth2/callback',
builder: (BuildContext context, GoRouterState state) {
print("Callback route!");
return const OAuth2RedirectCallbackView();
},
),
],
),
],
);
3. 创建主页面
创建一个主页面,包含一个按钮用于触发 OAuth2 登录。
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
// 触发 OAuth2 登录
void _incrementCounter() async {
try {
// 获取访问令牌
var token = await oauth2helper.client.getTokenWithAuthCodeFlow(
clientId: oauth2helper.clientId,
enableState: true,
);
print("Received callback!: ${token.accessToken}");
} catch (e) {
print("Error during OAuth2 login: $e");
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('点击按钮进行 OAuth2 登录'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: '登录',
child: const Icon(Icons.login),
),
);
}
}
4. 创建回调视图
创建一个专门处理 OAuth2 回调的视图。
class OAuth2RedirectCallbackView extends StatelessWidget {
const OAuth2RedirectCallbackView({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("OAuth2 Callback"),
),
body: const Center(
child: Text("OAuth2 回调页面"),
),
);
}
}
5. 运行应用
运行应用后,点击浮动按钮触发 OAuth2 登录。浏览器会弹出授权页面,用户同意后返回回调页面并打印访问令牌。
完整示例代码
以下是完整的代码结构:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:oauth2_client/oauth2_client.dart';
import 'package:oauth2_client/oauth2_helper.dart';
import 'package:oauth2_redirect_callback/oauth2_redirect_callback.dart';
import 'package:url_strategy/url_strategy.dart';
void main() {
setPathUrlStrategy();
runApp(const MyApp());
}
var oauth2helper = OAuth2Helper(OAuth2Client(
authorizeUrl: "https://idp.company.de/realms/master/protocol/openid-connect/auth",
tokenUrl: "https://idp.company.de/realms/master/protocol/openid-connect/token",
redirectUri: "$windowOrigin/oauth2/callback",
customUriScheme: "com.example.application:/oauth2redirect",
), clientId: "yourClientId");
final GoRouter _router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) {
return const MyHomePage(title: "OAuth2 Example");
},
routes: [
GoRoute(
path: 'oauth2/callback',
builder: (BuildContext context, GoRouterState state) {
print("Callback route!");
return const OAuth2RedirectCallbackView();
},
),
],
),
],
);
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
routerConfig: _router,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() async {
try {
var token = await oauth2helper.client.getTokenWithAuthCodeFlow(
clientId: oauth2helper.clientId,
enableState: true,
);
print("Received callback!: ${token.accessToken}");
} catch (e) {
print("Error during OAuth2 login: $e");
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('点击按钮进行 OAuth2 登录'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: '登录',
child: const Icon(Icons.login),
),
);
}
}
class OAuth2RedirectCallbackView extends StatelessWidget {
const OAuth2RedirectCallbackView({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("OAuth2 Callback"),
),
body: const Center(
child: Text("OAuth2 回调页面"),
),
);
}
}
更多关于Flutter OAuth2重定向回调插件oauth2_redirect_callback的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter OAuth2重定向回调插件oauth2_redirect_callback的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中使用oauth2_redirect_callback
插件可以帮助你处理OAuth2的重定向回调。这个插件通常用于处理OAuth2授权流程中的重定向URL,以便在用户授权后获取访问令牌。
以下是使用oauth2_redirect_callback
插件的基本步骤:
1. 添加依赖
首先,你需要在pubspec.yaml
文件中添加oauth2_redirect_callback
插件的依赖:
dependencies:
flutter:
sdk: flutter
oauth2_redirect_callback: ^1.0.0 # 请使用最新版本
然后运行flutter pub get
来安装依赖。
2. 配置OAuth2重定向URL
在OAuth2提供者(如Google、Facebook等)的开发者控制台中,配置重定向URL。这个URL通常是你的应用程序的特定格式的URL,例如:
yourapp://oauth2redirect
3. 在Flutter应用中处理重定向
在Flutter应用中,你需要配置oauth2_redirect_callback
插件来处理重定向URL。
import 'package:flutter/material.dart';
import 'package:oauth2_redirect_callback/oauth2_redirect_callback.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: OAuth2RedirectCallback(
redirectUri: 'yourapp://oauth2redirect',
onAuthorizationCodeReceived: (String code) {
// 在这里处理授权码
print('Authorization Code: $code');
// 你可以使用这个授权码来获取访问令牌
},
child: Scaffold(
appBar: AppBar(
title: Text('OAuth2 Redirect Callback Example'),
),
body: Center(
child: Text('OAuth2 Redirect Callback Example'),
),
),
),
);
}
}
4. 处理授权码
在onAuthorizationCodeReceived
回调中,你将收到授权码。你可以使用这个授权码来请求访问令牌。通常,你需要向OAuth2提供者的令牌端点发送请求,以交换访问令牌。
onAuthorizationCodeReceived: (String code) async {
// 使用授权码请求访问令牌
final response = await http.post(
Uri.parse('https://oauth2-provider.com/token'),
body: {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': 'yourapp://oauth2redirect',
'client_id': 'YOUR_CLIENT_ID',
'client_secret': 'YOUR_CLIENT_SECRET',
},
);
if (response.statusCode == 200) {
// 解析响应并获取访问令牌
final Map<String, dynamic> tokenResponse = json.decode(response.body);
final String accessToken = tokenResponse['access_token'];
print('Access Token: $accessToken');
} else {
print('Failed to obtain access token');
}
},
5. 配置Android和iOS的URL Scheme
为了确保重定向URL在Android和iOS上工作,你需要在各自的配置文件中设置URL Scheme。
Android
在android/app/src/main/AndroidManifest.xml
文件中添加以下内容:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="yourapp" />
</intent-filter>
iOS
在ios/Runner/Info.plist
文件中添加以下内容:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>yourapp</string>
</array>
</dict>
</array>