Swagger UI 使用 IdentityServer4 的授权 returns 无效 redirect_uri

Swagger UI Authorization using IdentityServer4 returns Invalid redirect_uri

我正在使用 Swashbuckle 通过 IdentityServer 进行 Swagger 授权。我遵循了这些步骤:https://www.scottbrady91.com/Identity-Server/ASPNET-Core-Swagger-UI-Authorization-using-IdentityServer4.

这是来自 IdentityServer 的日志记录:

2019-01-17 19:17:41.031 +01:00 [ERR] Invalid redirect_uri: 
http://localhost:3200/oauth2-redirect.html
{
  "ClientId": "demo_api_swagger",
  "ClientName": "Swagger UI for API",
  "AllowedRedirectUris": [
    "http://localhost:5001/oauth2-redirect.html"
  ],
  "SubjectId": "anonymous",
  "RequestedScopes": "",
  "Raw": {
    "response_type": "token",
    "client_id": "demo_api_swagger",
    "redirect_uri": "http://localhost:3200/oauth2-redirect.html",
    "scope": "api_data openid profile",
    "state": "VGh1IEph etc.."
  }
}

日志记录说:

Invalid redirect_uri: http://localhost:3200/oauth2-redirect.html

但我没有在任何地方设置这个地址,也不知道它来自哪里。如何设置正确的重定向地址?

它来自 Identity Server 4 端 Client 的配置。在文章示例中,它设置为 http://localhost:5001/oauth2-redirect.html,因此请将其更改为适合您的值:

new Client {
    ClientId = "demo_api_swagger",
    ClientName = "Swagger UI for demo_api",
    AllowedGrantTypes = GrantTypes.Implicit,
    AllowAccessTokensViaBrowser = true,
    RedirectUris = {"http://localhost:5001/oauth2-redirect.html"},
    AllowedScopes = {"demo_api"}
};

带有端口 3200 的重定向地址被硬编码到 Swagger 中 UI。

幸运的是,通过将密钥 oauth2RedirectUrl 添加到 Swagger 初始化中,有一个简单的解决方法。

Swaggerinit.js(添加到 wwwroot/assets 文件夹):

function createSwaggerUi() {
    var full = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '');

    const ui = SwaggerUIBundle({
        url: full + "/swagger/v2/swagger.json",
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
            SwaggerUIBundle.presets.apis,
            SwaggerUIStandalonePreset
        ],
        plugins: [
            SwaggerUIBundle.plugins.DownloadUrl
        ],
        layout: "StandaloneLayout",

        oauth2RedirectUrl: full + "/oauth2-redirect.html"
    })

    window.ui = ui;
}

window.addEventListener("load", function () {
    createSwaggerUi();
});

Startup.cs:

app.UseSwaggerUI(options =>
{
    options.RoutePrefix = string.Empty;

    ...

    options.InjectJavascript("../assets/swaggerinit.js");
});

这适用于 Swashbuckle.AspNetCore.SwaggerUI,版本=4.0.1.0。