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

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

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

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

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

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


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

app.py

  1. import identity.web
  2. import connexion
  3. import logging
  4. import json
  5. import requests
  6. from pathlib import Path
  7. from consts import *
  8. from flask import Flask, redirect, render_template, request, session, url_for
  9. from logging.config import dictConfig
  10. from connexion import FlaskApp
  11. # Create Log Directory if it does not exist
  12. Path(LOG_DIR).mkdir(parents=True, exist_ok=True)
  13. app = FlaskApp(__name__, specification_dir=OPENAPI_DIR)
  14. app.add_api(OPENAPI_FILE)
  15. @app.route('/oauth2-redirect.html')
  16. def oauth2_redirect():
  17. print(request.__dict__)
  18. args = "&".join(var + "=" + value for var, value in request.args.items())
  19. print(args)
  20. return redirect('/ui/oauth2-redirect.html?' + args, 302)
  21. if __name__ == "__main__":
  22. app.run(host="0.0.0.0", port=8004, debug=VADER_DEBUG)

swagger.yml的一部分

  1. components:
  2. securitySchemes:
  3. AzureAD:
  4. type: oauth2
  5. x-tokenInfoFunc: auth.azure_ad
  6. flows:
  7. authorizationCode:
  8. authorizationUrl: "https://login.microsoftonline.com/{my_tenant_id}/oauth2/v2.0/authorize"
  9. tokenUrl: "https://login.microsoftonline.com/{my_tenant_id}/oauth2/v2.0/token"
  10. scopes:
  11. User.ReadBasic.All: Read basic information on a user
  12. Group.Read.All : List all groups
  13. GroupMember.Read.All: See members of a group

Azure应用清单

  1. {
  2. "id": "{REDACTED}",
  3. "acceptMappedClaims": null,
  4. "accessTokenAcceptedVersion": null,
  5. "addIns": [],
  6. "allowPublicClient": false,
  7. "appId": "{REDACTED}",
  8. "appRoles": [],
  9. "oauth2AllowUrlPathMatching": false,
  10. "createdDateTime": "2023-07-29T05:37:43Z",
  11. "description": null,
  12. "certification": null,
  13. "disabledByMicrosoftStatus": null,
  14. "groupMembershipClaims": null,
  15. "identifierUris": [
  16. "api://{REDACTED}"
  17. ],
  18. "informationalUrls": {
  19. "termsOfService": null,
  20. "support": null,
  21. "privacy": null,
  22. "marketing": null
  23. },
  24. "keyCredentials": [],
  25. "knownClientApplications": [],
  26. "logoUrl": null,
  27. "logoutUrl": null,
  28. "name": "vader-{REDACTED}",
  29. "notes": null,
  30. "oauth2AllowIdTokenImplicitFlow": false,
  31. "oauth2AllowImplicitFlow": false,
  32. "oauth2Permissions": [],
  33. "oauth2RequirePostResponse": false,
  34. "optionalClaims": null,
  35. "orgRestrictions": [],
  36. "parentalControlSettings": {
  37. "countriesBlockedForMinors": [],
  38. "legalAgeGroupRule": "Allow"
  39. },
  40. "passwordCredentials": [
  41. {
  42. "customKeyIdentifier": null,
  43. "endDate": "2025-07-28T05:38:18.455Z",
  44. "keyId": "2a637497-012e-442a-8841-83ca8c59d7e5",
  45. "startDate": "2023-07-29T05:38:18.455Z",
  46. "value": null,
  47. "createdOn": "2023-07-29T05:38:34.6206198Z",
  48. "hint": "S-k",
  49. "displayName": "vader-{REDACTED}"
  50. }
  51. ],
  52. "preAuthorizedApplications": [],
  53. "publisherDomain": "{REDACTED}devgmail.onmicrosoft.com",
  54. "replyUrlsWithType": [
  55. {
  56. "url": "http://localhost:8004/oauth2-redirect.html",
  57. "type": "Spa"
  58. }
  59. ],
  60. "requiredResourceAccess": [
  61. {
  62. "resourceAppId": "00000003-0000-0000-c000-000000000000",
  63. "resourceAccess": [
  64. {
  65. "id": "e1fe6dd8-ba31-4d61-89e7-88639da4683d",
  66. "type": "Scope"
  67. },
  68. {
  69. "id": "b340eb25-3456-403f-be2f-af7a0d370277",
  70. "type": "Scope"
  71. },
  72. {
  73. "id": "5f8c59db-677d-491f-a6b8-5f174b11ec1d",
  74. "type": "Scope"
  75. },
  76. {
  77. "id": "bc024368-1153-4739-b217-4326f2e966d0",
  78. "type": "Scope"
  79. }
  80. ]
  81. }
  82. ],
  83. "samlMetadataUrl": null,
  84. "signInUrl": null,
  85. "signInAudience": "AzureADMyOrg",
  86. "tags": [],
  87. "tokenEncryptionKeyId": null
  88. }

ut6juiuv

ut6juiuv1#

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

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

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

字符串


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

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

  1. https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
  2. client_id=ClientID
  3. &response_type=code
  4. &redirect_uri=https://jwt.ms
  5. &response_mode=query
  6. &scope=https://graph.microsoft.com/.default
  7. &state=12345
  8. &code_challenge=CodeChallenge
  9. &code_challenge_method=S256



生成auth-code成功:



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

  1. https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
  2. client_id:ClientID
  3. scope:https://graph.microsoft.com/.default
  4. code:code
  5. redirect_uri:https://jwt.ms
  6. grant_type:authorization_code
  7. code_verifier:S256


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

参考文献:

azure-identity · PyPI
作者:Charles Lowell

展开查看全部

相关问题