go auth_error ai_generated true

rpc错误:代码=权限被拒绝 描述=未认证:请求未通过身份验证

rpc error: code = PermissionDenied desc = unauthenticated: request not authenticated

ID: go/grpc-permission-denied-auth-missing

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

版本兼容性

版本状态引入弃用备注
1.0 active
1.1 active

根因分析

gRPC调用缺少必需的身份验证凭据,例如令牌缺失或无效。

English

The gRPC call lacks required authentication credentials, such as a missing or invalid token.

generic

解决方案

  1. 90% 成功率 Attach a valid authentication token to the gRPC metadata.
    token := "valid-jwt-token"
    conn, err := grpc.Dial("localhost:8080", grpc.WithInsecure(), grpc.WithPerRPCCredentials(&authCreds{token: token}))
    // Define authCreds implementing credentials.PerRPCCredentials
    func (c *authCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
        return map[string]string{"authorization": "Bearer " + c.token}, nil
    }
    func (c *authCreds) RequireTransportSecurity() bool { return false }
  2. 85% 成功率 Implement an interceptor to add credentials automatically.
    func authInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
        md := metadata.Pairs("authorization", "Bearer token")
        ctx = metadata.NewOutgoingContext(ctx, md)
        return invoker(ctx, method, req, reply, cc, opts...)
    }
    conn, err := grpc.Dial("localhost:8080", grpc.WithInsecure(), grpc.WithUnaryInterceptor(authInterceptor))

无效尝试

常见但无效的做法:

  1. Retry the request without adding any credentials. 100% 失败

    The server will continue to reject unauthenticated requests.

  2. Use a hardcoded token that may be expired. 90% 失败

    Expired tokens are also rejected by the server.