Antonin Mrchd
Antonin Mrchd

Reputation: 666

node js JWT get current user

I am working on an app which has authentication implemented using Node JS, JWT and Sequelize for the API. I'm using React JS / redux on frontend. I've successfully implemented the login/logout/register parts of the application, but now I need access to the current_user which logged in.

I've put JWT in the localStorage, but I want to have access to the user ID, user email, user name and more information about my user currently being logged in.

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

I'm a bit lost with this, someone please help me find some useful resources or advices!

Thanks!

Upvotes: 4

Views: 13001

Answers (4)

Human programmer
Human programmer

Reputation: 504

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.

Upvotes: 0

NonameLover
NonameLover

Reputation: 90

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.

Upvotes: 0

Paul
Paul

Reputation: 36319

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: '[email protected]' }
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.

Upvotes: 6

Alex K
Alex K

Reputation: 890

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.

Upvotes: 3

Related Questions