go auth_error ai_generated true

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

ID: go/grpc-permission-denied-auth

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-08-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.x active — — —

Root Cause

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

generic

中文

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

Workarounds

  1. 90% success
    // 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% success
    // 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)
    }

Dead Ends

Common approaches that don't work:

  1. 95% fail

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

  2. 100% fail

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