node js JWT get current user

Viewed 8702

I work on app with an authentication using Node JS, JWT and Sequelize for the API and I'm using React JS / redux for the front part. I'm successfully implemented the login/logout/register parts for the application, but now I need to access to the current_user logged in.

I put a JWT in the localStorage, but I want to have access to the user ID, user email, user name and more informations about my user currently logged in.

Should I use Cookies ? LocalStorage ? Or should I create a currentUser method in my API ?

I'm a bit lost with this, if someone could help me find some usefull resources or advices !

Thank !

4 Answers

If you put that information in the payload of the JWT, then you can get it without decoding on the server or needing the secret, and can therefore put the token in LocalStorage for use whenever. By the spec, a JWT is <headerINfo>.<payloadInfo>.<signature>. So on the client, you can just do:

// given a payload object of { username: 'bob', userid: 1, email: 'bob@example.com' }
const tokenParts = token.split('.');
const encodedPayload = tokenParts[1];
const rawPayload = atob(encodedPayload);
const user = JSON.parse(rawPayload);
console.log(user.username); // outputs 'bob'

Obviously, this info is available to any client that has access to the Token, so you only want to put stuff in the payload that that's OK for.

Storing the token in LocalStorage is fine. If you need to fetch the user details, create an endpoint in your API such as getUser. You can then use jwt.decode(accessToken, JWT SECRET HERE) and return the decoded value (which will be your user) assuming the accessToken is valid.

You can make a middleware if you haven't already that will ensure that user info is always available to those routes that require it:

const auth = jwt({
    secret: JWT_SECRET,
    userProperty: 'payload',
    algorithms: ['HS256']
});

module.exports = auth;

Then you should have req.payload with user details. Alternatively you can check the Authorization property in your headers depending on how you set up your app.

When logging in, server should send token and user data, you can store that data in Redux store. Then simply request data from there. When user reloads page, send API request with JWT token and server should return user data, that you will again put in Redux store.

Related