如何在Flutter Web中捕获OAuth2令牌



此依赖项据称支持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");
}
}

最终发生的是,auth令牌在最后一步显示在地址栏中。我可以在?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

有一个新的插件Flutter插件,它支持网络和移动设备上的完整身份验证流:

https://pub.dev/packages/flutter_web_auth

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

这里有一个链接到博客,它做得很好:https://aws.plainenglish.io/oauth2-in-flutter-web-using-aws-cognito-f7051be92bdf

相关内容

  • 没有找到相关文章

最新更新