• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Storing user data using jwt

Resolved: Storing user data using jwt

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I am fetching user data from graphql backend through apollo client. My goal is to keep the user logged in so I signed jwt token with all user data, passed it to localStorage(only the token) decoded it and passed all values to redux-store.
userLogin:
reduxSlice
I am wondering if this is ok that the token is holdin too much info like:
There is another effective way saving user data and keep him logged in ?

Answer:

it’s not recommended (actually very dangerous) to return all information with the jwt token especially password. I think userId is enough! But you can also return username, firstName, lastName, etc. But in some cases even returning email address is not a good approach for some user privacy reasons.
I mean by that you have only to get the userId once there is a user and the credentials are correct, then :


Now after signing the jwt token , you can set whatever data from user inside some redux state or even react context , (choose your favorite) , but DON’T set any password in the localStorage.
Update: at the end you should store the user from the payload like this :


Btw you should check the localStorage only to get the token and verify it , then based on userId you need to fetch the user and store it, here is an example :

const getUser = React.useCallback(async (userId) => {
try {
const res = await axios.post(‘/auth/login’, {userId}, {
credentials: ‘include’,
withCredentials: true
});
const { accessToken, user } = res.data;
setState((currentState: IState) => ({
…currentState,
user,
loading: false,
isAuth: !!accessToken,
accessToken
}));
} catch (err) {
setState((currentState: IState) => ({
…currentState,
user: null,
loading: false,
isAuth: false,
accessToken: ”
}));
}
}, []);

useEffect(() => {
getUser(userId);
}, [getUser]);

useEffect(() => {
const jwtToken = localStorage.getItem(‘jwtToken’);
if (jwtToken && jwt_decode(jwtToken)) {
const { exp } = jwt_decode(jwtToken);
const currentTime = Date.now() / 1000;
if (exp < currentTime) { getUserById(userId); } } }, [getUser]);[/code]


If you have better answer, please add a comment about this, thank you!

apollo-client graphql reactjs redux
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Modify entity using Action in C#

24/03/2023

Resolved: How to give rank on datetime column group by another column with userid in it

24/03/2023

Resolved: Passing 2 functions in onChange in react

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.