Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Setting Authorization header in HttpResponse throws "borrowed value does not live long enough"

I am using actix-web to authenticate a user in a REST api. The endpoint for authenticating a user sets the "Authorization" header of the response object to a generated token.

async fn signin(request: web::Json<UserAndPw>) -> impl Responder {
  let token = String::from("thisisatest");
  HttpResponse::Ok()
    .header(AUTHORIZATION, HeaderValue::from_static(&token))
    .json(ApiResponse {...})
}

This is error occurs when compiled:

.header(AUTHORIZATION, HeaderValue::from_static(&test_token))
                       -------------------------^^^^^^^^^^^-
   |                   |                        |
   |                   |                        borrowed value does not live long enough
   |                   argument requires that `test_token` is borrowed for `'static`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your case token is a local variable and a reference to it (&token) is definitely not with a static lifetime. The compiler error explains it and shows it to you.

You probably want to create a HeaderValue instance some other way, not via from_static. For example like this: HeaderValue::from_str(&token).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading