How to use JWT to do a simple login operation

The authentication of registration and login is very important for a website, not only can protect your personal information, but also facilitate subsequent operations.

Insert picture description here

01 Preface


Today I will talk to you about our login and registration process. We know that there are many situations for logging in. For example, you can log in using your account password, you can log in using a scan code, and you can also log in using a third-party account. In fact, the principle is similar, just verify that your account is reasonable Whether the login information is valid.

But this article is to tell you the mystery of using a simple login process. Generally speaking, after we log in successfully, the server will return a token. Don't think that this is an irrational string. At first, I thought that. In fact, the information of our account is saved in the token, only after the encryption operation, we can get the information after decryption.

02 Preparation

You may not know what jwt is at the beginning. Simply put, this is an encrypted version of user information. You can encrypt your account or decrypt it. Understand this, we can use it to do a little thing, we are using a simple architecture such as vue + jwt + node + mysql, we can simply write the login operation on the vue page, use node to write a login The interface is enough.

In order to take care of most of the little friends, I will elaborate on the process a little more. At first we must install the two plugins mysql and jsonwebtoken. For more convenience, I also installed express, the purpose is to facilitate the operation when using routing.

Access the database
api.js文件
const mysql = require('mysql');
const sqlMap = require('./sqlMap');

//创建链接对象
const pool = mysql.createPool({
    host: 'xx.xx.xxx.xxx',
    user: 'root',
    port: 3306,
    password: 'xxxxxx',
    database: 'xxxxxx',
    multipleStatements: true    // 多语句查询
})
//写一个登录接口
module.exports = {
    login(req, res, next) {
      var username = req.query.username;
      var password = req.query.password;
      pool.getConnection((err, connection) => {
        var sql = sqlMap.login; //这里有一个sqlMap对象,用来写sql语句
        connection.query(sql,[username,password] ,(err, result) => {
            res.json(result);
            connection.release();
        })
      })
    },
    //接下来可以写更多的接口
}

There is also a route to write an interface, that is, you will connect to the database and query the database when you request this

router.js文件
const express = require('express');
const router = express.Router();
const api = require('./api'); //这里引入上面的文件

router.get('/login', (req, res, next) => {
  api.login(req, res, next);
});

//最后记得导出
module.exports = router;

Above I still use an object of a sqlMap, we write one separately, just for future convenience, and the coupling is lower and easy to expand.

var sqlMap = {
    login: 'select * from teacher where teacherName = ? and `password` = ?;',
}
//最后也记得要导出
module.exports = sqlMap;

In this way, we can use this object when we introduce it in the file, which can also write a lot of SQL statement queries.

Having said so much, we must start the service, then we simply start a service that can call all the interfaces we write, this is a main file, we named it index.js file

const routerApi = require('./router');
const path = require('path');
const bodyParser = require('body-parser'); // post 数据解析
const express = require('express');
const app = express();

app.use(bodyParser.json());
// 后端api路由
app.use('/api', routerApi);

// 监听端口
app.listen(3000);
console.log('success listen at port:3000......');

In this way, we will listen to port 3000 after node index.js. At this point, our service is started, and the database part will be opened.

Front page

As an explanation here, we don't need to write some beautiful pages. There are two input boxes. Vue has a two-way data binding function, so that we can easily obtain the contents of the input box and use the account password to pass it. Do sql query to the backend. How about it, is it particularly simple?

form: {
    username: "",
    password: "",
}

For example, under data, we store the data of the input box in this way. If you can do some operations such as verification, use the elementui component library, you will find a new world. It won't start here.

Then write a login method in the methods to interact with the back-end data. Here is also a very simple operation.

//在script标签下面引入:
//const jwt = require("jsonwebtoken");
//const secret = "your string"; //自己的密钥

login() {
      this.$axios
        .get("/api/login", {//请求的接口
          params: { username: form.username, password: form.password }//传递参数
        })
        .then(res => {
          if (res.data.length > 0) {//假如返回有数据就使用token加密一下
            const token = jwt.sign(
              {
                name: res.data[0]//这里就是数据库返回的用户相关的信息
              },
              secret,//这是一个密钥,可以使用你喜欢的字符串
              {
                expiresIn: 86400 //秒,到期时间,一天
              }
            );
            this.$store.commit("SET_TOKEN", token);//写入token
            this.$router.replace("home");//跳转到主页
          } else {
            this.$message.error("登录失败");
          }
        });
    }

You can see that I wrote the token in vuex and put it in sessionStorage, which is to manage it in a global state. For example, it is very practical to display your name on the home page and do permission control in the future. You can use this. $ Store.state.user to obtain user information in the future.

Insert picture description here

If you need to use user data where you can directly parse the token, here I have written an extra field to store user name and identity information for convenience. Here to parse the data, we just use the function method that comes with jwt. The token is the token you stored in the global, and the secret is the one you used for encryption, so that it can be parsed out smoothly.

//这里也要引入
//const jwt = require("jsonwebtoken");
//const secret = "your string"; //自己的密钥

jwt.verify(token, secret, function(err, decoded) {
        if (!err) {
          User.id = decoded.name.teacherId;
          User.username = decoded.name.teacherName;
        }
      });

04 Summary


In this article, I only talked about how to use jwt to perform a simple login verification operation, suitable for some white students to try it out, after all, this is also one of the more commonly used npm packages. In fact, many tutorials on the Internet say how to use jwt for verification. Maybe you think that such a simple knowledge point needs to be so complicated? In fact, you don't understand the pain in Xiaobai's heart. At the beginning, I didn't know how to use it. I also saw a lot of details about the realization, and finally realized it.

In fact, my article should be aimed at some students with weak foundations. I understand that they want to make a simple function but do not know how to write the pain. It is the same as the original one. I do n’t think it ’s readable if I do n’t understand other people ’s articles, although I do n’t know if I can understand everyone.

Because of the recent improvement of graduation-related matters, there is not much time to read and study, and the quality may be reduced. In the future, we will share more dry goods with everyone.

Insert picture description here

Published 57 original articles · won praise 6 · views 6419

Guess you like

Origin blog.csdn.net/weixin_42724176/article/details/105199528