go auth_error ai_generated true

rpc 错误:code = Unauthenticated desc = 授权令牌缺失或无效

rpc error: code = Unauthenticated desc = missing or invalid authorization token

ID: go/grpc-unauthenticated-token

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-09-12首次发现

版本兼容性

版本状态引入弃用备注
1.x active — — —

根因分析

服务器的认证拦截器拒绝了请求,因为元数据中不包含有效的 bearer 令牌,或令牌已过期/格式错误。常见于客户端忘记附加元数据或使用了错误的元数据键。

English

The server's auth interceptor rejected the request because the metadata did not contain a valid bearer token, or the token was expired/malformed. Common when the client forgets to attach metadata or uses the wrong metadata key.

generic

解决方案

  1. 90% 成功率
    Attach the token via outgoing metadata with a lowercase key and the Bearer scheme:
    
    md := metadata.Pairs("authorization", "Bearer "+token)
    ctx := metadata.NewOutgoingContext(context.Background(), md)
    resp, err := client.Do(ctx, req)
  2. 88% 成功率
    Use a client interceptor to inject a freshly refreshed token on every call:
    
    func authInterceptor(token *oauth2.TokenSource) grpc.UnaryClientInterceptor {
        return func(ctx context.Context, m string, req, reply interface{}, cc *grpc.ClientConn, inv grpc.UnaryInvoker, opts ...grpc.CallOption) error {
            t, _ := token.Token()
            ctx = metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+t.AccessToken)
            return inv(ctx, m, req, reply, cc, opts...)
        }
    }

无效尝试

常见但无效的做法:

  1. 70% 失败

    gRPC metadata keys are lowercased; an uppercase key like "Authorization" is not recognized by the server's lookup for "authorization".

  2. 95% 失败

    An expired or missing token never becomes valid on retry; the server rejects each attempt identically.