代码之家  ›  专栏  ›  技术社区  ›  Meet Parikh

FastAPI:Oauth2隐式流在后续api中不传递访问令牌

  •  0
  • Meet Parikh  · 技术社区  · 2 年前

    我正在实现FastAPI oauth2隐式流,在实现过程中,我能够从azure ad接收访问令牌,但是访问令牌不会在后续的api中传递。

    在我的swagg-url中,授权按钮看起来像这样 enter image description here

    在UI中成功登录后,我可以看到 enter image description here

    我还可以看到存储在 浏览器本地存储 但是,在我后续的api请求中,accessToken没有在curl url中传递

    curl url的格式如下

    curl -X 'GET' \
      'http://localhost:8000/protected' \
      -H 'accept: application/json'
    

    现在,在swaggredirect逻辑中,我有这样的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隐式流,接收访问令牌,但在后续的api curl请求中没有传递访问令牌。

    0 回复  |  直到 2 年前
        1
  •  1
  •   Meet Parikh    2 年前

    在寻找了很多解决方案后,我发现fastapi内部不支持隐式流,但它支持使用pkce流的授权代码,这比隐式流更安全。

    有一个包有很好的文档来实现pkce流的授权代码。

    包名称: fastapi-azure-auth

    推荐文章