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

Nginx反向代理下Duende Identity Server与Blazor认证异常求助

问题:Nginx反向代理下Blazor对接Duende Identity Server认证失效

我有一个包含Blazor应用、Web API服务和Duende Identity Server的微服务方案,采用Nginx作为反向代理。直接配置Blazor对接Duende认证可正常运行,但添加Nginx后认证功能失效。参考相关解决方案仍未解决问题,以下是各服务配置细节:

Nginx配置

nginx.conf

worker_processes  1;
events {
     worker_connections  1024;
}
http {
     include       mime.types;
     default_type  application/octet-stream;
     log_format  main  '[$time_local]-status :[$status] - $remote_addr - $host - UriAddr: [$request_uri] - XFF : ["$http_x_forwarded_for"] '
                  '- BodyByteSent : [$body_bytes_sent] "$http_referer" '
                  '"$request"'; #"$http_user_agent"
     access_log  logs/access.log  main;
     sendfile        on; 
     keepalive_timeout  300;   
     include nginx_http.conf;  
}

nginx_http.conf

server {
    listen       80;
    server_name  localhost;
    server_tokens off;

    gzip on;
    gzip_buffers      16 8k;
    gzip_comp_level   4;
    gzip_http_version 1.0;
    gzip_min_length   1280;
    gzip_types        *;
    gzip_vary         on;    
    gzip_disable msie6;
    charset UTF-8;
    include nginx_access_control.conf;
    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host $http_host;
        #proxy_set_header Referer $http_referer;

        proxy_pass         https://127.0.0.1:5001/;
    }
location /Identity/ {
        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_pass         http://127.0.0.1:12000/;
    }

}

Duende Identity Service配置

该服务基于.NET 6运行在https://localhost:12001/和http://localhost:12000/,配置如下:

builder.Services.AddIdentityServer(options =>
{
    options.IssuerUri = "http://localhost/Identity/";
})
 .AddDeveloperSigningCredential()
.AddInMemoryClients(new List<Client>
{
    new Client
    {
        ClientName = "Web User",
        ClientId = "web",/*"D2B8B5EC-9766-40B9-9D95-077B54245E6E",*/
        ClientSecrets= {new Secret("123456".Sha256())},
        AllowedGrantTypes = GrantTypes.Code,
        // RedirectUris={"https://localhost:5001/signin-oidc"},
        RedirectUris={"http://localhost/signin-oidc"},
        PostLogoutRedirectUris={ "http://localhost/signout-callback-oidc" },
        AllowedScopes=
        {
            "openid",
            "profile"
        }
    }
}).AddInMemoryIdentityResources(new List<IdentityResource>
{
    new IdentityResources.OpenId(),
    new IdentityResources.Profile(),
})
.AddInMemoryApiScopes(new List<ApiScope>
{
    new ApiScope("Management.fullaccess")
})
.AddInMemoryApiResources(new List<ApiResource>
{
    new ApiResource("Management","Management Service")
    {
        Scopes = { "Management.fullaccess" }      
    }
})
.AddAspNetIdentity<User>();

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();

app.MapRazorPages();
app.MapControllers();
app.Run();

Blazor App配置

该应用基于.NET 5运行在https://localhost:5001/和http://localhost:5000/,配置如下:

public void ConfigureServices(IServiceCollection services)
{
    var blazorSevice = services.AddControllersWithViews();

    services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders =
            ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    });
    if (environment.IsDevelopment())
    {
        blazorSevice.AddRazorRuntimeCompilation();
    }
    services.AddRazorPages();
    services.AddServerSideBlazor(o => o.DetailedErrors = true);
    services.AddAuthentication(p =>
        {
            p.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            p.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
        {
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.Authority = "http://localhost/Identity";//"http://localhost:12000";
            options.MetadataAddress = "http://localhost/Identity/.well-known/openid-configuration";
            options.ClientId = "web";
            options.ClientSecret = "123456";
            options.ResponseType = "code";
            options.GetClaimsFromUserInfoEndpoint = true;
            options.Scope.Add("profile");
            options.Scope.Add("openid");
            options.SaveTokens = true;
            options.RequireHttpsMetadata = false;
            
        });

    services.AddTelerikBlazor();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseForwardedHeaders();

    app.Use(async (httpcontext, next) =>
    {
        await next();
        string location = httpcontext.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Location];

        if ((httpcontext.Response.StatusCode == StatusCodes.Status302Found
            || httpcontext.Response.StatusCode == StatusCodes.Status307TemporaryRedirect)
            && location != "https://localhost:5001/signin-oidc"
            && location != "https://localhost:5001/")
        {
            location = location.Replace("https","http")
                .Replace("://localhost:5001/", "://localhost/Identity/");
            httpcontext.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Location] = location;
        }
        if (httpcontext.Response.StatusCode == StatusCodes.Status302Found
            || httpcontext.Response.StatusCode == StatusCodes.Status307TemporaryRedirect)
        {
            if (location != "https://localhost:5001/" 
                && location != "https://localhost:5001/signin-oidc" 
                && !location.Contains("://localhost/Identity/"))
            {
                location = location.Replace("%3A5001", "")
                    .Replace("://localhost/", "://localhost/Identity/")
                    .Replace("://localhost:12001/", "://localhost/Identity/");
                httpcontext.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Location] = location;
            }
        }
    });
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
        endpoints.MapControllers();
    
        endpoints.MapBlazorHub(option =>
            option.Transports = HttpTransportType.LongPolling);
        endpoints.MapFallbackToPage("/_Host");
    });
}

当前现象与尝试

我尝试通过中间件修改HTTP响应Location来处理Duende的重定向请求,但这并非常规方案。当前现象为:运行Blazor应用后可跳转到Duende登录页,点击登录后重定向到/signin-oidc时出现错误,推测是向Duende的/connect/token端点获取令牌时失败,恳请提供帮助。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:45:33