xref: /tonic/examples/src/authentication/server.rs (revision 9f5fc3b9)
1d9a481baSLucio Franco pub mod pb {
2df8dd896Stottoto     tonic::include_proto!("grpc.examples.unaryecho");
3d9a481baSLucio Franco }
4d9a481baSLucio Franco 
5d9a481baSLucio Franco use pb::{EchoRequest, EchoResponse};
6df8dd896Stottoto use tonic::{metadata::MetadataValue, transport::Server, Request, Response, Status};
7d9a481baSLucio Franco 
8d9a481baSLucio Franco type EchoResult<T> = Result<Response<T>, Status>;
9d9a481baSLucio Franco 
10d9a481baSLucio Franco #[derive(Default)]
11*9f5fc3b9Stottoto pub struct EchoServer {}
12d9a481baSLucio Franco 
13d9a481baSLucio Franco #[tonic::async_trait]
14d9a481baSLucio Franco impl pb::echo_server::Echo for EchoServer {
unary_echo(&self, request: Request<EchoRequest>) -> EchoResult<EchoResponse>15d9a481baSLucio Franco     async fn unary_echo(&self, request: Request<EchoRequest>) -> EchoResult<EchoResponse> {
16d9a481baSLucio Franco         let message = request.into_inner().message;
17d9a481baSLucio Franco         Ok(Response::new(EchoResponse { message }))
18d9a481baSLucio Franco     }
19d9a481baSLucio Franco }
20d9a481baSLucio Franco 
21d9a481baSLucio Franco #[tokio::main]
main() -> Result<(), Box<dyn std::error::Error>>22d9a481baSLucio Franco async fn main() -> Result<(), Box<dyn std::error::Error>> {
23d9a481baSLucio Franco     let addr = "[::1]:50051".parse().unwrap();
24d9a481baSLucio Franco     let server = EchoServer::default();
25d9a481baSLucio Franco 
26eba7ec7bSLucio Franco     let svc = pb::echo_server::EchoServer::with_interceptor(server, check_auth);
27d9a481baSLucio Franco 
28eba7ec7bSLucio Franco     Server::builder().add_service(svc).serve(addr).await?;
29d9a481baSLucio Franco 
30d9a481baSLucio Franco     Ok(())
31d9a481baSLucio Franco }
32eba7ec7bSLucio Franco 
check_auth(req: Request<()>) -> Result<Request<()>, Status>33eba7ec7bSLucio Franco fn check_auth(req: Request<()>) -> Result<Request<()>, Status> {
34edc5a0d8SAdam Chalmers     let token: MetadataValue<_> = "Bearer some-secret-token".parse().unwrap();
35eba7ec7bSLucio Franco 
36eba7ec7bSLucio Franco     match req.metadata().get("authorization") {
37eba7ec7bSLucio Franco         Some(t) if token == t => Ok(req),
38eba7ec7bSLucio Franco         _ => Err(Status::unauthenticated("No valid auth token")),
39eba7ec7bSLucio Franco     }
40eba7ec7bSLucio Franco }
41