swagger 将Oauth2和Azure Active Directory与使用connexion和OpenAPI 3.0构建的Flask应用集成

u3r8eeie  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(162)

正如标题所说,尝试在我的Flask应用程序中使用Oauth2 for Azure Active Directory,该应用程序使用connexion和swagger编写。我已经让sample Azure python app与Oauth2一起工作,但是当我在Flask应用程序中实现它时,我得到了两个错误之一。
当我在Azure中为应用程序注册将平台设置为“Web”时,我收到错误

AADSTS9002326: Cross-origin token redemption is permitted only for the 'Single-Page Application' client type. Request origin: 'http://localhost:8004'.

字符串
当我在Azure中为应用程序注册将平台设置为“SPA”时,我收到错误

AADSTS9002325: Proof Key for Code Exchange is required for cross-origin authorization code redemption.


我在本地运行这个应用程序,所以我不知道为什么会有跨域授权。下面是相关代码

app.py

import identity.web
import connexion
import logging
import json
import requests
from pathlib import Path

from consts import *
from flask import Flask, redirect, render_template, request, session, url_for
from logging.config import dictConfig

from connexion import FlaskApp

# Create Log Directory if it does not exist
Path(LOG_DIR).mkdir(parents=True, exist_ok=True)

app = FlaskApp(__name__, specification_dir=OPENAPI_DIR)
app.add_api(OPENAPI_FILE)

@app.route('/oauth2-redirect.html')
def oauth2_redirect():
    print(request.__dict__)
    args = "&".join(var + "=" + value for var, value in request.args.items())
    print(args)
    return redirect('/ui/oauth2-redirect.html?' + args, 302)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8004, debug=VADER_DEBUG)

swagger.yml的一部分

components:
  securitySchemes:
    AzureAD:
      type: oauth2
      x-tokenInfoFunc: auth.azure_ad
      flows:
        authorizationCode:
          authorizationUrl: "https://login.microsoftonline.com/{my_tenant_id}/oauth2/v2.0/authorize"
          tokenUrl: "https://login.microsoftonline.com/{my_tenant_id}/oauth2/v2.0/token"
          scopes:
            User.ReadBasic.All: Read basic information on a user
            Group.Read.All : List all groups
            GroupMember.Read.All: See members of a group

Azure应用清单

{
    "id": "{REDACTED}",
    "acceptMappedClaims": null,
    "accessTokenAcceptedVersion": null,
    "addIns": [],
    "allowPublicClient": false,
    "appId": "{REDACTED}",
    "appRoles": [],
    "oauth2AllowUrlPathMatching": false,
    "createdDateTime": "2023-07-29T05:37:43Z",
    "description": null,
    "certification": null,
    "disabledByMicrosoftStatus": null,
    "groupMembershipClaims": null,
    "identifierUris": [
        "api://{REDACTED}"
    ],
    "informationalUrls": {
        "termsOfService": null,
        "support": null,
        "privacy": null,
        "marketing": null
    },
    "keyCredentials": [],
    "knownClientApplications": [],
    "logoUrl": null,
    "logoutUrl": null,
    "name": "vader-{REDACTED}",
    "notes": null,
    "oauth2AllowIdTokenImplicitFlow": false,
    "oauth2AllowImplicitFlow": false,
    "oauth2Permissions": [],
    "oauth2RequirePostResponse": false,
    "optionalClaims": null,
    "orgRestrictions": [],
    "parentalControlSettings": {
        "countriesBlockedForMinors": [],
        "legalAgeGroupRule": "Allow"
    },
    "passwordCredentials": [
        {
            "customKeyIdentifier": null,
            "endDate": "2025-07-28T05:38:18.455Z",
            "keyId": "2a637497-012e-442a-8841-83ca8c59d7e5",
            "startDate": "2023-07-29T05:38:18.455Z",
            "value": null,
            "createdOn": "2023-07-29T05:38:34.6206198Z",
            "hint": "S-k",
            "displayName": "vader-{REDACTED}"
        }
    ],
    "preAuthorizedApplications": [],
    "publisherDomain": "{REDACTED}devgmail.onmicrosoft.com",
    "replyUrlsWithType": [
        {
            "url": "http://localhost:8004/oauth2-redirect.html",
            "type": "Spa"
        }
    ],
    "requiredResourceAccess": [
        {
            "resourceAppId": "00000003-0000-0000-c000-000000000000",
            "resourceAccess": [
                {
                    "id": "e1fe6dd8-ba31-4d61-89e7-88639da4683d",
                    "type": "Scope"
                },
                {
                    "id": "b340eb25-3456-403f-be2f-af7a0d370277",
                    "type": "Scope"
                },
                {
                    "id": "5f8c59db-677d-491f-a6b8-5f174b11ec1d",
                    "type": "Scope"
                },
                {
                    "id": "bc024368-1153-4739-b217-4326f2e966d0",
                    "type": "Scope"
                }
            ]
        }
    ],
    "samlMetadataUrl": null,
    "signInUrl": null,
    "signInAudience": "AzureADMyOrg",
    "tags": [],
    "tokenEncryptionKeyId": null
}

ut6juiuv

ut6juiuv1#

错误“AADSTS 9002325:跨域授权码兑换需要换码验证密钥 ”,通常是在授权请求中不传递code_challenge时出现。
我创建了
Azure AD应用程序,并授予了API权限

x1c 0d1x的数据
对于 * 示例 *,我使用了下面的授权请求,得到了同样的错误:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
&client_id=ClientID
&response_type=code
&redirect_uri=https://jwt.ms
&response_mode=query
&scope=https://graph.microsoft.com/.default
&state=12345

字符串


注意:单页应用程序(SPA)使用具有用于代码交换的证明密钥(PKCE)的认证代码流。参考此MsDoc

修改授权请求,传入code_challengecode_challenge_method即可解决。

https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
client_id=ClientID
&response_type=code
&redirect_uri=https://jwt.ms
&response_mode=query
&scope=https://graph.microsoft.com/.default
&state=12345
&code_challenge=CodeChallenge
&code_challenge_method=S256



生成auth-code成功:



我通过Postman生成了access token,参数如下:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
scope:https://graph.microsoft.com/.default
code:code
redirect_uri:https://jwt.ms
grant_type:authorization_code
code_verifier:S256


x1c4d 1x的
使用**InteractiveBrowserCredential**,使用PKCE保护授权码。

参考文献:

azure-identity · PyPI
作者:Charles Lowell

相关问题