Custom headers in actix_web 4 request

Hey everyone!
I wanted to ask how I can access custom headers in a normal request with actix_web 4.
The following way works, but I want to access a header like X-Auth-Stuff, which I can't do with the method below. Any ideas?

pub async fn some_handler(headers: web::Header<http::header::ACCEPT_ENCODING>) -> Result<HttpResponse, Error> {

Thanks for your help!

Hey @Mawoka,

you should be able to extract custom headers from a more general HttpRequest.

From the HttpRequest you can then extract the headers as a HeaderMap, like so (:warning: I haven't compiled this :warning: ):

pub async fn some_handler(req: actix_web::HttpRequest) -> Result<HttpResponse, Error> {
    let headers = req.headers();
    if let Some(auth_header_value) = headers.get(HeaderName::from_static("x-auth-stuff")) /*note: header name must be all lower case*/ {
        // do something with the auth value
    } else {
        // custom auth header not found

Please keep in mind that HeaderName::from_static only accepts lowercase letters as the header name (according to HTTP2 spec).

Also keep in mind that HeaderMap is a "multi-map", which means multiple values can be stored per key. If you want to get all values that are associated with a certain header name, use get_all method.

I hope this helps. :slightly_smiling_face:

Maybe just an additional info on this topic:

It seems you might want to protect a route from unauthorized access.

In this case, you might also be able to use Route guards:

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.