Use node to implement the token Acquisition Interface in a similar style, nodetoken
Flowchart
Dependency
"dependencies": { "express": "^4.12.3", "jsonwebtoken": "^5.0.0", "mongoose": "^4.0.2", "redis-fast-driver": "0.0.9", }
Get token code
Function get_interface_token (req, res) {Jiekou. findOne ({username: req. query. username}, function (err, interface_find) {if (err) throw err; if (! Interface_find) {res. json ({success: false, message: 'authentication failed, user name cannot be found'});} else if (interface_find) {// check the password if (interface_find.password! = Req. query. password) {res. json ({success: false, message: 'authentication failed, password error'});} else {// Add token creation time for the interface, make the token obtained each time different var time = new Date (); interface_find.token_create_time = time; // Create token var token = jwt. sign (interface_find, config. secret, {expiresInMinutes: 1440 // set the expiration time}); r. rawCall (['hmset', req. query. username, 'Token', token], function (err, d) {if (err) throw err ;}); r. rawCall (['expir E ', req. query. username, config. token_expire_time], function (err, d) {if (err) throw err ;}); // return token res in json format. json ({success: true, message: 'Enjoy your token! ', Token: token });}}})}
Check the token code
Function checktoken (req, res, next) {// check the post information or url query parameter or header information var token = req. body. token | req. query. token | req. headers ['x-access-token']; // parse token if (token) {// confirm token jwt. verify (token, config. secret, function (err, decoded) {if (err) {return res. json ({success: false, message: 'token information error. '});} else {console. log (decoded. username); r. rawCall (['hexists', decoded. username, 'Token'], fun Ction (err, d) {if (err) throw err; console. log (d) if (d = 1) {// if no problem occurs, save the decoded information to the request for req. decoded = decoded; next ();} else {return res. status (403 ). send ({success: false, message: 'token has expired! '}); Next ()};} else {// if no token exists, the return res error is returned. status (403 ). send ({success: false, message: 'token is not provided! '});}}
Code file structure
For more information, see create a restful api with nodejs express.