我有一个flutter web应用程序,我试图实现Okta oauth2,但每当我使用DIO包调用我设法用一些参数创建的url时,我都会得到html响应,而不是实际响应。
我调用的端点看起来像这样:
https://dev-xxxxxxxx.okta.com/oauth2/default/v1/authorize?response_type=code&scope=openid+profile+offline_access&client_id=xxxxxxxxxxxxxxxxxxxx&重定向uri=http://localhost:8080/authorization-代码/回调&code_challenge_method=S256&code_challenge=Wag0u2yeYWJHy_ baK-XbMWO9H2xwUBii7R4Nvj761Y&sessionToken=20111jWBb2P2BoPIL-Add0pk5QDImstT7EmYULPFMg2GoCGPgOrxKFl&state=X7hih1mUow&nonce=lSfF1CxmmR
每当我调用此url时,它都会被重定向到另一个url,例如:
http://localhost:8080/authorization-代码/回调?code=TCifQEab0a6HwEGeWQXlDQhPm22RlyemvO5GbipASEU&state=YLi4I2P4qd
所以使用DIO的要点是它返回第二个url的响应,这是一个html flutter内容。如果DIO不遵循重定向并给出状态代码302,但它没有这样做,则可以解决这个问题。
目前我正在尝试不同的方法,我正在尝试在一个新窗口中打开url,该窗口会立即更改为第二个url。
我的问题是,我应该如何从第二个url获得代码,以及从新打开的窗口获得第二个url提供的cookie。
final html.WindowBase newWindow = html.window.open(url, "callback");
所以至少我如何才能从新打开的窗口中获得href,因为我知道它在一段时间后会变成我坐起来的正确路线。
知道newWidnow.location.href
是只写的。
好的,我设法解决了这个问题,如果有人遇到同样的问题,就留下解决方案。
在/web目录下创建一个html文件,并将其调用,例如
callback.html
。
然后将此代码粘贴到其中。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Auth</title>
<meta name="description"
content="Simple, quick, standalone responsive placeholder without any additional resources">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>Authentication Succeeded</h2>
<h3>Close this window if it didn't close by itself.</h3>
</body>
<script>
window.opener.postMessage(window.location.href, '*');
</script>
</html>
然后将重定向URI设置为如下http://localhost:8080/callback.html
因此,在这种情况下,无论何时从oauth2获得重定向URI,都会得到如下
http://localhost:8080/callback.html?code=TCifQEab0a6HwEGeWQXlDQhPm22RlyemvO5GbipASEU&state=YLi4I2P4qd
其将基本上调用新创建的html文件CCD_ 4。
在颤振侧,您需要执行以下操作:
html.WindowBase popupWindow;
popupWindow = html.window.open(
url,
"Auth",
"width=400, height=500, scrollbars=yes",
);
String? code;
html.window.onMessage.listen((event) {
if (event.data.toString().contains('code=')) {
code = event.data.toString().split('code=')[1].split('&')[0];
}
});
await Future.delayed(const Duration(seconds: 2), () {
popupWindow.close();
});
这基本上会打开窗口,然后捕获url并提取它,然后关闭窗口。
我希望这能有所帮助。
在Location
上使用assign重定向到授权服务器的Authorize端点。
window.location.assign('https://${yourOktaDomain}/oauth2/default/v1/authorize?...');