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

StrawberryShake生成需Token认证的客户端类遇403错误求助

解决StrawberryShake CLI拉取认证Schema时的403错误

核心问题

CLI工具拉取需要认证的GraphQL服务器Schema时,未携带认证Token导致返回403 Forbidden错误,同时你的NuGet包版本不一致,可能引发额外兼容问题。

解决方案

1. 手动获取Schema文件

如果服务器开启了Schema introspection,用curl或Postman携带认证头手动下载:

curl -H "Authorization: Bearer YOUR_AUTH_TOKEN" https://your-graphql-api-url/graphql -o schema.graphql

若服务器关闭了introspection,直接联系后端团队获取Schema文件。

2. 基于本地Schema生成客户端代码

使用CLI命令时指定本地Schema路径,跳过远程拉取步骤:

dotnet graphql init -n YourClientName -s ./schema.graphql -u https://your-graphql-api-url/graphql

该命令会基于本地Schema生成C#客户端代码,并配置目标API地址。

3. 统一NuGet包版本

将所有StrawberryShake相关包升级到同一稳定版本(例如13.9.1),避免版本冲突:

  • StrawberryShake (13.9.1)
  • StrawberryShake.CodeGeneration.CSharp (13.9.1)
  • StrawberryShake.Transport.Http (13.9.1)

4. 配置运行时认证Token

生成客户端代码后,在依赖注入中为HTTP客户端添加认证头处理器:

using System.Net.Http.Headers;
using System.Net.Http;

// 注册客户端及认证逻辑
services.AddHttpClient<IYourClient>(client =>
{
    client.BaseAddress = new Uri("https://your-graphql-api-url/graphql");
})
.AddHttpMessageHandler(() => new AuthTokenHandler("Bearer YOUR_AUTH_TOKEN"));

// 自定义认证消息处理器
public class AuthTokenHandler : DelegatingHandler
{
    private readonly string _authHeader;

    public AuthTokenHandler(string authHeader)
    {
        _authHeader = authHeader;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Authorization = AuthenticationHeaderValue.Parse(_authHeader);
        return await base.SendAsync(request, cancellationToken);
    }
}

若Token需要动态获取(如从配置或身份服务),可在处理器中添加对应逻辑实现动态注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:33:24