4. Permission interception control \ AccessToken jwt - API nodejs + Express + MySQL in the back end of Blog

Keywords: Javascript JSON github

Authority control

Business requirements: View user list interface (only available to administrators), update user information interface (only available to current corresponding users)

At this time, middleware needs to be added to realize permission control:

At this time, we need to learn the following: AccessToken jwt

AccessToken jwt

Learn before class
Getting started with JSON Web Token
http://www.ruanyifeng.com/blo...
web authentication based on jsonwebtoken (JWT) (Node version Implementation)
https://segmentfault.com/a/11...
node-jsonwebtoken
https://github.com/auth0/node...

The node-jsonwebtoken@7.2.1 plug-in is used in this article

Now attach the token service logic code

/**
 * token service
 * add by boomer 2019-05-03 21:57:11
 */
var Promise = require("bluebird");
var config = require('config-lite'); //To configure
var jwt = require('jsonwebtoken'); //json token

module.exports = {
    /**
     * Set token create token
     */
    setToken: function(payload) {
        // var expiresIn = Math.floor(Date.now() / 1000) + (1 * 60); // var expiresIn = '24h';
        var expiresIn = Date.now() + 3600000 * 24;//24 hours later
        var token = jwt.sign(payload, config.token.secretOrPrivateKey, {
            expiresIn: expiresIn, // Set expiration time
        });
        return {
            token: token,
            expiresIn: expiresIn,
        };
    },
    /**
     * Verify whether the token is correct: pass in the current token and the current user uuid
     */
    verifyToken: function(token, userUuid){
        return new Promise(function(resolve, reject) {
            jwt.verify(token, config.token.secretOrPrivateKey, function(err, tokenData) {
                if (tokenData && tokenData.uuid == userUuid) {
                    resolve('ok');
                }else{
                    reject('fail');
                }
            });
        });
    },
    /**
     * Route verification token
     */
    verifyRouterToken: function(req, res, next, isAdmin) {
        //accesstoken is automatically lowercase
        var token = req.headers.accesstoken;
        if (!token) { // If there is no token, an error is returned
            res.json({
                code: "401",
            });
            return;
        } else { //Verify token
            jwt.verify(token, config.token.secretOrPrivateKey, function(err, tokenData) { //tokenData has a value only when the token is correct
                if (err) {
                    res.json({
                        code: "402",
                    });
                    return;
                } else {
                    //Verify administrator
                    if (isAdmin && !tokenData.isAdmin) {
                        res.json({
                            code: "403",
                        });
                        return;
                    } else if (!isAdmin && tokenData.uuid && !tokenData.isAdmin) {
                        //Verify userUuid to prevent ordinary users from logging in and modifying other people's data
                        var userUuid = (req.body || req.query || req.params)['userUuid'];
                        if (userUuid && userUuid != tokenData.uuid) {
                            res.json({
                                code: "403",
                            });
                            return;
                        } else {
                            next();
                        }
                    } else {
                        next();
                    }
                }
            });
        }
    },
    /**
     * Clear token
     */
    delToken: function(token) {
        if (!token) {
            return 'delTokenFail';
        } else {
            jwt.decode(token);
            return 'delTokenSuccess';
        }
    },
};

Access token is usually obtained when login / registration is successful and then cached locally. Every time a front-end request is made, an effective access token is put in the headers (the heartbeat mechanism of token is updated when the front-end is written later), then the request is sent to the back-end, and the back-end performs permission interception through the token intermediate. After the verification is passed, the subsequent business logic can be executed
Now, the backend generates the code of AccessToken through the tokenService.setToken method above:

Posted by damianraine on Sun, 17 Nov 2019 11:42:03 -0800