Security JWT in payload

189 views Asked by At

I am developing a REST API and I have some doubts about what is the correct way to do the authentication via JWT, what information to include in the payload of the token and what are the best practices and the safest:

Is safe include the mongoDB’s ObjectId inside of payload token?

{
  "sub": "507f191e810c19729de861ea",
  "name": "John Doe",
  "rol": "admin"
}

After check the 'sub' in the token if the user navigates to protected route such as:

“api/dashboard /: userId“

And comparate in the reques, this example in Express.js

.get('api/dashboard/:userId', (req, res)=> {
  if(Req.params.uiserID != token.payload.sub) {
     Res.status(401).send({ message: ‘No authorization’})   
 } 
})

Is the above considered safe?

1

There are 1 answers

0
pedrofb On BEST ANSWER

The sub claim identifies the principal that is the subject of the JWT, and is expected to be unique in the context of issuer ( or globally). Sending an internal ID is not a bad practice as long as you respect it to be unique, do not change and do not reveal private data. (An internal hexadecimal string can not be considered private)

In server side you need to verify the signature of the token to check authenticity and that the data has not been altered. After this is safe to check access to protected resources using the data embedded in JWT