如何解决如何在Flutter Web中捕获OAuth2令牌?
This dependency应该支持Web,但是缺少用于侦听回调和检索令牌的实现。经过三天的研究后,一些人建议它可以使用带有onMessage和postMessage函数的dart:html库工作。
这是我的设置:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。