# rpc 错误：code = PermissionDenied desc = 认证失败：无效令牌

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

## 根因

客户端提供了无效或过期的认证令牌，或者服务器的认证中间件拒绝了凭据。

## 版本兼容性

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

## 解决方案

1. **** (90% 成功率)
   ```
   // Use a token source that refreshes automatically
ts := oauth.NewTokenSource(ctx, config)
creds := oauth.NewOauthAccess(token)
conn, err := grpc.Dial(addr, grpc.WithPerRPCCredentials(creds))
   ```
2. **** (85% 成功率)
   ```
   // Server interceptor to validate token
func authInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    token, err := extractToken(ctx)
    if err != nil || !validateToken(token) {
        return nil, status.Errorf(codes.PermissionDenied, "invalid token")
    }
    return handler(ctx, req)
}
   ```

## 无效尝试

- **** — This is a security risk and not a proper fix; it may violate compliance requirements. (95% 失败率)
- **** — The token is invalid; retrying won't change the outcome. (100% 失败率)
