nodejs+express+mysql+jwt接口安全验证
-
一段token aaa.bbb.ccc分别有头部,载荷和签名组成。
-
用户登录成功后服务端返回token(jwt.sign()方法)。
-
客户端请求其他接口,不管是post,get或者在headers里面判断是否有token(jwt.verify())。
第一部分:服务器设置
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var secretkey = 'secretkey'; //加密字段
//获取数据库连接对象
var connection = require('./mysql/db');
//处理post字段请求
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//建立拦截器处理跨域请求
app.all(function(req, res, next) {
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.use(function(req,res,next){
if(req.url !='/user/login' && req.url !='/user/register'){
//token可能存在post请求和get请求
let token = req.body.token || req.query.token || req.headers.token;
jwt.verify(token,secretkey,function(err,decode){
if(err){
res.json({
message: 'token过期,请重新登录',
resultCode: '403'
})
}else{
next();
}
})
}else{
next();
}
})
第二部分:mysql的连接方法
var mysql = require('mysql');
var dbMsg = {
host : 'localhost',
user : 'root',
password : '123456',
database : 'app_pro'
}
var connection = mysql.createConnection(dbMsg);
connection.connect();
module.exports=connection;
第三部分:POST请求接口
app.get('/',function(req,res){
res.send('请求home成功');
})
//用户登录
app.post('/user/login', (req,res) => {
var name = req.body.username;
var passwd = req.body.password;
if(!name||!passwd){
res.status='404';
res.send({
message: '用户名或密码错误',
resultCode: 1
})
return;
}
var userStr = `select * from user where username="${name}" and password="${passwd}"`;
connection.query(userStr,function(err,result){
if(err){
throw err;
}else{
var token = jwt.sign({username:name},secretkey,{expiresIn: 60*8});
res.json({
message: '请求成功',
token: token
})
}
})
})
//获取用户列表
app.post('/user/getList',(req,res)=>{
var listStr = `select * from user`;
connection.query(listStr,function (err,result) {
if(err) throw err;
res.json({
message: '请求成功',
resultCode: 1,
info: result
})
})
})
//用户注册
app.post('/user/register',(req,res)=>{
var name = req.body.username;
var passwd = req.body.password;
if(!name || !passwd){
res.send({
message: '用户名或密码错误',
resultCode: 1
})
return;
}
var json = {};
var userStr = `select * from user where username="${name}" and password="${passwd}"`;
connection.query(userStr,function(err,result){
if(err) throw err;
if(result.length>0){
json.message= '请求失败用户已经存在';
json.resultCode = 1;
}else{
json.message = '请求成功';
json.resultCode = 0;
var insertStr = `insert into user (username, password) values ("${name}", "${passwd}")`;
console.log(insertStr)
connection.query(insertStr,function(err,res){
if(err) throw err;
})
}
res.send(JSON.stringify(json))
})
})
const port = 3001;
app.listen(port, () => {
console.log('Express server listening on port ' + port);
});