go auth_error ai_generated true

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

rpc error: code = PermissionDenied desc = authentication failed: invalid token

ID: go/grpc-permission-denied-auth

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

版本兼容性

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

根因分析

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

English

The client provided an invalid or expired authentication token, or the server's authentication middleware rejected the credentials.

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 95% 失败

    This is a security risk and not a proper fix; it may violate compliance requirements.

  2. 100% 失败

    The token is invalid; retrying won't change the outcome.