C++GRPC::实验性:拦截器如何从自定义拦截器返回状态和消息

2022-04-03 00:00:00 grpc c++

我正在我的c++GRPC项目中创建一个自定义的inteceptor,以检查授权持有者令牌是否有效或用户是否经过身份验证,因此我创建了一个拦截器来获取元数据并验证令牌,如果令牌是OK的,我将执行继续方法,此时一切正常,但是...

当令牌无效时,如何从侦听器返回GRPC::Status::未经身份验证的错误?

我尝试了方法。ModifySendMessage和Status,但它不工作和崩溃

void AuthInterceptor::Intercept(grpc::experimental::InterceptorBatchMethods *methods) {

    if (methods->QueryInterceptionHookPoint(
            grpc::experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
        auto map = methods->GetRecvInitialMetadata();

        std::multimap<grpc::string_ref, grpc::string_ref>::iterator itr;

        for (itr = map->begin(); itr != map->end(); ++itr) {
            if (itr->first == "authorization") {

                std::string erase = "Bearer ";
                std::size_t pos = itr->second.find(erase);
                std::string value = itr->second.data();
                std::string token = value.erase(pos, erase.length());

                TokenStatus tokenStatus = Security::Token::validateToken(token);

                if (tokenStatus.valid) {
                    std::cout << " token is valid " << token << "
";
                    //continue 
                    methods->Proceed();
                } else {
                    std::cout << " token is no valid " << token << "
";
                 // i need to return or throw
              // return Status(grpc::StatusCode::UNAUTHENTICATED, "you are not UNAUTHENTICATED");


                }


            } else {
                 // i need to return or throw
              // return Status(grpc::StatusCode::UNAUTHENTICATED, "you are not UNAUTHENTICATED");
            }

        }

    }


}

我如何才能返回 返回状态(GRPC::StatusCode::未验证,e.What()); 拦截器中的令牌无效时


解决方案

这是旧的,但请尝试methods->ModifySendStatus(grpc::Status const & status);

相关文章