首页 > 解决方案 > Dart grpc 在授权失败时不会抛出异常

问题描述

我正在使用 dart grpc 客户端连接到 asp .net 核心服务器。服务器使用 jwt 身份验证来识别客户端。该getProfiles()方法应该返回一个配置文件流,如果我使用有效的令牌,一切正常。但是,如果令牌无效,该方法将返回一个空流并且根本没有错误,即使标头包含 401 状态代码。

final stub = PublicProfileServiceClient(
  channel,
  options: CallOptions(
    timeout: const Duration(seconds: 10),
    metadata: {'Authorization': 'Bearer $token'},
  ),
);

try {
  final response = stub.getProfile(ProfileRequest());
  response.listen((value) {
    print(value);
  }, onError: (e) {
    print('stream error: $e');
  }, onDone: () {
    print('done');
  });

  final header = await response.headers;
  print('header: $header');
} catch (e) {
  print('catch error: $e');
}

客户端输出:

header: {:status: 401, server: nginx/1.18.0, date: Wed, 17 Mar 2021 19:07:02 GMT, content-length: 0, www-authenticate: Bearer error="invalid_token"}
done

服务器日志:

Request finished HTTP/2 POST http://127.0.0.1:5001/PublicProfileService/UpdateProfile application/grpc - - 401 0 - 0.9421ms

尽管返回空流,我希望 grpc 客户端会引发异常。但是当我使用只返回单个响应而不是流的方法时,grpc 会抛出以下异常:

gRPC Error (code: 12, codeName: UNIMPLEMENTED, message: No responses received, details: null, rawResponse: null)

pubspec.yaml 中的依赖项:

grpc: ^3.0.0
protobuf: ^2.0.0

标签: asp.net-coredartgrpc

解决方案


推荐阅读