我正在尝试使用 OIDC 来保护 .NET 8 API。我的项目基于这篇文章:https://auth0.com/blog/backend-for-frontend-pattern-with-auth0-and-dotnet
到目前为止,我可以调用登录端点,它正确地完成了整个登录过程,之后我可以调用授权端点。现在我正在尝试设置 Swagger UI,以便它有效地执行相同的操作。
第一期:
但我认为我不需要在这里解决这个问题,因为我可以使用用户界面上的常规“身份验证”按钮,这导致我
第二期:
当我手动调用端点时,身份验证回调是 POST,一切正常。当我通过 Swagger 登录时,一切都会按照回调进行,这是一个以代码作为查询参数的 GET。我找不到需要更改的设置以使 Swagger 触发 POST。
这是相关的 Swagger 配置:
internal static void Configure(IConfiguration configuration, IServiceCollection services, IWebHostEnvironment environment, string apiName)
{
var authOptions = configuration.GetSection("Auth0").Get<OIDCOptions>();
// Add Swagger options
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = $"{apiName} - {environment.EnvironmentName}", Version = "v1" });
var securityDefinition = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OpenIdConnect,
Name = "Authorization",
In = ParameterLocation.Cookie,
OpenIdConnectUrl = new Uri($"https://{authOptions.Domain}/.well-known/openid-configuration")
};
c.AddSecurityDefinition(
"oauth2",
securityDefinition);
});
}
internal static void Configure(SwaggerUIOptions c, IConfiguration configuration, string apiName, string environmentName)
{
var authOptions = configuration.GetSection("Auth0").Get<OIDCOptions>();
c.SwaggerEndpoint("v1/swagger.json", $"{apiName} - {environmentName}");
c.InjectStylesheet("custom.css");
c.EnableFilter();
c.DocExpansion(DocExpansion.None);
c.OAuthUsePkce();
c.OAuthConfigObject.ClientId = authOptions.ClientId;
c.OAuthConfigObject.ClientSecret = authOptions.ClientSecret;
c.OAuthConfigObject.AppName = "Auth0";
c.OAuth2RedirectUrl($"https://localhost:5001/callback");
}
我想我已经弄清楚了,这个问题根本与 GET/POST 无关。据我了解,SwaggerUI 创建了一个单独的身份验证中间件,而不是使用现有的中间件。由于我将回调设置为已由不同身份验证设置使用的相同路径,因此它不知道如何处理传入的令牌。删除
c.OAuth2RedirectUrl($"https://localhost:5001/callback");
并将 swaggerUI 默认回调路径添加到“允许的回调”列表中我的 Auth0 应用程序注册似乎已经解决了问题。