You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web应用Azure SSO登录:无法获取重定向链接Fragment参数

Flutter Web Azure SSO无法获取Fragment参数解决方案

问题说明

Azure已按配置完成重定向,返回包含#code、client_info等参数的完整链接,但Flutter Web应用只能读取#之前的内容,无法获取Fragment部分的参数。

解决方法

1. 直接通过dart:html读取Fragment

Flutter Web可以借助浏览器API直接获取URL的Fragment部分,无需依赖路由框架:

import 'dart:html';

void parseRedirectParams() {
  final hash = window.location.hash;
  if (hash.isNotEmpty) {
    // 移除开头的#符号
    final paramsString = hash.substring(1);
    // 解析为键值对
    final params = Uri.splitQueryString(paramsString);
    
    // 获取所需参数
    final code = params['code'];
    final clientInfo = params['client_info'];
    final state = params['state'];
    
    // 后续的token交换逻辑
  }
}

2. 适配路由框架(如GoRouter、GetX)

如果使用了路由管理框架,可能会自动处理URL导致Fragment丢失,需要手动拦截并保留参数:
以GoRouter为例,在路由初始化时添加重定向逻辑:

import 'package:go_router/go_router.dart';
import 'dart:html';

final router = GoRouter(
  initialLocation: '/home',
  redirect: (context, state) {
    // 检查当前URL是否有Fragment但路由状态未包含
    if (window.location.hash.isNotEmpty && state.uri.fragment.isEmpty) {
      final fragment = window.location.hash.substring(1);
      // 将Fragment添加到路由URI中
      return state.uri.replace(fragment: fragment).toString();
    }
    return null;
  },
  routes: [
    // 你的路由配置
    GoRoute(
      path: '/home',
      builder: (context, state) {
        // 从state.uri.fragment获取参数
        final params = Uri.splitQueryString(state.uri.fragment);
        final code = params['code'];
        return HomePage(code: code);
      },
    ),
  ],
);

3. 验证Azure重定向配置

确保Azure门户中配置的重定向URI为http://localhost:64914/home(不要包含#),Fragment参数由Azure自动追加,无需手动配置。

4. 清除浏览器缓存测试

浏览器缓存可能导致URL解析异常,建议使用隐身模式或清除缓存后重新测试登录流程。

内容的提问来源于stack exchange,提问作者Teodora Luca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:43:46