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

Swagger在Azure根路径部署时授权失败,非根路径正常问题排查

问题描述

我有一套可正常运行的Swagger配置,能跳转至Azure完成授权并获取可用token,且无需将Azure应用类型从Web转为SPA。

同事建议将Swagger部署在后端根路径而非原有/swagger路径,我先修改为/swaggy路径并在Azure添加对应重定向URL,功能正常:

//app.UseSwagger(options => options.RouteTemplate = "swagger/{documentName}/docs.json");
app.UseSwagger(options => options.RouteTemplate = "swaggy/{documentName}/docs.json");
app.UseSwaggerUI(options =>
{
  ...
  //options.RoutePrefix = "swagger";
  options.RoutePrefix = "swaggy";
});

添加的重定向URL:

https://localhost:7001/swagger/oauth2-redirect.html

https://localhost:7001/swaggy/oauth2-redirect.html

但改为根路径部署后功能失效,代码修改如下:

//app.UseSwagger(options => options.RouteTemplate = "swagger/{documentName}/docs.json");
app.UseSwagger(options => options.RouteTemplate = "{documentName}/docs.json");
app.UseSwaggerUI(options =>
{
  ...
  //options.RoutePrefix = "swagger";
  options.RoutePrefix = "";
});

添加的重定向URL:

https://localhost:7001/swagger/oauth2-redirect.html

https://localhost:7001/oauth2-redirect.html

此时出现错误:

Auth ErrorError: response status is 400, error: invalid_request, description: AADSTS9002326: Cross-origin token redemption is permitted only for the 'Single-Page Application' client-type. Request origin: 'https://localhost:7001'.

所有搜索结果都指向转为SPA或检查重定向URL,均不符合我的场景,请问问题原因及解决方法?


问题原因与解决方案

原因

当SwaggerUI部署到根路径(RoutePrefix = "")时,SwaggerUI默认启用了**PKCE(Proof Key for Code Exchange)**机制。PKCE是SPA类应用的专属授权特性,Azure AD会将带有PKCE的请求判定为SPA应用的跨源token兑换操作,但你的应用注册类型是Web应用,因此触发AADSTS9002326错误。

此前部署在/swagger或/swaggy路径时,SwaggerUI未启用PKCE(或Azure AD的识别逻辑未触发SPA判定),所以授权流程正常。

解决方案

在SwaggerUI的OAuth配置中显式禁用PKCE,并确保重定向URL配置正确:

  1. 修改SwaggerUI配置,添加OAuthUsePkce(false):
app.UseSwaggerUI(options =>
{
    // 保留原有其他配置(如文档地址、作用域等)
    options.RoutePrefix = "";
    options.OAuthClientId("你的Azure AD客户端ID");
    options.OAuthAuthority("你的Azure AD授权地址,例如https://login.microsoftonline.com/你的租户ID");
    options.OAuthRedirectUri("https://localhost:7001/oauth2-redirect.html");
    options.OAuthUsePkce(false); // 核心:禁用PKCE,使用Web应用标准授权流程
});
  1. 确认Azure AD应用注册的重定向URL:
    确保已添加根路径的重定向地址:

https://localhost:7001/oauth2-redirect.html

  1. 验证Swagger文档路由:
    保持Swagger的RouteTemplate配置正确,确保接口文档可正常访问:
app.UseSwagger(options => options.RouteTemplate = "{documentName}/docs.json");

完成以上调整后,SwaggerUI会使用Web应用的标准Authorization Code Flow(无PKCE),Azure AD将不再判定为SPA跨源请求,授权功能即可恢复正常。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:35:28