Access static link on Node using authentication

Asked

Viewed 35 times

-1

In my backend I have this:

app.use('/files', express.static('upload'))

Generating static image and pdf links for users to access. In my frontend I put a button where the user can display the static link file.

But when opening the tab with the link always gives unauthorized, This is due to authentication middleware. How can I set the headers with the authentication data if who makes the request and the browser itself and not my application?

NOTE: One solution is that I do not authenticate the static file path, but security is compromised.

2 answers

1

The browser exposes several Apis for you to develop the experience you want for your user.

When you navigate to a link using an Anchor element, you are making a GET type HTTP request for the link endpoint resource (e. g.: http://example.com/meu-pdf) and updating the browser Location.

In this case, you don’t just want to browse, you want to make a GET type HTTP request and pass what your server needs in the header from saved cookies or whatever. Javascript does this natively with XHR.

https://developer.mozilla.org/en-US/docs/Web/API/XMLHTTPRequest.

You can use the window.fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API or install libraries as Axios.

I suggest testing calls and responses in programs like Postman, to find out exactly what you need to program on the front end with javascript. You will also need to read the documentation of your auth middleware to understand what it is asking for.

Good luck

1

The simplest case would be that you don’t really authenticate the static file route, but I believe you need to ensure that users access the files only through the platform and not just through a link. This way, I recommend that you create a controller to download these files and call this controller through the route from your application. You can do this using the Express download method.

Thus you guarantee the authenticity of who is downloading the files and the code becomes more cohesive.

Express download method reference: https://expressjs.com/pt-br/api.html#res.download

Browser other questions tagged

You are not signed in. Login or sign up in order to post.