jwt login registration
jwt concept
Token does not need to be stored in the database.Just generate the key behind the scenes, then put the token in the request body or header when the client sends the request. When the client receives the token, it is stored in the local store or cookie. Note that sensitive information cannot be stored in the token here, otherwise it will be acquired (such as cookie or request body) and decrypted backwards to expose sensitive information.Such as passwords;
token contains three pieces of
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9//Header Information This is fixed write-dead {'type':'JWT','alg':'HS256'} . > eyJ1c2VyIjoid2FuZyIsImVudmlyb25tZW50Ijoid2ViIwiZXhwaXJlcyI6MTUzNTUyMDk1MTcxOX0//Carrier is such as username sent by client . > 4rmP6UeeJ3mQbHfplruH15PvuUxPzFTxAfVnPgA7sgo//Key A token is formed by converting the header and the carrier to base64 encoding, then encrypting the header and the carrier to the sha256 algorithm to generate the key (that is, the third step). Changing this idea to code will result in the encode in the jwt-smile package, and decode is obtained for reverse decoding.
encode and decode in jwt-smilp
{username:username}//Time can also be set in the carrier as well as other jwt.encode({username:username},sercet)//sercet's own defined key jwt.encode(token,sercet)//Decrypt
The whole process of login registration
Enter the login page, enter the account and password, click on the login request interface, and the background will look for the corresponding account password in the database. If it exists, the background will generate a token and be stuck in the request header (or response body).After giving the front end, the front end gets the return value and stores it in the cookie or request header. The front end intercepts the request in axios and inserts the key into the request header, so that each request sent carries the token, and the background receives the token to verify whether it is the correct token. If so, it proceeds to the next step, and if not, prompts the front end.
Implementation of node background code
Build a new src file after the node frame is builtApp.jsThe file code is as follows
let express = require('express') let app = express() //Get body of req let bodyParser = require('body-parser'); //Introduce your own logon verification compliance file let retoken = require('./retoken/retoken.js') //The following two bodyParser s also parse json data in post s app.use(express.json()) //Urlencoded parses the x-ww-form-urlencoded requester body app.use(express.urlencoded()) //The object returned is a key-value pair, the value of which is either'String'or'Array' when the extension is false, or any data type when the extension is true. app.use(bodyParser.urlencoded({ extended: true })) //Use your own middleware written above app.use(retoken) //Logon Interface File app.use('/login', require('./login/index.js')); //Unify error information app.use((err, req, res, next) => { if (err) { res.status(500).json({ message: err.message }) } }) //Default listen on port 3000 app.listen(3000, () => { console.log('Service Enabled Successfully'); })
retoken.js
//Use third-party plug-ins let jwt = require('jwt-simple'); //Define encryption and decryption keys (write freely) const jstSecret = 'mengyuhang' function checkToken(req,res,next){ //Determine that token verification is not required if it is a login or registered interface if(req.url!='/login/login'&&req.url!='/login/create'){ //The front end here is to plug token directly into the cookie so I get it directly in the cookie let tokenClone = req.headers.cookie; //Token is passed in this form: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Im15aDEyMyIsV4cGlyZXMiOjE1OTQwNDU4NDc1NzN9.PwIAp3nXIscIvgXykjmO6CbIFHpG6-2HgQU4 //Intercept after equal sign let token = tokenClone.split('=')[1] if(token){ //If so, does the encrypted username and verification time expire here {username:'myh123', expires: 1594045847573} var decoded = jwt.decode(token, jstSecret) //Return to landing expiration if it is longer than the landing time I set if(Date.now()>decoded.expires){ res.json({ code:'-2', message: 'Landing Expiration' }) }else{ //Otherwise, execute down next() } }else{ //Return prompt if no token exists res.status(401).json({ code:"-1", message: 'you need login:there is no token' }) } }else{ //If going directly down for login or registration interface next() } } module.exports=checkToken
Login.jsInterface Writing in
const express = require('express'); let router = express.Router(); //I use sequelize here to manipulate databases let sequelize = require('sequelize') let models = require('../../db/models') let jwt = require('jwt-simple'); //Set token expiration time const tokenExpiresTime = 1000 * 60 * 60 * 24 * 7 //secret key const jstSecret = 'mengyuhang' router.post('/login', async (req, res, next) => { let { username, password} = req.body; try { //Find the corresponding account password in the user table in the database let personalInformation = await models.User.findOne({ where: { username, password } }) //If Account Exists if (personalInformation) { //Generate token //Objects that need to be encrypted let payload = { username: personalInformation.username, expires: Date.now() + tokenExpiresTime } //Encryption method provided by jwt-simple package, key defined by jstSecret itself let token = jwt.encode(payload, jstSecret) res.json({ message: 'Landing Success', token }) } else { //If the account does not exist res.json({ code: '-1', message: 'User does not exist, please verify that the information is correct' }) } } catch (e) { res.json({ message: 'error' }) } }) //Register interface router.post('/create', async (req, res, next) => { let { username, password } = req.body; try{ //Find User Name in Database let user = await models.User.findOne({ where: { username } }) //If the user name exists if (user) { res.json({ code: '-1', message: 'User name already exists' }) } else { //If the username does not exist, you can register successfully await models.User.create({ username, password }) res.json({ code: '0', message: 'login was successful' }) } }catch(e){ next() } }) module.exports = router
Front End Landing
Click on the token to get back in the background when you log in and plug it directly inDocument.cookieMedium