Evert Evert - 1 year ago 135
HTTP Question

HTTP Caching for authenticated REST apis

I'm currently building a REST API. Many of the resources I'm creating will always be identical regardless of who's accessing the resource. The few that aren't will have a

Vary: Authorization

There's two exceptions:

  1. You will get a 401 response if you're not authenticated.

  2. You might get a 403 response for some resources that you don't have access to.

My question is, in this scenario would it still be possible to setup Caching correctly. In particular, I would like to use a reverse proxy such as nginx, varnish or haproxy to offload the main service.

Are there elegant solutions to this problem?

Answer Source

Vary: Authorization is unnecessary; responses to requests with Authorization are automatically private, and won't be cached by shared caches.

You can send Cache-Control: public to override this; responses with that can be cached using the normal rules.

However, if you want those responses to remain authenticated, you need to impose authentication. You can do that by also sending Cache-Control: no-cache, which will force the cache to check with the origin before serving a stored response.

If you just want to have your reverse proxy (e.g., Varnish, nginx) do the caching, it's likely that it has a way of being configured to impose authentication on the "edge", serving the responses from cache when the request has the proper authentication. Check its documentation for details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download