当ASP.NET Core应用程序在使用反向代理或负载均衡器时,可能会出现OIDC无法正常工作的问题。这是因为OIDC需要在重定向期间检测请求的URL,但是在使用代理时,请求的URL可能会被修改。
为了解决此问题,我们需要在ASP.NET Core应用程序中添加以下代码段:
services.Configure(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto;
});
app.UseForwardedHeaders();
这将启用前向代理标头,以确保请求的URL始终正确解析。此外,我们需要在OIDC选项中配置正确的回调路径:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = "https://example.com";
options.ClientId = "my-client";
options.ClientSecret = "my-secret";
options.CallbackPath = "/signin-oidc"; // 正确的回调路径
options.ResponseType = "code";
options.SaveTokens = true;
});
在示例中,回调路径设置为“/signin-oidc”以确保它与代理服务器上的配置相匹配。
如果您的ASP.NET Core应用程序部署在多个代理之后,则需要确保正确配置用于处理请求的代理的标头。例如,假设您在Nginx代理之后运行应用程序,并且您需要将以下配置添加到Nginx服务器块中:
location /myapp {
proxy_pass http://localhost:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https; # 代理服务器协议
proxy_redirect off;
# ...
}
请注意,我们在此处将X-Forwarded-Proto标头设置为“https”以正确传递协议信息。
通过执行这些步骤,您就可以解决多个代理下的ASP.NET Core OIDC问题。