首页 > 解决方案 > 使用 IdentityServer4 的 Swagger UI 授权返回 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

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

标签: asp.net-coreswaggeridentityserver4swagger-uiswashbuckle

解决方案


端口 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();
});

启动.cs:

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

    ...

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

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


推荐阅读