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

在Linux服务器上以HTTP运行带Azure AD认证的ASP.NET Core应用问题求助

解决Linux上HTTP+IP运行Azure AD认证ASP.NET Core应用的问题

核心限制说明

Azure AD平台强制要求:除localhost外,所有重定向URI必须使用HTTPS协议,直接配置公网/局域网IP的HTTP重定向URI是不被允许的。要继续用HTTP+IP运行,得通过反向代理中转+本地回调配置绕开这个限制。

具体解决步骤

1. 修正CallbackPath配置错误

CallbackPath只能设置相对路径(必须以/开头),不能填完整URL。在appsettings.json里正确配置:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "your-domain.com",
  "TenantId": "your-tenant-id",
  "ClientId": "your-client-id",
  "CallbackPath": "/signin-oidc" // 仅填相对路径,不能带http/IP
}

2. 配置ASP.NET Core应用监听localhost

修改应用启动配置,让它只监听localhost的HTTP端口(比如5000),这样Azure AD会认可localhost的HTTP回调:

  • 在Program.cs中修改Kestrel配置:
    var builder = WebApplication.CreateBuilder(args);
    builder.WebHost.ConfigureKestrel(options =>
    {
        options.ListenLocalhost(5000, o => o.Protocols = HttpProtocols.Http1AndHttp2);
    });
    
  • 或通过环境变量临时设置:
    export ASPNETCORE_URLS="http://localhost:5000"
    

3. 部署Nginx反向代理(中转外部IP请求)

在Linux服务器上安装Nginx,配置它把外部IP的HTTP请求转发到localhost的应用端口:

  • 新建Nginx配置文件(如/etc/nginx/sites-available/myapp):
    server {
        listen 80;
        server_name 192.168.1.100; // 替换为你的服务器实际IP
    
        location / {
            proxy_pass http://localhost:5000;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme; // 传递HTTP协议信息
        }
    }
    
  • 启用配置并重启Nginx:
    ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
    nginx -t && systemctl restart nginx
    

4. 在Azure AD门户配置正确的重定向URI

进入Azure AD应用注册页面,添加localhost的HTTP回调地址:
http://localhost:5000/signin-oidc

5. 配置ASP.NET Core转发头支持

让应用识别反向代理传递的真实请求地址,避免认证跳转时生成错误地址。在Program.cs中添加(需放在UseAuthentication、UseAuthorization之前):

var app = builder.Build();

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

// 其他中间件配置
app.UseAuthentication();
app.UseAuthorization();

验证运行

启动ASP.NET Core应用后,通过http://你的服务器IP(如http://192.168.1.100)访问应用,此时Nginx会把请求转发到localhost的应用,Azure AD认证时会回调到http://localhost:5000/signin-oidc,认证完成后会自动跳回外部IP的HTTP地址。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:10:25