Home > Web Front-end > JS Tutorial > Complete login verification by using node.js+captchapng+jsonwebtoken

Complete login verification by using node.js+captchapng+jsonwebtoken

巴扎黑
Release: 2017-08-18 10:34:30
Original
2269 people have browsed it

This article mainly introduces the example of node.js+captchapng+jsonwebtoken to implement login verification. It has certain reference value. Those who are interested can learn about it.

When it comes to login verification, everyone can definitely think of it. The verification code is 12306. 12306 has taken great pains to prevent ticket fraud, and the verification code has become increasingly difficult to identify, and eventually even humans may not be able to identify it.

Today, the editor will tell you how to implement image verification code in node and use token to verify login. After studying this article, you will learn:

1. Use captchapng to generate image verification code

2. Use jsonwebtoken to implement login verification

一, Image verification code generation (all codes at the end)

First, let’s go over the process. The first step is for the server to randomly generate a set of four digits.

The second step is to draw these four digits on canvas to generate a picture.

The third step is to save these four digits for comparison when the user returns the data.

So where to save it? Obviously, in order to distinguish users, it is safest to save them in session.

The first step is to have a login page. Here we still use react,

login.tsx


import * as React from 'react'
import * as ReactDom from 'react-dom'
import {Link, browserHistory} from 'react-router';
import * as axios from 'axios';
export default class Login extends React.Component<any,any>{
  constructor(props){
    super(props)
    this.state = {
      userName : &#39;&#39;,
      password : &#39;&#39;,
      yzNoId  : &#39;&#39;,
      hash : Math.random()
    }
  }
  handleUserName(e) : any {
    this.setState({
      userName : e.target.value
    })
  }
  handlePassword(e) : any {
    this.setState({
      password : e.target.value
    })
  }
  handleYzId(e) : any {
    this.setState({
      yzNoId : e.target.value
    })
  }
  render(){
    const { userName, password, yzNoId } = this.state;
    return(
      <p>
        <p className="nav-wrap">
          <ul className="nav">
            <li><Link to="/home">首页</Link></li>
            <li><Link to="/imgLoad">上传</Link></li>
            <li><Link to="/login">登陆</Link></li>
          </ul>
        </p>
        <p className="content">
          <p className="login-warp">
            <p>
              <input type="text" className="username" value={userName} onChange={this.handleUserName.bind(this)} placeholder="用户名"/>
            </p>
            <p>
              <input type="text" className="password" value={password} onChange={this.handlePassword.bind(this)} placeholder="密码"/>  
            </p>  
            <p>
              <input type="text" className="yz" value={yzNoId} onChange={this.handleYzId.bind(this)} placeholder="验证码"/>
              <img src={"http://localhost:3000/captcha"} className="yz-img" />  
            </p>
            <p>
              <input type="button" className="submit" value="登陆" onClick={this.sbumit.bind(this,{userName:userName,password:password,captcha:yzNoId})} /> 
            </p>  
          </p>
        </p>
      </p>
    )
  }
}
Copy after login

The page looks like this


We need to give a verification picture through the server.

router/index.js Add the following code


