How to correctly store a user's jwt token on React - reactjs

What is the best, most secure and professional way to store a user's jwt token after logging into React?
I see many people saying that using localStorage is a good way.
For example:
localStorage.setItem("token", "ey.......")
Others say to use a library like Redux or others.
Could someone advise me?
Thanks

Redux hasn't built-in persistent storage. It means on refresh of the page your key might be lost, and you need to re-login(authorize) once again. There is no "correct" way, there is "desired behaviour".
As already was suggested to you in comments you can use also cookies as a storage of the key, and I think it is one of the most preferable ways for now, as it is kinda safe solution.
Redux has middleware to persist its state. You can choose there what kind of storage you want to use as a long-term storage.
But, I wouldn't recommend you add redux to the project just to have it.
And there is a good answer on difference between most popular browser storages.
Read carefully and choose smart, there are some major differences like scope and secure between them.

Although storing data in localStorage is not the worst choice. In my opinion the best, most secure and professional way will be following OWASP guide.
They suggest using sessionStorage with browser fingerprint as a precaution along with CSP

Related

should I state my user information in redux?

Should I safe my user information in redux state or context ?
Like email,username,isLogged
I use this in multiple components so what you recommend ?
If you're already using redux anyway: Yes. The user information is considered global application state and consumed by multiple components, so redux is a perfect fit.
As #rohit-aggarwal pointed out it is nowadays considered safer to not store tokens or passwords in redux. http-only cookies are a good way to restrict access to sensitive tokens from the JS runtime. They can be sent along in requests to the authentication backend without exposing them to potentially malicious JS code.

Secure JWT token handling in React

I have been searching for a satisfying answer for an hour and I still can't figure out the answer to the question: how to securely store the JWT token on the client side with React?
From what I have read, the localStorage solution in undesirable as it's accessible from third-party scripts. A more secure solution proposed is to use a HttpOnly cookie, but the problem is, it is inaccessible via js, hence it is useless in React.
Therefore, how can I securely store a JWT token on the client side?
In short - you can't securely store token in the browser. If your code has access to the token, then any attacker can also get access to it. That said you can mitigate some risks and decide on a solution which might be "secure enough" for your needs.
E.g. it might be enough for you to keep tokens in the local storage, if losing such a token does not pose a great risk - maybe the data handled by your website is not sensitive.
A viable option is to keep the token in the memory. This way it's a bit more complicated to steal it. Then of course you need to get a new token every time you refresh the page, but you might use SSO cookies to automatically get new tokens in the background.
If you want to go with current security best practices for SPAs, you should investigate the Backend-For-Frontend pattern. You add a lightweight backend component which handles tokens and OAuth flows, and which uses regular cookie-based sessions in communication with your React app. At Curity we created an example implementation of such a component, which you could use as inspiration: https://github.com/curityio/bff-node-express
You can have a look at this great video: https://www.youtube.com/watch?v=lEnbi4KClVw where Philippe de Ryck goes into detail of why it's not possible to securely store tokens in SPAs.

Standard for storing session key

After doing a bit of research on this topic, it seems like session keys have typically been stored as cookies which is nice because they get automatically added to requests. I've been seeing that developers prefer localstorage to cookies due to less restrictions, though. I am building a React frontend, so persisting a reducer in localstorage and managing the session key in that reducer would be very easy. I would need to append this to requests, which seems to be the only downside. Wondering if there is a standard for how this should be done. Thank you in advance!
There are only a few places you can store your keys in the browser:
SessionStorage / LocalStorage
Cookies
Web workers
in memory
Cookies
Cookies are one of the best places to put sensitive keys as long as it has the correct configurations/attributes with them. This includes, httpOnly, secure, SameSite, Domain and making sure they expire in a reasonable time. more reading here for how to set these attributes properly.
Cookies are good to use since they are as secure as HTTPS and cannot be accessed via javascript (if correct atrtibutes are set i.e httpOnly). But note there are still vulnerabilities you have to watch out for such as a CSRF attack, and you would have to include a CSRF token to counter this vulnerability since the cookie gets added to the headers automatically by the browser.
LocalStorage / SessionStorage
LocalStorage and session storage are poor places to keep keys since they are accessible via javascript. You can look here on how Auth0 recommends to store keys, and note they persuade not to store it in localStorage for said reasons.
In Memory
You can store the key in javascript memory (use a closure to encapsulate your key). This has a downside as the key will not persist after refresh/close/new tab etc but is still pretty secure
Web Workers
Web Workers are another place you can store the key. Workers run in a separate global scope than the rest of the application so it keeps them pretty secure, and you can have fine grain control as to what apis to send they key to.
Auth can be tricky and it can be easy to forget to include something important, so make sure you are well read on all attributes and how each piece works. Or go with a pre made options like Auth0 or single sing-on.

What is the true place/way to save api keys in react app?

I'm working on a react project in team. We are using a few third party services and these services require api keys. Right now We are storing these key right in the code. As I know It's not good and dangerous.
I tried to find some recommendations in that regard. All ways to solve this problem I see now are:
create .env file and store all key there (but in this case I need to share my keys with other members of the team)
or move all keys to server and always make a calls to the server in order to get required information (but in this case I have no idea how to work with external components which are require keys, for example google maps/places/drawing and so on).
Which way are you using in your team and why? I would like to understand what's the best solution for me.
Thanks!
You cannot really hide an API key used for a client-side API such as JavaScript API and its services. The right way to secure your API key is to add API key restrictions.
Check out Google's guide on API Key Best Practices. You may also want to have a look at this answer.
Hope this helps!

Authentication for single-page apps

Background
I am looking at the OAuth 2.0 Implicit Grant flow where a user is redirected to an authentication service and a JWT token is sent back a Single Page Application(SPA). The token is stored in a cookie or in local storage and, in the examples i have seen, the application will hide/show certain pages based on whether it can find the token in storage.
Issue
The problem is that in all the examples (official from service providers), i was able to manually add any random but properly formed token to the browser's local storage and got access to the 'secured' pages.
It was explained to me that you cannot validate the token in the SPA because that would require exposing the client secret and that you should validate the token on the API server. This means that you can 'hide' the pages but it is really easy to see them if someone wants to. Having said that you are unlikely to cause any real damage because any data retrieval or actions would need to go through the API server and the token should be validated there.
This is not really a vulnerability but the documentation and examples I have seen do not explicitly cover this nuance and i think that it could lead naive programmers (like myself) to think that some pages are completely secure when it is not strictly the case.
Question
It would be really appreciated if, someone who is better informed than i am, confirm that this is indeed how SPA authentication supposed to work?
I am far from an expert, but I have played a bit in this space. My impression is that you are correct, any showing/hiding of functionality based solely on the presence of a token is easily spoofed. Your SPA could, of course, get into verifying an access token.
But that may just make it a little more challenging to spoof. If someone wants to fake the client into thinking it has a valid token, they can likely manipulate the client-side JS to do that. Unfortunately that's the nature of client-side JS. Much of the code can be manipulated in the browser.
Thus far this is speaking to protecting the user from seeing a UI/UX. Most applications are only beneficial when they have data to populate their UI. That's where the API access token strategy is still sound. The server will verify the token and not give the client any data without it.
So while it's unfortunate that JS can be easily spoofed and manipulated to show things the developer would rather not make visible, this isn't typically a deal-breaker. If you have some awesome UI feature that doesn't need data, and you need to secure access to that UI itself, this model may not be the greatest.

Resources