NelmioApiDocBundle 中的 Oauth2 授权

Oauth2 Authorization in NelmioApiDocBundle

我正在尝试将 NelmioApiDocBundle 用于 Symfony 3.4 项目 API 文档,同时还试图围绕项目 API 访问权限的 OAuth 2 授权来解决问题。

到目前为止,我已经按照 this tutorial 了解了如何让 FOSOAuthServerBundle 工作。到目前为止我可以 1.) 使用命令行命令创建客户端:

php bin/console fos:oauth-server:create-client --redirect-uri="___" --grant-type="authorization_code" --grant-type="password" --grant-type="refresh_token" --grant-type="token" --grant-type="client_credentials"

2.) 我也可以通过在我的服务器上访问这个 url 来手动获取访问令牌

http://127.0.0.1:8000/oauth/v2/token?client_id=______&client_secret=________&grant_type=client_credentials

3.) 通过在 GET 参数中包含令牌,我可以使用令牌访问需要 OAuth 访问的 Symfony 项目区域

但是,在 NelmioApiDocBundle 授权中我无法完成这项工作。这是屏幕截图:

如果输入我的 client_id 和密钥,它会将我带到登录页面,如预期的那样。我可以输入我的登录信息,然后按预期进入批准或拒绝页面。此时,如果我单击“批准”或“拒绝”,它会尝试使用 http://localhost:3200/oauth2-redirect.html 的 "redirect_uri"。无论我做什么,我都无法更改重定向 URI。

如何获得正确的重定向 URI?

好的,这实际上很容易解决。您需要添加一行:

oauth2RedirectUrl: 'URLhere',

到位于 web/bundles/nelmioapidoc/

中的 (Symfony 3.4) 文件 init-swagger-ui.js

最终文件看起来像这样:

window.onload = () => {
  const data = JSON.parse(document.getElementById('swagger-data').innerText);
  const ui = SwaggerUIBundle({
      oauth2RedirectUrl: 'URLhere',
    spec: data.spec,
    dom_id: '#swagger-ui',
    validatorUrl: null,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: 'StandaloneLayout'
  });

  window.ui = ui;
};

您可能还想从 Swagger 项目下载文件 oauth2-redirect.html 以包含在实际重定向中。