var Login = require(&#39;./controller/login&#39;);
var login = new Login;
router.get(&#39;/captcha&#39;, login.captcha);
router.post(&#39;/login&#39;,login.loginer);
login是定义在控制器的一个类的实例,captcha,loginer是它的方法。分别是返回验证图片、登录验证。
controller/login.js

var rf = require(&#39;fs&#39;);
var captchapng = require(&#39;captchapng&#39;);
class Login {
  constructor(){}
  captcha(req, res, next) {
    var str = parseInt(Math.random()*9000+1000);  //随机生成数字
    req.session.captcha = str;  // 存入session
    var p = new captchapng(80, 30, str); //生成图片
    p.color(0, 0, 0, 0);
    p.color(80, 80, 80, 255);
    var img = p.getBase64();
    var imgbase64 = new Buffer(img, &#39;base64&#39;);
    res.writeHead(200, {
      &#39;Content-Type&#39;: &#39;image/png&#39;
    });
    res.end(imgbase64);
  }
  loginer(req, res, next) {
    let captcha = req.body.captcha;
    let userName = req.body.userName;
    let password = req.body.password;
    if (captcha != req.session.captcha) {
      res.status(400).send({
        message: &#39;验证码错误&#39;
      });
    }else if(userName == "chenxuehui" && password == "123321"){
      res.json({"code":100,"verson":true,"msg":"登陆成功","token":token});
    }else{
      res.json({"code":0,"verson":false,"msg":"密码错误"});
    }
  }
}
module.exports = Login
Copy after login

The captcha method is to generate a picture containing four digits and then save the picture to the session.

Reference this method in router/index.js


router.get(&#39;/captcha&#39;, login.captcha);
Copy after login

That is to say, when we access localhost:3000/captcha, it will return picture.

With this connection, we can get the image through the src attribute of the image, but when the image is clicked, it needs to be refreshed, so we need to add a Click refresh event. Insert the following code into login.tsx


setHash() {
    this.setState({
      hash : Math.random()
    })
}
Copy after login

The img tag also becomes

Copy code The code is as follows :




All codes of login.tsx at this time:


import * as React from &#39;react&#39;
import * as ReactDom from &#39;react-dom&#39;
import {Link, browserHistory} from &#39;react-router&#39;;
import * as axios from &#39;axios&#39;;
export default class Login extends React.Component<any,any>{
  constructor(props){
    super(props)
    this.state = {
      userName : &#39;&#39;,
      password : &#39;&#39;,
      yzNoId  : &#39;&#39;,
      hash : Math.random()
    }
  }
  public async sbumit(params : any) : Promise<any>{
    let res = await axios.post(&#39;http://localhost:3000/login&#39;,params);
  }
  handleUserName(e) : any {
    this.setState({
      userName : e.target.value
    })
  }
  handlePassword(e) : any {
    this.setState({
      password : e.target.value
    })
  }
  handleYzId(e) : any {
    this.setState({
      yzNoId : e.target.value
    })
  }
  setHash() {
    this.setState({
      hash : Math.random()
    })
  }
  render(){
    const { userName, password, yzNoId } = this.state;
    return(
      <p>
        <p className="nav-wrap">
          <ul className="nav">
            <li><Link to="/home">首页</Link></li>
            <li><Link to="/imgLoad">上传</Link></li>
            <li><Link to="/login">登陆</Link></li>
          </ul>
        </p>
        <p className="content">
          <p className="login-warp">
            <p>
              <input type="text" className="username" value={userName} onChange={this.handleUserName.bind(this)} placeholder="用户名"/>
            </p>
            <p>
              <input type="text" className="password" value={password} onChange={this.handlePassword.bind(this)} placeholder="密码"/>  
            </p>  
            <p>
              <input type="text" className="yz" value={yzNoId} onChange={this.handleYzId.bind(this)} placeholder="验证码"/>
              <img src={"http://localhost:3000/captcha?aaa="+this.state.hash} className="yz-img" onClick={this.setHash.bind(this)} />  
            </p>
            <p>
              <input type="button" className="submit" value="登陆" onClick={this.sbumit.bind(this,{userName:userName,password:password,captcha:yzNoId})} /> 
            </p>  
          </p>
        </p>
      </p>
    )
  }
}
Copy after login

In this way, as long as you click img, a hash will be randomly generated, and then the new image will be called.

Then we proceed with login verification.

The loginer method is used for login verification.

Get the user's username information, password and verification code, compare them, and finally return data on whether the login is successful.

When the user logs in successfully, he does not need to log in again next time. In the past, you can choose session or cookie. Here we use token. Because we have now implemented separate development of front-end and back-end, we are more inclined to build a single page and use Ajax to build applications. Token is the most suitable for this development model.

Token login verification

Token is an encrypted string. After successful login, it is returned to the user for storage. Then the user will bring this token when requesting the interface. . So we need to encrypt the token.

Json Web Token is specifically designed to solve this problem. The principle will not be explained in detail. In fact, it is to obtain a string in a certain way and then unravel it in a certain way.

The first step we need to do is

When the user logs in successfully, create a token and return it to the user.

Step 2: After the user gets the token, he should save the token locally.

The third step: We need to write an intermediate layer. Every time the user requests, we verify whether the token carried by the user is correct. Data is returned correctly, warning is returned incorrectly.
Every time the user requests data, he or she must bring the token in the header.

The first step: Still controller/login.js


var rf = require(&#39;fs&#39;);
var jwt = require(&#39;jsonwebtoken&#39;);
var captchapng = require(&#39;captchapng&#39;);
var Tokens = require(&#39;../middleware/token&#39;)
var t = new Tokens;
class Login {
  constructor(){}
  captcha(req, res, next) {
    var str = parseInt(Math.random()*9000+1000);  //随机生成数字
    req.session.captcha = str;  // 存入session
    var p = new captchapng(80, 30, str); //生成图片
    p.color(0, 0, 0, 0);
    p.color(80, 80, 80, 255);
    var img = p.getBase64();
    var imgbase64 = new Buffer(img, &#39;base64&#39;);
    res.writeHead(200, {
      &#39;Content-Type&#39;: &#39;image/png&#39;
    });
    res.end(imgbase64);
  }
  loginer(req, res, next) {
    let captcha = req.body.captcha;
    let userName = req.body.userName;
    let password = req.body.password;
    if (captcha != req.session.captcha) {
      res.status(400).send({
        message: &#39;验证码错误&#39;
      });
    }else if(userName == "chenxuehui" && password == "123321"){
      // 设置token
      var datas = {userName:"chenxuehui"}
        //调用../middleware/token 下方法设置
      var token = t.setToken(&#39;cxh&#39;,300,datas)
      res.json({"code":100,"verson":true,"msg":"登陆成功","token":token});
    }else{
      res.json({"code":0,"verson":false,"msg":"密码错误"});
    }
  }
}

module.exports = Login
Copy after login

This time we add the setting token in the login method and return it to the user . The setToken method is a method for setting token.

Step 2: Save after the user gets it.

In login.tsx it becomes as follows


import * as React from &#39;react&#39;
import * as ReactDom from &#39;react-dom&#39;
import {Link, browserHistory} from &#39;react-router&#39;;
import * as axios from &#39;axios&#39;;
export default class Login extends React.Component<any,any>{
  constructor(props){
    super(props)
    this.state = {
      userName : &#39;&#39;,
      password : &#39;&#39;,
      yzNoId  : &#39;&#39;,
      hash : Math.random()
    }
  }
  public async sbumit(params : any) : Promise<any>{
    let res = await axios.post(&#39;http://localhost:3000/login&#39;,params);
    if(res.data.verson){
      sessionStorage.setItem(&#39;token&#39;,res.data.token);
      browserHistory.push("/home")
    }
  }
  handleUserName(e) : any {
    this.setState({
      userName : e.target.value
    })
  }
  handlePassword(e) : any {
    this.setState({
      password : e.target.value
    })
  }
  handleYzId(e) : any {
    this.setState({
      yzNoId : e.target.value
    })
  }
  setHash() {
    this.setState({
      hash : Math.random()
    })
  }
  render(){
    const { userName, password, yzNoId } = this.state;
    return(
      <p>
        <p className="nav-wrap">
          <ul className="nav">
            <li><Link to="/home">首页</Link></li>
            <li><Link to="/imgLoad">上传</Link></li>
            <li><Link to="/login">登陆</Link></li>
          </ul>
        </p>
        <p className="content">
          <p className="login-warp">
            <p>
              <input type="text" className="username" value={userName} onChange={this.handleUserName.bind(this)} placeholder="用户名"/>
            </p>
            <p>
              <input type="text" className="password" value={password} onChange={this.handlePassword.bind(this)} placeholder="密码"/>  
            </p>  
            <p>
              <input type="text" className="yz" value={yzNoId} onChange={this.handleYzId.bind(this)} placeholder="验证码"/>
              <img src={"http://localhost:3000/captcha?aaa="+this.state.hash} className="yz-img" onClick={this.setHash.bind(this)} />  
            </p>
            <p>
              <input type="button" className="submit" value="登陆" onClick={this.sbumit.bind(this,{userName:userName,password:password,captcha:yzNoId})} /> 
            </p>  
          </p>
        </p>
      </p>
    )
  }
}
Copy after login
Copy after login

In the sbumit method we put the token into sessonstorage.

Step 3: Set the middleware to verify the token every time it requests the interface. If the parsing is successful, it will be added to the request header.

./middleware/token.js


##

var jwt = require(&#39;jsonwebtoken&#39;);
class Tokens {
  constructor(){}
  testToken(req,res,next) {
    var token = req.body.token || req.query.token || req.headers[&#39;x-access-token&#39;];
       
    if(token) {
            //存在token,解析token
      jwt.verify(token, &#39;cxh&#39; , function(err,decoded) {
        if(err) {
                   // 解析失败直接返回失败警告
          return res.json({success:false,msg:&#39;token错误&#39;})
        }else {
                   //解析成功加入请求信息,继续调用后面方法
          req.userInfo = decoded;
          next()
        }
      })
    }else {
      return res.status(403).send({success:false,msg:"没有token"})
    }
  }
  setToken(name,time,data) {
    var jwtSecret = name;
    var token = jwt.sign(data, jwtSecret, {
      expiresIn: time
    })
    return token;
  }
}
module.exports = Tokens
Copy after login

The testToken method is to verify the token, and setToken is to set the token method


If there is no login request, this is like this


在 router/index.js


var express = require('express');
var router = express.Router();
var rf = require('fs');
var Login = require('./controller/login');
var Tokens = require('./middleware/token')
var t = new Tokens;
var login = new Login;
//主页
router.get('/', function(req, res, next) {
  res.render("wap/index")
});
//获取图片验证码
router.get(&#39;/captcha&#39;, login.captcha);
//登录验证
router.post('/login',login.loginer);
//请求数据时 t.testToken 验证token
router.post('/list',t.testToken,function(req, res, next){
  res.json({
    //在请求信息里面拿到数据
    username : req.userInfo.userName,
    success : true,
    result : [
      {
        name:'1111111'
      },
      {
        name :'22222'
      }
    ]
  })
})
module.exports = router;
Copy after login

我们在另一个页面调用list接口试一下


import * as axios from &#39;axios&#39;;
import { transToken } from &#39;../decorator/index&#39;


class Home extends React.Component<any,any>{
  constructor(props){
    super(props)
    this.state = {
      data : &#39;&#39;
    }
  }
  async getList(): Promise<any>{
    let token = sessionStorage.getItem(&#39;token&#39;);
    const config = {
     // 请求头信息
     headers: {&#39;x-access-token&#39;: token}      
    }
    let res = await axios.post(&#39;http://localhost:3000/list&#39;,{},config);
    if(!res.data.success){
      browserHistory.push(&#39;/login&#39;);
      return;
    }
    this.setState({
      data : res.data
    })
  }
  render(){
    const { data } = this.state;
    return(
      <p>
        <p className="nav-wrap">
          <ul className="nav">
            <li><Link to="/home">首页</Link></li>
            <li><Link to="/imgLoad">上传</Link></li>
            <li><Link to="/login">登陆</Link></li>
          </ul>
        </p>
        <p className="content">
          Home
          <span onClick={this.getList.bind(this)}>获取数据</span>
          <p>{
            data ? data.result.map( (val,k) => {
              return <li key = {k}>{val.name}</li>
            }) : null
          }</p>
        </p>
      </p>
      
    )
  }
}
export default Home
Copy after login

当调用getList时,如果此时没有登录res.data.success就会为false,则跳到登录页。

全部代码

node.js

app.js


var express = require(&#39;express&#39;);
var path = require(&#39;path&#39;);
var favicon = require(&#39;serve-favicon&#39;);
var logger = require(&#39;morgan&#39;);
var cookieParser = require(&#39;cookie-parser&#39;);
var bodyParser = require(&#39;body-parser&#39;);
var session = require("express-session");
var ejs = require(&#39;ejs&#39;);

var index = require(&#39;./routes/index&#39;);


var app = express();

// view engine setup
app.set(&#39;views&#39;, path.join(__dirname, &#39;views&#39;));
// app.set(&#39;view engine&#39;, &#39;jade&#39;);
app.engine(&#39;html&#39;, ejs.__express);
app.set(&#39;view engine&#39;, &#39;html&#39;);
app.use(session({
  secret:"dabao",
  resave:false,
  saveUninitialized:true,
  cookie:{}
}));
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, &#39;public&#39;, &#39;favicon.ico&#39;)));
app.use(logger(&#39;dev&#39;));
app.use(bodyParser.json());
app.use(bodyParser({limit: 5000000}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, &#39;&#39;)));

app.use(&#39;/&#39;, index);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
 var err = new Error(&#39;Not Found&#39;);
 err.status = 404;
 next(err);
});

// error handler
app.use(function(err, req, res, next) {
 // set locals, only providing error in development
 res.locals.message = err.message;
 res.locals.error = req.app.get(&#39;env&#39;) === &#39;development&#39; ? err : {};

 // render the error page
 res.status(err.status || 500);
 res.render(&#39;error&#39;);
});

module.exports = app;
Copy after login

index.js


var express = require('express');
var router = express.Router();
var rf = require('fs');
var Login = require('./controller/login');
var Tokens = require('./middleware/token')
var t = new Tokens;
var login = new Login;
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render("wap/index")
});
router.post('/upLoadImg',function(req,res,next){
  let imgData = req.body.imgData;
  console.log(imgData)
  let base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
  let dataBuffer = new Buffer(base64Data, 'base64');
  let timer = Number( new Date() );
  console.log(timer)
  rf.writeFile("views/images/artCover"+timer+".png",dataBuffer, function(err) {
    if(err) {
     res.json({"code":400,"verson":false,"msg":err});
    }else {
     res.json({"code":100,"verson":true,"url":"views/src/common/images/artCover/"+timer+".png"});
    }
  });
})
router.get(&#39;/captcha&#39;, login.captcha);
router.post('/login',login.loginer);
router.post('/list',t.testToken,function(req, res, next){
  // 先解析token 
  console.log(req.userInfo)
  res.json({
    username : req.userInfo.userName,
    success : true,
    result : [
      {
        name:'1111111'
      },
      {
        name :'22222'
      }
    ]
  })
})
module.exports = router;
Copy after login

controller/login.js


var rf = require(&#39;fs&#39;);
var jwt = require(&#39;jsonwebtoken&#39;);
var captchapng = require(&#39;captchapng&#39;);
var Tokens = require(&#39;../middleware/token&#39;)
var t = new Tokens;
class Login {
  constructor(){}
  captcha(req, res, next) {
    var str = parseInt(Math.random()*9000+1000);  //随机生成数字
    req.session.captcha = str;  // 存入session
    var p = new captchapng(80, 30, str); //生成图片
    p.color(0, 0, 0, 0);
    p.color(80, 80, 80, 255);
    var img = p.getBase64();
    var imgbase64 = new Buffer(img, &#39;base64&#39;);
    res.writeHead(200, {
      &#39;Content-Type&#39;: &#39;image/png&#39;
    });
    res.end(imgbase64);
  }
  loginer(req, res, next) {
    let captcha = req.body.captcha;
    let userName = req.body.userName;
    let password = req.body.password;
    if (captcha != req.session.captcha) {
      res.status(400).send({
        message: &#39;验证码错误&#39;
      });
    }else if(userName == "chenxuehui" && password == "123321"){
      // 设置token
      var datas = {userName:"chenxuehui"}
      var token = t.setToken(&#39;cxh&#39;,300,datas)
      res.json({"code":100,"verson":true,"msg":"登陆成功","token":token});
    }else{
      res.json({"code":0,"verson":false,"msg":"密码错误"});
    }
  }
}
module.exports = Login
Copy after login

middleware/token.js


var jwt = require(&#39;jsonwebtoken&#39;);

class Tokens {
  constructor(){}
  testToken(req,res,next) {
    var token = req.body.token || req.query.token || req.headers[&#39;x-access-token&#39;];

    if(token) {
      jwt.verify(token, &#39;cxh&#39; , function(err,decoded) {
        if(err) {
          return res.json({success:false,msg:&#39;token错误&#39;})
        }else {
          req.userInfo = decoded;
          next()
        }
      })
    }else {
      return res.status(403).send({success:false,msg:"没有token"})
    }
  }
  setToken(name,time,data) {
    var jwtSecret = name;
    var token = jwt.sign(data, jwtSecret, {
      expiresIn: time
    })
    return token;
  }
}
module.exports = Tokens
Copy after login

react部分

login.tsx


import * as React from &#39;react&#39;
import * as ReactDom from &#39;react-dom&#39;
import {Link, browserHistory} from &#39;react-router&#39;;
import * as axios from &#39;axios&#39;;
export default class Login extends React.Component<any,any>{
  constructor(props){
    super(props)
    this.state = {
      userName : &#39;&#39;,
      password : &#39;&#39;,
      yzNoId  : &#39;&#39;,
      hash : Math.random()
    }
  }
  public async sbumit(params : any) : Promise<any>{
    let res = await axios.post(&#39;http://localhost:3000/login&#39;,params);
    if(res.data.verson){
      sessionStorage.setItem(&#39;token&#39;,res.data.token);
      browserHistory.push("/home")
    }
  }
  handleUserName(e) : any {
    this.setState({
      userName : e.target.value
    })
  }
  handlePassword(e) : any {
    this.setState({
      password : e.target.value
    })
  }
  handleYzId(e) : any {
    this.setState({
      yzNoId : e.target.value
    })
  }
  setHash() {
    this.setState({
      hash : Math.random()
    })
  }
  render(){
    const { userName, password, yzNoId } = this.state;
    return(
      <p>
        <p className="nav-wrap">
          <ul className="nav">
            <li><Link to="/home">首页</Link></li>
            <li><Link to="/imgLoad">上传</Link></li>
            <li><Link to="/login">登陆</Link></li>
          </ul>
        </p>
        <p className="content">
          <p className="login-warp">
            <p>
              <input type="text" className="username" value={userName} onChange={this.handleUserName.bind(this)} placeholder="用户名"/>
            </p>
            <p>
              <input type="text" className="password" value={password} onChange={this.handlePassword.bind(this)} placeholder="密码"/>  
            </p>  
            <p>
              <input type="text" className="yz" value={yzNoId} onChange={this.handleYzId.bind(this)} placeholder="验证码"/>
              <img src={"http://localhost:3000/captcha?aaa="+this.state.hash} className="yz-img" onClick={this.setHash.bind(this)} />  
            </p>
            <p>
              <input type="button" className="submit" value="登陆" onClick={this.sbumit.bind(this,{userName:userName,password:password,captcha:yzNoId})} /> 
            </p>  
          </p>
        </p>
      </p>
    )
  }
}
Copy after login
Copy after login

home.js 获取列表信息


import * as React from &#39;react&#39;
import * as ReactDom from &#39;react-dom&#39;
import {Link, browserHistory} from &#39;react-router&#39;;
import * as axios from &#39;axios&#39;;
class Home extends React.Component<any,any>{
  constructor(props){
    super(props)
    this.state = {
      data : &#39;&#39;
    }
  }
  async getList(): Promise<any>{
    let token = sessionStorage.getItem(&#39;token&#39;);
    const config = {
     // 请求头信息
     headers: {&#39;x-access-token&#39;: token}      
    }
    let res = await axios.post(&#39;http://localhost:3000/list&#39;,{},config);
    if(!res.data.success){
      browserHistory.push(&#39;/login&#39;);
      return;
    }
    this.setState({
      data : res.data
    })
  }
  render(){
    const { data } = this.state;
    return(
      <p>
        <p className="nav-wrap">
          <ul className="nav">
            <li><Link to="/home">首页</Link></li>
            <li><Link to="/imgLoad">上传</Link></li>
            <li><Link to="/login">登陆</Link></li>
          </ul>
        </p>
        <p className="content">
          Home
          <span onClick={this.getList.bind(this)}>获取数据</span>
          <p>{
            data ? data.result.map( (val,k) => {
              return <li key = {k}>{val.name}</li>
            }) : null
          }</p>
        </p>
      </p>
      
    )
  }
}
export default Home
Copy after login

The above is the detailed content of Complete login verification by using node.js+captchapng+jsonwebtoken. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template