简体   繁体   中英

Securely storing auth token in React Frontend

I am currently working on a single page react app. This app will not require any login and it will be publicly available. I am making a POST request to a webhook of another API that I do not have access to and that I do not maintain. This API required me to send an authentication token via the POST. I wonder how I can securely store this token so that it does not get out in the world. I need to send it as is so storing it in a cookie that a backend provides is not an option. Storing in in JWT will not work as I can decode that without the secret.

Is there even a way to store the token without exposing it to the world?

I hope the issue is clear, if not let me know and I'll explain better.

Thank you all for your time!

I would usually have a local Express server running and proxy the request through that.

You would set up a route in your Express app that you would POST to from your React front-end, this Express route handler then makes the call to the external API from the server side which has the token to put in the header. Then the response is returned to your React front-end without it knowing anything about the external API or tokens.

You can't store the token in front-end. either you need to use cookies/session to store the token. If you want to store the token you need to encrypt it and store it will be the better option.

Please check here to understand the JWT token mechanism

if the web app doesn't have a login. you can't generate token without user details.

The token should be passed in the header of the request for best practices.

If you're using create-react-app to instantiate your React project, have you looked into using an environment variable to store the token? It's not 100% safe and secure, check here for the cons, but can be a quick fix without a separate proxy request. You can make an .env file (make sure to add it to your .gitignore if using git) in the root of your directory and define variables there. They need to start with REACT_APP, like REACT_APP_SECRET=1234 and can then be referenced where you need them in your app with process.env.REACT_APP_SECRET .

Read more about environments in React here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM