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

YARP反向代理对接SSO时的CORS问题及认证透明化配置咨询

问题分析

当前CORS错误的核心原因是:前端Blazor应用(http://localhost:6799)发起请求后,YARP直接将微软登录页的重定向响应返回给前端,导致浏览器触发跨域拦截——微软登录端点并未配置允许localhost:6799的跨域访问。我们需要让YARP自身处理SSO认证流程,避免前端直接与登录端点交互,同时实现认证令牌的透明转发。

解决方案

以下是分步配置方案,实现YARP对SSO认证的透明管理及CORS问题的解决:

1. 配置YARP的Microsoft Identity认证

让YARP自身处理登录跳转,而非将重定向返回给前端。在YARP项目的Program.cs中添加认证配置:

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    options.ClientId = "你的微软应用ClientId";
    options.ClientSecret = "你的微软应用ClientSecret";
    options.Authority = "https://login.microsoftonline.com/你的租户ID/v2.0";
    options.ResponseType = "code";
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    // 添加SAP API要求的权限范围(如果需要)
    options.Scope.Add("sap-api-required-scope");
    options.SaveTokens = true; // 将令牌保存到Cookie,用于后续转发
    options.CallbackPath = "/signin-oidc"; // 回调路径需在微软应用注册中配置
});

2. 配置YARP的令牌转发转换器

实现登录后将认证令牌自动添加到转发给SAP API的请求头中:

// 自定义令牌转发转换器
public class TokenForwardTransform : HttpTransformer
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public TokenForwardTransform(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public override async ValueTask TransformRequestAsync(HttpContext context, HttpRequestMessage proxyRequest, string destinationPrefix)
    {
        await base.TransformRequestAsync(context, proxyRequest, destinationPrefix);
        // 从认证会话中获取AccessToken
        var accessToken = await context.GetTokenAsync("access_token");
        if (!string.IsNullOrEmpty(accessToken))
        {
            proxyRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        }
    }
}

// 在服务注册中添加转换器
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
    .AddTransforms<TokenForwardTransform>();

3. 配置YARP的CORS策略

允许Blazor应用的跨域请求,并支持携带认证Cookie:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowBlazorApp", policy =>
    {
        policy.WithOrigins("http://localhost:6799")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials(); // 允许携带YARP的认证Cookie
    });
});

4. 配置YARP中间件管道顺序

确保中间件顺序正确:CORS → 认证 → 代理路由

var app = builder.Build();

app.UseHttpsRedirection();
// CORS中间件必须放在认证和路由之前
app.UseCors("AllowBlazorApp");
app.UseAuthentication();
app.UseAuthorization();

// 启用反向代理
app.MapReverseProxy();

app.Run();

5. 配置YARP转发规则(appsettings.json)

添加SAP API的转发路由,并要求认证才能访问:

"ReverseProxy": {
  "Routes": {
    "sap-api-route": {
      "ClusterId": "sap-api-cluster",
      "Match": {
        "Path": "{**catch-all}"
      },
      "AuthorizationPolicy": "Authenticated" // 未认证请求将触发YARP的登录跳转
    }
  },
  "Clusters": {
    "sap-api-cluster": {
      "Destinations": {
        "sap-api": {
          "Address": "你的SAP API基础地址"
        }
      }
    }
  }
}

6. Blazor应用端配置

确保API请求携带认证Cookie,在Blazor的HttpClient中配置:

var handler = new HttpClientHandler
{
    UseCookies = true,
    CookieContainer = new CookieContainer()
};
var httpClient = new HttpClient(handler)
{
    BaseAddress = new Uri("https://localhost:6899/")
};
// 注入到服务容器中供组件使用
builder.Services.AddScoped(sp => httpClient);
关键注意事项
  • 微软应用注册中需配置回调URL为https://localhost:6899/signin-oidc
  • 确认SAP API支持Bearer令牌认证,且配置的权限范围与微软应用一致
  • 登录流程中,浏览器将直接跳转到微软登录页(由YARP触发),而非前端AJAX请求触发,从根源避免跨域问题

内容的提问来源于stack exchange,提问作者Akshay Pradeep-Kulkarni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:30:30