【发布时间】: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,它也会从头开始加载所有内容。
-
还有github.com/MaikuB/flutter_appauth/issues/… 带有示例 ZIP
-
你搞定了吗?我有一个类似的问题。其他 cmets 中的链接页面看起来很有希望,但最终没有足够的细节,或者代码甚至无法编译。
标签: flutter dart oauth-2.0 flutter-dependencies flutter-web