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

- **ID:** `go/grpc-unauthenticated-token`
- **领域:** go
- **类别:** auth_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.x | active | — | — |

## 解决方案

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...)
    }
}
   ```

## 无效尝试

- **** — gRPC metadata keys are lowercased; an uppercase key like "Authorization" is not recognized by the server's lookup for "authorization". (70% 失败率)
- **** — An expired or missing token never becomes valid on retry; the server rejects each attempt identically. (95% 失败率)
