How to dynamically control access to static files?


#1

I’m just getting started with Workers and I’m trying to figure out how to limit a user to only his own static files (mostly images).

The static files are arranged like this:
/images/user001/images.jpg
/images/user002/images.jpg
/images/user003/images.jpg

After “user001” logs in, they should only be able to access files in the /images/user001 directory.

I’m trying to figure out how to pass authentication and access information back to the Worker script so it can control which files can be accessed. Is this kind of dynamic access control even possible?


#2

Hi! There are several ways to do this. One of the best would be to generate signed tokens which are checked inside the Worker before responding to the user with the file.

For example, if in your backend you generated a token composed of: HMAC(userId, secretKey), and then made your requests something like: /images/userId/images.jpg?token=token you could use that same secretKey to check the HMAC token before responding with the file in your Worker.

In practice you often want to also include a timestamp of some sort, to make your tokens only valid for a certain amount of time.


#3

Thanks for the reply. After I made my original post, I found something similar (JSON Web Tokens) that I think will do the job. They have timestamps and several other useful features:
https://jwt.io
https://en.wikipedia.org/wiki/JSON_Web_Token
https://dev.to/neilmadden/7-best-practices-for-json-web-tokens

After I generate a web token (which will contain the access details), I should be able to set a cookie in the browser. Then the Worker can authenticate the cookie data and use the access details to set rules that determine which URLs can be accessed.

If my thinking is correct and I took this to an extreme, I could probably create fine-grained URL access control and let Cloudflare handle it all on the edge. All I would need to do is create a JWT token on the initial signin. Then the JWT cookie would determine what could be accessed.

When I get some code working, I’ll post an example.


#4

Great find, yes! Please do post what you come up with.