问题
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