I have a MEAN stack application with REST, like api. I have two types of users: user and admin. To sign the user and save the session, I use jsonwebtoken jwt, like this (simplified):
const jwt = require("jsonwebtoken"); //example user, normally compare pass, find user in db and return user let user = { username: user.username, userType: user.userType }; const token = jwt.sign({ data: user }, secret, { expiresIn: 604800 // 1 week });
To protect my express routes, I do this:
in this example, this is the "get user" route, the administrator is allowed to receive information about any given user. A "normal" user is allowed to receive information about him himself, why I compare the requested username with the username decoded using the token.
let decodeToken = function (token) { let decoded; try { decoded = jwt.verify(token, secret); } catch (e) { console.log(e); } return decoded; } // Get one user - admin full access, user self-access router.get('/getUser/:username', (req, res, next) => { let username = req.params.username; if (req.headers.authorization) { let token = req.headers.authorization.replace(/^Bearer\s/, ''); decoded = decodeToken(token); if (decoded.data.userType == 'admin') { //do something admin only } else if (decoded.data.username == username) { //do something user (self) only } else{ res.json({ success: false, msg: 'not authorized' }); } } else { res.json({ success: false, msg: 'You are not logged in.' }); } })
So my question is: how safe is this? Can someone manipulate a session token to change the username to a different username? or even change userType from user to administrator?
My suggestion. Only if they know the "secret", but is there enough security? a secret is, like a plain text password, stored in code. What is the practice?