You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastEndpoints+.NET8中如何修改Swagger UI的oauth2RedirectUrl参数?

在.NET 8 FastEndpoints中自定义Swagger UI的OAuth2重定向URL

要解决Swagger UI中OAuth2重定向URL重复的问题,你不需要通过AdditionalQueryStringParameters手动添加redirect_uri,而是直接修改Swagger UI的OAuth配置以及SwaggerGen中的OAuth流配置,替换框架默认的/oauth2-redirect.html路径。

步骤1:配置SwaggerGen的OAuth2客户端

在Program.cs的SwaggerGen配置中,明确指定OAuth授权码流的RedirectUri,确保Swagger生成的OpenAPI规范中包含正确的重定向地址:

builder.Services.SwaggerGen(c =>
{
    // 基础Swagger文档配置(如标题、版本等)
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });

    // 配置OAuth2安全定义
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
            AuthorizationCode = new OpenApiOAuthFlow
            {
                AuthorizationUrl = new Uri("https://your-fusionauth-instance/oauth2/authorize"),
                TokenUrl = new Uri("https://your-fusionauth-instance/oauth2/token"),
                // 这里设置你的自定义重定向URL
                RedirectUri = "https://your-api-domain/your-custom-redirect-path"
            }
        }
    });

    // 添加安全要求,确保接口文档显示OAuth授权按钮
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
            },
            Array.Empty<string>()
        }
    });
});

步骤2:修改SwaggerUI的OAuth2重定向URL

在SwaggerUI的配置中,直接调用OAuth2RedirectUrl方法设置自定义路径,覆盖框架默认值:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API v1");
    c.RoutePrefix = string.Empty; // 可选:设置SwaggerUI根路径

    // OAuth客户端配置
    c.OAuthClientId("your-fusionauth-client-id");
    c.OAuthAppName("Your API");
    c.OAuthUsePkce(); // FusionAuth推荐使用PKCE,根据你的配置决定是否开启

    // 关键:替换默认的重定向URL
    c.OAuth2RedirectUrl("https://your-api-domain/your-custom-redirect-path");
});

注意事项

  • 不要同时使用AdditionalQueryStringParameters添加redirect_uri,否则会导致参数重复,因为SwaggerUI会自动根据OAuth2RedirectUrl生成该参数。
  • 如果你使用自定义的重定向页面,需要确保该页面的功能和默认的/oauth2-redirect.html一致:接收授权回调的code和state参数,并将它们传递给SwaggerUI的前端逻辑。你可以直接复制默认页面的代码到自定义路径下使用。

内容的提问来源于stack exchange,提问作者paulofer85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:05:11