Flutter网页授权插件url_auth_web的使用

本文档将详细介绍如何在Flutter Web项目中使用url_auth_web插件来实现OAuth2认证流程。


第一步

首先,我们需要调用插件打开认证URL。以下是基本的使用方法:

await UrlAuthWeb().launch(url);
// 可以通过传递字符串参数来配置窗口行为
// 也可以传递名称参数来处理浏览器行为

说明

  • launch(url) 方法用于打开指定的认证URL。
  • 可选参数可以用来配置窗口的行为(如窗口大小、是否可调整等)。

第二步(可选)

为了确保认证完成后能够正确返回到应用,你需要在项目的web/auth.html文件中添加一个页面,用于接收服务器的重定向并解析JWT令牌。

创建web/auth.html文件

在你的Flutter项目的web目录下创建一个名为auth.html的文件,并添加以下内容:

<!DOCTYPE html>
<title>认证完成</title>
<p>
  认证已完成。如果此过程未自动完成,请关闭窗口。
  <script>
    // 获取URL中的查询参数
    const url = new URL(window.location.href);
    const code = url.searchParams.get("jwt"); // 获取JWT令牌
    const redirectUrl = new URL(`${url.origin}`); // 获取当前域名
    const page = "/#/auth"; // 设置跳转路径
    window.location = `${redirectUrl.href}${page}?jwt=${code}`;
    // 将页面跳转到应用内的指定路径
  </script>
</p>

注意

  • 如果你已经配置了服务器端的重定向逻辑,可以忽略这一步。
  • 该文件的作用是捕获认证后的回调,并将JWT令牌传递给Flutter应用。

第三步

在你的应用的认证页面中,使用getUrlParams()方法获取查询参数并进行处理。

await UrlAuthWeb().getQueryParams();
/* 
此方法返回查询参数作为Map<String, dynamic>,例如:
{
    'jwt': {{jwt}}
}
*/

说明

  • getQueryParams() 方法用于从URL中提取查询参数。
  • 返回值是一个Map<String, dynamic>对象,其中包含认证成功后返回的JWT令牌。

完整示例代码

以下是一个完整的示例代码,展示了如何在Flutter Web中使用url_auth_web插件进行OAuth2认证。

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

import 'package:flutter/services.dart';
import 'package:url_auth_web/url_auth_web.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _urlAuthWebPlugin = UrlAuthWeb();

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  // 初始化平台状态
  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      // 调用插件获取平台版本
      platformVersion = await _urlAuthWebPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  // 打开认证URL
  void authenticate() async {
    final url = "https://your-auth-server.com/oauth2/authorize"; // 替换为实际的认证URL
    await _urlAuthWebPlugin.launch(url);
  }

  // 获取查询参数
  void getQueryParams() async {
    final params = await _urlAuthWebPlugin.getQueryParams();
    print('查询参数: $params');
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('URL Auth Web 示例'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
            ElevatedButton(
              onPressed: authenticate,
              child: Text('开始认证'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: getQueryParams,
              child: Text('获取查询参数'),
            ),
            SizedBox(height: 20),
            Text('运行于: $_platformVersion'),
          ],
        )),
      ),
    );
  }
}

更多关于Flutter网页授权插件url_auth_web的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网页授权插件url_auth_web的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


url_auth_web 是一个用于在 Flutter Web 应用中处理 URL 授权的插件。它可以帮助你在 Flutter Web 应用中处理 OAuth 2.0 授权流程,例如从第三方服务(如 Google、Facebook 等)获取访问令牌。

以下是如何使用 url_auth_web 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  url_auth_web: ^0.0.1  # 请使用最新版本

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

2. 配置授权 URL

你需要配置授权 URL,通常这是由第三方服务提供的。例如,Google OAuth 2.0 的授权 URL 可能如下:

const authUrl = 'https://accounts.google.com/o/oauth2/auth';

3. 使用 url_auth_web 插件

接下来,你可以在 Flutter 应用中使用 url_auth_web 插件来处理授权流程。

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('URL Auth Web Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              const clientId = 'YOUR_CLIENT_ID';
              const redirectUri = 'https://your-redirect-uri.com';
              const scope = 'email profile';

              final authUrl = 'https://accounts.google.com/o/oauth2/auth'
                  '?response_type=code'
                  '&client_id=$clientId'
                  '&redirect_uri=$redirectUri'
                  '&scope=$scope';

              try {
                final result = await UrlAuthWeb.launch(authUrl);
                print('Authorization result: $result');
              } catch (e) {
                print('Error: $e');
              }
            },
            child: Text('Authorize with Google'),
          ),
        ),
      ),
    );
  }
}

4. 处理授权结果

UrlAuthWeb.launch 方法会打开一个新的浏览器窗口或标签页,用户将在其中完成授权流程。授权完成后,用户将被重定向到你指定的 redirect_uri,并且 UrlAuthWeb.launch 方法将返回授权结果。

你可以根据返回的结果(如授权码)继续完成 OAuth 2.0 的流程,例如获取访问令牌。

5. 获取访问令牌

通常,你需要将授权码发送到你的后端服务器,或者直接在客户端使用 http 包来获取访问令牌。例如:

import 'package:http/http.dart' as http;

Future<void> getAccessToken(String authorizationCode) async {
  const tokenUrl = 'https://oauth2.googleapis.com/token';
  const clientId = 'YOUR_CLIENT_ID';
  const clientSecret = 'YOUR_CLIENT_SECRET';
  const redirectUri = 'https://your-redirect-uri.com';

  final response = await http.post(
    Uri.parse(tokenUrl),
    body: {
      'code': authorizationCode,
      'client_id': clientId,
      'client_secret': clientSecret,
      'redirect_uri': redirectUri,
      'grant_type': 'authorization_code',
    },
  );

  if (response.statusCode == 200) {
    final accessToken = jsonDecode(response.body)['access_token'];
    print('Access Token: $accessToken');
  } else {
    print('Error getting access token: ${response.body}');
  }
}
回到顶部