我正在实现 Fastapi oauth2 隐式流程,在实现时我能够从 azure ad 接收访问令牌,但是访问令牌不会在后续 api 中传递。
我还可以看到存储在浏览器本地存储中的访问令牌,但是在我后续的api请求中,accessToken并未在curl url中传递
curl url 是这样形成的
curl -X 'GET' \
'http://localhost:8000/protected' \
-H 'accept: application/json'
现在在招摇重定向逻辑中我有这样的html
html = """
<!doctype html>
<html lang="en-US">
<head>
<title>Swagger UI: OAuth2 Redirect</title>
</head>
<body>
<script>
'use strict';
function run() {
var oauth2 = window.opener.swaggerUIRedirectOauth2;
var sentState = oauth2.state;
var redirectUrl = oauth2.redirectUrl;
var isValid, qp, arr;
// Extract the query parameters from the URL fragment
var fragment = window.location.hash.substring(1);
var params = new URLSearchParams(fragment);
// Extract the token from the fragment
var accessToken = params.get('access_token');
isValid = params.get('state') === sentState;
// Store the access token securely in localStorage
localStorage.setItem('accessToken', accessToken);
// Callback with the token
oauth2.callback({ auth: oauth2.auth, token: accessToken, isValid: isValid, redirectUrl: redirectUrl });
window.close()
}
if (document.readyState !== 'loading') {
run();
} else {
document.addEventListener('DOMContentLoaded', function () {
run();
});
}
</script>
</body>
</html>
"""
我应该怎么做才能在curl请求中传递访问令牌?
在fastapi中实现了oauth2隐式流程,接收访问令牌,但在后续的apicurl请求中不会传递访问令牌。
在寻找了很多解决方案之后,我发现fastapi内部不支持隐式流,但它支持带有pkce流的授权码,这比隐式流更安全。
有一个包有很好的文档来使用 pkce 流程实现授权代码。