【问题标题】:How to catch OAuth2 token in Flutter Web?如何在 Flutter Web 中捕获 OAuth2 令牌?
【发布时间】:2020-09-19 20:07:40
【问题描述】:

This dependency 应该支持 Web,但是缺少监听回调和检索令牌的实现。在过去三天的挖掘之后,一些人建议它可以使用 dart:html 库,带有 onMessage 和 postMessage 函数。

这是我的设置:

import 'dart:html' as html;
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:oauth2/oauth2.dart' as oauth2;
import 'package:url_launcher/url_launcher.dart';

class AuthYoutube {
var httpClient = http.Client();
  Future<oauth2.Client> getClient() async {
    var grant = new oauth2.AuthorizationCodeGrant(
        CLIENT_ID, AUTH_DOMAIN, AUTH_TOKEN,
        secret: secret);
    var authorizationUrl =
        grant.getAuthorizationUrl(REDIRECT_URI, scopes: scopes);

    html.window.open(authorizationUrl.toString(), "open");
    Completer<LinkedHashMap<dynamic, dynamic>> completer = Completer();
    html.window.onMessage.listen((event) async {
      completer.complete(event.data as LinkedHashMap<dynamic, dynamic>);
    });
    Uri responseUri;
    completer.future.then((value) {
      responseUri = Uri.parse(value.toString());
      return grant.handleAuthorizationResponse(responseUri.queryParameters);
    });
  }

} 并将单独的路由设置为回调 URL:

class Special extends StatelessWidget {
  static String route = "/special";
  @override
  Widget build(BuildContext context) {
    final loc = Uri.parse(html.window.location.href);
    final code = loc.queryParameters["code"];
    print("code $code");
    html.window.postMessage(code, html.window.location.origin);
    return Text("All done");
  }
}

最终发生的情况是身份验证令牌在最后一步出现在地址栏中。我可以在?code= 之后看到它,但它没有被打印出来。 listen 方法在整个流程中被触发 5-6 次(同时在另一个窗口中单击“允许”)。在控制台中,我只收到一个错误:

Uncaught (in promise) Error: Bad state: Future already completed
    at Object.throw_ [as throw] (errors.dart:212)
    at _AsyncCompleter.new.complete (future_impl.dart:43)
    at authYT.dart:41
    at Generator.next (<anonymous>)
    at runBody (async_patch.dart:84)
    at Object._async [as async] (async_patch.dart:123)
    at authYT.dart:40
    at Object._checkAndCall (operations.dart:324)
    at Object.dcall (operations.dart:329)
    at html_dart2js.dart:37246

【问题讨论】:

  • 我有同样的问题要解决,谢谢!如果'$code'不能打印出来,可以设置成cookie或本地存储吗?
  • 你是如何为你的 SpecialPage 实现导航的,通常当你重定向到你的 Flutter Web 应用程序时,即使你提到了一个特定的 URL,它也会从头开始加载所有内容。
  • 你搞定了吗?我有一个类似的问题。其他 cmets 中的链接页面看起来很有希望,但最终没有足够的细节,或者代码甚至无法编译。

标签: flutter dart oauth-2.0 flutter-dependencies flutter-web


【解决方案1】:

您可以通过URL在onGenerateRoute方法中获取访问令牌。

这里有一个链接到正确的博客:https://aws.plainenglish.io/oauth2-in-flutter-web-using-aws-cognito-f7051be92bdf

【讨论】:

  • 感谢您的文章。如何使用此方法传递 Cognito 用户名和密码?
  • 您将能够通过 Cognito 托管 UI 传递用户名和密码,当应用程序在按下登录后定向到身份验证 URL 时,该 UI 将呈现给您。这让我意识到我应该在其中添加视觉辅助那个博客。很快就会更新?
猜你喜欢
  • 1970-01-01
  • 2021-01-05
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 2013-07-29
  • 2016-04-19
  • 2012-06-20
相关资源
最近更新 更多