Node uses Jsonwebtoken to generate tokens, complete user login, login detection

Source: Internet
Author: User
Tags call back

Recently in the background login with node to detect the login function. The local use of the session can be successful, but after the server to find the session is invalid, each request session will change, for a long reason. Originally, the project is a front-end separation, the front end of the call back-end API interface, so used cors = require(‘cors‘) to solve the cross-domain problem, and cross-domain for the cookie, is two different sites, so the session will continue to change.

Cause

Recently in the background login with node to detect the login function. The local use of the session can be successful, but after the server to find the session is invalid, each request session will change, for a long reason. Originally, the project is a front-end separation, the front end of the call back-end API interface, so used cors = require(‘cors‘) to solve the cross-domain problem, and cross-domain for the cookie, is two different sites, so the session will continue to change.

Workaround
    • Set an nginx or something else to do the forwarding, avoid cross-domain. You can get an nginx, set 8080, then the app points to 3000,api Point 1994.
    • Do not use the session and use token to make API requests

      Use token
    • Import Module
      npm install jsonwebtoken
    • Generate tokens in the background and deposit them in the database
//api.js//登录router.post(‘/api/admin/signIn‘,(req, res)=>{    db.User.find({ name: req.body.name,password: req.body.password},(err, docs)=>{        if (err) {            res.send(err);            return        }        if(docs.length>0){            let content ={name:req.body.name}; // 要生成token的主题信息            let secretOrPrivateKey="suiyi" // 这是加密的key(密钥)             let token = jwt.sign(content, secretOrPrivateKey, {                    expiresIn: 60*60*1  // 1小时过期                });            docs[0].token = token    //token写入数据库            db.User(docs[0]).save(function (err) {                if (err) {                res.status(500).send()                return                }                res.send({‘status‘:1,‘msg‘:‘登陆成功‘,‘token‘:token,‘user_name‘:req.body.name})     //反给前台            })        }else{            res.send({‘status‘:0,‘msg‘:‘登录失败‘});        }    })})
    • The front desk will be able to get tokens and deposit localstorage.
//signin.vue this.$axios.post(webUrl+‘api/admin/signIn‘, {‘name‘: this.name, ‘password‘: this.password})        .then((response) => {          if(response.data.status==1){              localStorage.setItem(‘token‘, response.data.token);              localStorage.setItem(‘user_name‘, response.data.user_name);          }else{            alert(response.data.msg)          }        })        .catch((reject) => {          console.log(reject)        })
    • Background check token
 //Detect Token//api.jsrouter.post ('/api/admin/checkuser ', (req, res) =>{db.            User.find ({Name:req.body.user_name,token:req.body.token}, (Err, Docs) =>{if (err) {res.send (err);            return} if (docs.length>0) {Let token = Req.body.token;//Get token from body Let secretorprivatekey= "Suiyi";  This is the encrypted key (key) Jwt.verify (token, secretorprivatekey, function (err, decode) {if (err) {//                            Time Lapse/Forged token res.send ({' status ': 0});                } else {res.send ({' Status ': 1});                    }})}else{Res.send ({' status ': 0}); }    })})
    • The foreground every time calls checkuser to detect the login can, also can each interface to pass token, background authentication;

      At last

      Hello everyone, this is "taoland", this blog is mainly used to record a rookie program ape Growth Road. This is my first time to do blog, hope and we have a lot of communication, grow together! The article will be updated synchronously at the following address ...
      Personal blog: www.yangyuetao.cn
      Small program: Taoland

Node uses Jsonwebtoken to generate tokens, complete user login, login detection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.