Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best pratice for varnish cache content with authorization header

I have implemented a facebook-like message system in my application, and now I try to use varnish to improve performance.(i.e. caching user message conversation). user conversation must be protected so that only authenticated user can view it.

I used oauth2 to authorize/authenticate user, so the request to retrieve user messages is something like this.

curl -X GET user/{id}/message/thread/{thread} -H 'Authorization: Bearer XXX'

As far as I understand of varnish cache, default setup of varnish will not cache the content if the request has Authorization or Cookie header, I can stripe headers info in varnish setup, but if i do so, i lost the control in backend to identify if user is authenticated user.

So my question is: what's the best practice to use varnish cache in this case?

At the moment, I have a workaround that instead send Authorization in headers, I appended it as a query string, so it will be something like

curl -X GET user/{id}/message/thread/{thread}?access_token=XXX

it works, but I felt it's not a proper way, any ideas?

Thanks!

like image 221
huajun li Avatar asked Dec 07 '25 05:12

huajun li


1 Answers

Quite simply if the content changes because of a http header then you need return a Vary header specifying that.

To get Varnish to cache content with Authorization headers is easy. You just define your own vcl_recv method and remove this part:

if (req.http.Authorization) { return (pass); }

That will let Varnish cache it. Which is the first part. The second part is to not cache content for one user and serve it to another. To do that the best way is to have your backend respond with a HTTP Vary header that has Authorization in the list. This tells Varnish that the content varies based on that header. And a change in that request header means different content.

The authorization header will be different for different users and so you will get many objects for the same url. But that's what you want.

like image 116
dalore Avatar answered Dec 09 '25 19:12

dalore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!