go auth_error ai_generated true

rpc error: code = Unauthenticated desc = missing or invalid authorization token

ID: go/grpc-unauthenticated-token

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-09-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.x active — — —

Root Cause

The server's auth interceptor rejected the request because the metadata did not contain a valid bearer token, or the token was expired/malformed. Common when the client forgets to attach metadata or uses the wrong metadata key.

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

    gRPC metadata keys are lowercased; an uppercase key like "Authorization" is not recognized by the server's lookup for "authorization".

  2. 95% fail

    An expired or missing token never becomes valid on retry; the server rejects each attempt identically.