# rpc 错误：code = PermissionDenied desc = 缺少或无效的授权令牌

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

## 根因

服务端的认证拦截器拒绝了请求，因为 metadata 中不含有效的 bearer 令牌，或令牌已过期。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.45+ | active | — | — |

## 解决方案

1. **** (92% 成功率)
   ```
   md := metadata.Pairs("authorization", "Bearer "+token)
ctx = metadata.NewOutgoingContext(ctx, md)
resp, err := client.Get(ctx, req)
// or as a unary interceptor:
func auth(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, inv grpc.UnaryInvoker, opts ...grpc.CallOption) error {
    ctx = metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+getToken())
    return inv(ctx, method, req, reply, cc, opts...)
}
   ```
2. **** (90% 成功率)
   ```
   type tokenAuth struct{ token string }
func (t tokenAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
    return map[string]string{"authorization": "Bearer " + t.token}, nil
}
func (t tokenAuth) RequireTransportSecurity() bool { return true }
conn, _ := grpc.Dial(addr, grpc.WithPerRPCCredentials(tokenAuth{token: tok}))
   ```

## 无效尝试

- **** — An expired or malformed token is rejected deterministically on every attempt. (92% 失败率)
- **** — Removes the security boundary entirely and lets unauthenticated clients reach protected handlers. (95% 失败率)
