Verifying JWT tokens

Again, when a token is being used, it is up to the server that generated the token to verify that it is valid before use. Let's create a POST handler in our Express server that will verify the token as follows:

router.post(`/validate-user`, (req: any, res: any, next: any) => { 
    serverLog(`POST /validate-user`); 
 
    console.log(`req.body : ${JSON.stringify(req.body)}`); 
 
    if (req.body.token && req.body.token.length > 0) { 
 
        try { 
            let verifiedJwt = jwt.verify(req.body.token, jwtSecret); 
            return res.json(verifiedJwt); 
        } catch (err) { 
            serverLog(`/validate-user : token error`); 
            res.status(401).send('invalid auth token'); 
        } 
    } else { 
        serverLog(`/validate-user : token not found error`); 
        res.status(401).send('Invalid auth token'); 
    } 
 
}); 

Here, we have defined a route handler for a POST to the endpoint named validate-user. This handler checks for the existence of a token payload, and then calls the verify function on the jwt library. The verify function takes the token itself as input, as well as the secret that we used to sign the token in the first place. Note that we have wrapped this call in a try catch block, as the jwt library will throw an exception if the token cannot be verified correctly. If the token is valid, we simply return its contents as a JSON structure. If the token cannot be verified, we return a 401 HTTP status code with an error message.

Our two Express endpoints, then, have successfully created, or signed a JWT token, as well as verified this token. Both parts of this have used the same secret key.

Note the importance of this verification step. The token is a simple string, and can be decoded fairly easily. This means that it can also be modified very easily. Even the website at jwt.io can modify the contents of the token and generate a new encrypted string. Once a JWT token has been modified, however, it will fail verification. This means that it is impossible to regenerate a modified token without the secret key. So each time a server needs to do something on behalf of a user, it must verify that the token provided has not been tampered with in any way.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.55.14