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

Flutter/Dart中通过OAuth2生成Access Token返回Null问题

问题分析与修复方案

1. 重定向失败的核心原因:错误的redirectUri配置

你当前使用的https://oauth.pstmn.io/v1/browser-callback是Postman的回调地址,无法关联到你的Flutter应用,自然无法自动跳转回来。必须使用自定义URL Scheme作为redirectUri,步骤如下:

配置自定义URL Scheme

  • 先确定你的自定义Scheme,比如myflutterapp://auth(可替换为你的专属标识)
  • 修改OAuth2Client配置:
    OAuth2Client client = OAuth2Client(
        redirectUri: 'myflutterapp://auth',
        customUriScheme: 'myflutterapp', // 和Scheme前缀保持一致
        authorizeUrl: 'https://login.microsoftonline.com/${tenantID}/oauth2/authorize',
        tokenUrl: 'https://login.microsoftonline.com/${tenantID}/oauth2/token',
    );
    

配置Android端支持

在android/app/src/main/AndroidManifest.xml的<activity>标签内添加intent filter:

<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="myflutterapp" />
</intent-filter>

配置iOS端支持

在ios/Runner/Info.plist中添加:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>myflutterapp</string>
        </array>
    </dict>
</array>

2. Access Token为Null的关键问题

移除ClientSecret(移动端无需此参数)

Azure AD中,移动端属于公共客户端,不需要clientSecret,传递该参数会导致授权流程异常,直接删除clientSecret: '${clientSecret}'这一行。

修正Scope格式

你的Scopeapi://${tenantID}/Users.Login格式错误,正确格式应为api://{client-id}/{scope-name},其中client-id是你Azure AD应用的客户端ID,不是租户ID。修改为:

scopes: ['api://${clientID}/Users.Login'],

修正属性调用方式

AccessTokenResponse的属性并非异步对象,不需要用await调用,之前的await tknResp.tokenType会导致不必要的异步等待,直接获取即可。

3. 修复后的完整代码示例

OAuth2Client client = OAuth2Client(
  redirectUri: 'myflutterapp://auth',
  customUriScheme: 'myflutterapp',
  authorizeUrl: 'https://login.microsoftonline.com/${tenantID}/oauth2/authorize',
  tokenUrl: 'https://login.microsoftonline.com/${tenantID}/oauth2/token',
);

try {
  AccessTokenResponse tknResp = await client.getTokenWithAuthCodeFlow(
    clientId: '${clientID}',
    scopes: ['api://${clientID}/Users.Login'],
  );
  print("TOKEN IS: ${tknResp.tokenType} ${tknResp.scope} ${tknResp.accessToken}");
} catch(e) {
  print("TOKEN ERROR IS: ${e}");
}

额外注意事项

  • 务必在Azure AD应用的认证面板中,将自定义Scheme添加为"移动和桌面应用"的重定向URI
  • 测试前重启模拟器/真机,确保配置生效
  • 确认tenantID配置正确:单租户用具体租户ID,多租户用common或organizations

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:12:42