寻求Flutter Web对接Auth0 Authorization Code Flow的可运行示例
Flutter v2 三端适配Auth0授权码模式Web端实现方案
我这里提供一个无需依赖第三方授权封装库的纯原生实现方案,完全可以跑通,和你现有移动端逻辑完全不冲突:
- 平台分支处理:入口处通过
kIsWeb常量判断运行平台,非Web端直接复用你已经跑通的移动端授权逻辑即可,Web端走专属实现 - Auth0后台配置:提前在后台配置Web应用的允许回调地址、允许登出地址、允许跨域源,本地调试时填
http://localhost:你的端口号,部署后替换为线上域名
Web端核心实现逻辑
1. 发起授权请求
import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; import 'dart:html' as html; import 'dart:convert'; void launchAuth0Login() { const clientId = "替换为你的Auth0 clientId"; const authDomain = "替换为你的Auth0域名,例如xxx.us.auth0.com"; const redirectUri = "替换为你的回调地址,本地调试填http://localhost:端口号/callback"; const scope = "openid profile email"; // 生成随机state用于后续校验,防止CSRF攻击 final state = DateTime.now().millisecondsSinceEpoch.toString(); html.window.localStorage['auth_state'] = state; final authEndpoint = Uri.https(authDomain, '/authorize', { 'response_type': 'code', 'client_id': clientId, 'redirect_uri': redirectUri, 'scope': scope, 'state': state, // 如果需要PKCE校验,在这里加上code_challenge和code_challenge_method参数即可 }); // 跳转到Auth0授权页 html.window.location.href = authEndpoint.toString(); }
2. 处理授权回调
在应用的根路由初始化逻辑里调用这个方法,处理Auth0跳转回来的回调请求:
Future<void> handleAuthCallback() async { final currentUri = Uri.parse(html.window.location.href); final code = currentUri.queryParameters['code']; final returnedState = currentUri.queryParameters['state']; final savedState = html.window.localStorage['auth_state']; // 校验state一致且拿到授权码 if (code != null && returnedState == savedState) { html.window.localStorage.remove('auth_state'); const authDomain = "替换为你的Auth0域名"; const clientId = "替换为你的Auth0 clientId"; const redirectUri = "替换为你的回调地址"; // 用授权码交换token final tokenResponse = await http.post( Uri.https(authDomain, '/oauth/token'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({ 'grant_type': 'authorization_code', 'client_id': clientId, 'redirect_uri': redirectUri, 'code': code, // 如果用了PKCE,这里加上code_verifier参数 }), ); if (tokenResponse.statusCode == 200) { final tokenResult = jsonDecode(tokenResponse.body); // 存储token到本地 html.window.localStorage['access_token'] = tokenResult['access_token']; html.window.localStorage['id_token'] = tokenResult['id_token']; // 跳转到应用首页,清理url里的授权参数 html.window.location.href = "/"; } } }
注意事项
- 如果你的Flutter Web使用的是路径路由模式,需要配置部署服务器的回退规则,保证所有访问路径都回退到index.html,避免回调页刷新404
- 登出逻辑同样可以通过拼接Auth0的登出端点参数,跳转实现,不需要依赖第三方库
内容的提问来源于stack exchange,提问作者Stephen Gibson
相关产品推荐
相关产品推荐

