使用 Yarp.ReverseProxy 转发 ai 调用请求至硅基流动

在开发 AI 应用时,为了保障 API Key 安全并实现私有化鉴权,通常不建议客户端直接调用第三方 AI 服务。通过 Yarp.ReverseProxy 搭建转发代理,API 服务器可以作为中转层,在完成内部身份验证后,再将请求下发至硅基流动等服务商。这不仅能有效隐藏 API Key,还能灵活实现多账号负载均衡及额度控制。

配置

配置转发服务

# 可以配置  ApiHost = "https://api.siliconflow.cn";
# 可以配置  ApiKey = "sk-xxx";

 public static IServiceCollection AddAiYarpReverseProxy(this IServiceCollection services, IConfiguration configuration) {
   services.AddReverseProxy()
     .LoadFromMemory(
       [
         new RouteConfig {
           RouteId = "ai_route", // 路由ID
             ClusterId = "ai_cluster", // 集群ID
             AuthorizationPolicy = "AiAccessPolicy", // 指定访问策略
             Match = new RouteMatch {
               Path = "/api/ai/v1/{**remainder}",
             }, // 匹配路径
         },
       ],
       [
         new ClusterConfig {
           ClusterId = "ai_cluster", // 集群ID
             Destinations = new Dictionary < string, DestinationConfig > {
               {
                 "dest1",
                 new DestinationConfig {
                   Address = ApiHost,
                 }
               }, // 目的地
             },
         },
       ])
     .AddTransforms(builderContext => {
       // 核心:替换 API Key
       builderContext.AddRequestTransform(async transformContext => {
         var remainder = transformContext.HttpContext.GetRouteValue("remainder")?.ToString();

         if (!string.IsNullOrEmpty(remainder)) {
           // 2. 重新手动构建 RequestUri,避免 YARP 的默认转义逻辑
           // 这样得到的路径就是原始的 "audio/transcriptions"
           var targetUrl = $ "{ApiHost.TrimEnd('/')}/v1/{remainder}";
           transformContext.ProxyRequest.RequestUri = new Uri(targetUrl);
         }

         // 替换认证信息
         transformContext.ProxyRequest.Headers.Remove("Authorization");
         transformContext.ProxyRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ApiKey);

         // 保持 Host 为硅基流动的域名,否则某些 CDN 会拒绝请求
         transformContext.ProxyRequest.Headers.Host = new Uri(ApiHost).Host;

         await ValueTask.CompletedTask;
       });
     });

   return services;
 }

配置鉴权验证

public static void AddAiYarpReverseProxyAuthorizationOptions(this AuthorizationOptions options, string scheme) {
  options.AddPolicy("AiAccessPolicy", policy => {
    // 曾经配置过 "JWT_Selector" 自动选择认证方案,可以见 https://blog.xsoft.ltd/2026/02/03/asp-net-core-%e6%8e%a5%e5%85%a5-oidc-%e6%9c%8d%e5%8a%a1%e7%ab%af/
    policy.AddAuthenticationSchemes(scheme); // 关键:指定使用你配置的动态选择方案 
    policy.RequireAuthenticatedUser(); // 要求必须通过 Authelia 或 Introspection 认证
    // 如果有组权限要求,可以加上:
    // policy.RequireRole("ai-users"); 
  });
}

调用


builder.Services.AddAuthentication(); // 这里配置验证方案

builder.Services.AddAuthorization(options =>
{
    options.AddAiYarpReverseProxyAuthorizationOptions("JWT_Selector");
});

builder.Services.AddAiYarpReverseProxy(builder.Configuration);

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

app.MapReverseProxy();
上一篇