C++ grpc::experimental:interceptor how to return status and message from custom interceptor

北城余情 提交于 2020-12-12 11:04:10

问题


Im creating a custom inteceptor in my c++ grpc project to check if the Authorization Bearer token is valid or user is authenticated, so for that i create a interceptor to get the metadata and validate the token, if the token is ok i execute Proceed method, at this point all is ok, but...

how i can return a grpc::Status::Unauthenticated error from the interceptor when the token is not valid?

i try with method.ModifySendMessage and status but its not work and crash

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 << "\n";
                    //continue 
                    methods->Proceed();
                } else {
                    std::cout << " token is no valid " << token << "\n";
                 // 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");
            }

        }

    }


}

how i can return return Status(grpc::StatusCode::UNAUTHENTICATED, e.what()); when the token is not valid from the interceptor

来源:https://stackoverflow.com/questions/56995553/c-grpcexperimentalinterceptor-how-to-return-status-and-message-from-custom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!