How to use jsonwebtoken

Comprehensive jsonwebtoken code examples:

How to use jsonwebtoken.default:

94
95
96
97
98
99
100
101
102
103
    }
    jsonwebtoken_1.default.verify(refreshToken, REFRESH_TOKEN_SECRET, (err, decoded) => {
        if (err) {
            return res.sendStatus(403);
        }
        const accessToken = jsonwebtoken_1.default.sign({ id: userId, username: decoded.username }, JWT_SECRET, { expiresIn: "3600s" });
        return res.status(201).json({ token: accessToken });
    });
}
catch (error) {

How to use jsonwebtoken.decode:

125
126
127
128
129
130
131
132
133
// Check if JWT Access Token has expired
// logic to add 30 seconds to the check is to avoid edge case when the token is valid here
// but expires just before the api call due to ms time difference, so if token is expiring within next 30 seconds, refresh it.
isTokenExpired(token) {
  const now = Date.now().valueOf() / 1000;
  const payload = jsonwebtoken.decode(token);

  return (!!payload['exp'] && payload['exp'] < (now + 30)); // Add 30 seconds to make sure , edge case is avoided and token is refreshed.
},

How to use jsonwebtoken.verify:

144
145
146
147
148
149
150
151
152
153
154


router.get('/user', passport.authenticate('jwt', {session: false}), (req, res) => {
  const thisSession = req['session'];
  let userToken;
  try {
    userToken = jsonwebtoken.verify(thisSession['passport'].user.jwt, config.get('oidc:publicKey'));
    if (userToken === undefined || userToken.realm_access === undefined || userToken.realm_access.roles === undefined) {
      return res.status(HttpStatus.UNAUTHORIZED).json();
    }
    thisSession.roles = userToken.realm_access.roles;

How to use jsonwebtoken.sign:

252
253
254
255
256
257
258
259
260
261
  }
  return { user: await User.query().findOne({ email: userObj.email }), first_time_login };
}

createToken = (user) => {
  const JWTtoken = JWT.sign({ id: user.id, email: user.email }, CONFIG.auth.jwt.secret, {
    algorithm: 'HS256',
    expiresIn: CONFIG.auth.jwt.expiresIn,
  });
  return JWTtoken;