Custom Authentication with Hooks
Hooks let you control access to your federated graph. We recommend using JWT authentication in the Gateway for most use cases. However, you can use hooks to implement custom authentication and authorization logic.
First, check out our hooks guide to learn the basics of custom hook implementation.
We use the on_gateway_request
hook for authentication. The gateway calls this hook before processing the request. The hook receives the headers containing all headers from the request. You can use the headers to implement custom authentication logic.
The Context
provides mutable storage to pass information between hooks, which we won't need for authentication. The headers contain all headers from the request. The hook must return Ok(())
to allow the request, and Err(gateway_request::Error)
to deny it.
Let's create simple authentication logic. We'll check if the Authorization
header exists and contains the value foo
:
struct MyHooks;
#[grafbase_hooks::grafbase_hooks]
impl grafbase_hooks::Hooks for MyHooks {
fn on_gateway_request(
&mut self,
context: grafbase_hooks::Context,
headers: grafbase_hooks::Headers,
) -> Result<(), grafbase_hooks::ErrorResponse> {
match context.get("Authorization") {
Some(header) if &header == "foo" => Ok(()),
_ => {
let error = Error {
message: String::from("ACCESS DENIED"),
extensions: Vec::new(),
};
Err(gateway_request::ErrorResponse {
status_code: 403,
errors: vec![error],
})
},
}
}
}
First, we check for the Authorization
header. If we find it, we check if its value matches foo
. A matching value returns Ok(())
to allow the request. A missing header or non-matching value returns an error to deny the request.
This example shows how to implement custom authentication logic using hooks. You can create more complex logic, like checking the using an external service by triggering an HTTP request.