Во-первых, я использую Passport.JS, Passport-JWT и JWT:
$ npm i -s passport passport-jwt jsonwebtoken
В файле app.js (предполагается, что вы используете Express.JS) вы настраиваете паспорт
const passport = require('passport');
// TODO in case we cache need to to verify cache first
passport.use(new passportJWT.Strategy({
'secretOrKey': 'a secret string, longer than this one', // The secret mut be the same all the times
'jwtFromRequest': passportJWT.ExtractJwt.fromAuthHeaderAsBearerToken()
}, (payload, done) => {
// note that if the token is invalid an error will be thrown, else
// payload will be set as req.user here
done(null, payload);
}));
app.use(passport.initialize());
Чем использовать passport.authenticate в маршрутах с контролируемым доступом:
app.get('/home', passport.authenticate('jwt', {'session': false}), dashboard);
В вашем методе входа в систему после успеха вы дарите токен пользователю с данными, которые вы хотите сохранить.в полезной нагрузке:
const jwt = require('jsonwebtoken')
// Here you choose the data tha will be on your payload
jwt.sign({'id': user._id, 'username': user.username, 'email': user.email}, 'a secret string, longer than this one');
Наконец, вы можете получить доступ к данным через req.user int маршруты, которые требуют аутентификации