前端架構之node jwt認證

前言:

此次使用node express jwt實現一個小小的認證,數據庫之類的慢慢在添加上去,先跑通整個流程,基本上是可使用到項目裏面的了。此次就不用gulp編譯了,添加了log4.js一個錯誤日誌,還稍微作了一下壓測。就不詳細展開了,有興趣的能夠下載來看:github地址前端

和前端對應:前端架構之vue+axios 前端實現登陸攔截(路由攔截、http攔截)vue

大體流程:每次請求進來,都必須通過retoken.js,驗證是否帶token頭部,如有則next(),沒有則返回錯誤信息。固然也能夠設置不須要認證的接口,判斷後直接next()。node

1.目錄結構:

開始吧,config:配置文件,controllers:控制路由,logs:錯誤日誌,middleware:一些中間件,model:數據交互,router:路由分發ios


2.編寫app.js

app.js 

import express from 'express';
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import session from 'express-session'
import log4js from 'log4js';
import CONFIG from './config';
import api from './router/api'
// import errorHandler from './middleware/logger';

let app = express();

//中間件設置
app.use(cookieParser('sessionCaptcha'))
app.use(session({
    secret: 'sessionCaptcha', // 與cookieParser中的一致
    resave: true,
    saveUninitialized: true,
    name: 'USER_INFO_ID'
}))
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
// 路由
app.use('/', api)

//錯誤處理
log4js.configure({
    appenders: { cheese: { type: 'file', filename: './logs/chen.log' } },
    categories: { default: { appenders: ['cheese'], level: 'error' } }
});

const logger = log4js.getLogger('cheese');

//只會記錄error級別以上的錯誤
logger.error('Cheese is too ripe!');
logger.fatal('Cheese was breeding ground for listeria.');

//容錯處理機制
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);

function logErrors(err, req, res, next) {
    console.error('記錄日誌', err.stack);
    next(err);
}

function clientErrorHandler(err, req, res, next) {
    if (req.xhr) {
        res.status(500).send({ error: 'Something blew up!' });
    } else {
        next(err);
    }
}

function errorHandler(err, req, res, next) {
    res.status(500);
    res.send('你錯了');
}
app.use(function (req, res, next) {
    if (res.status(404)) {
        res.send('Sorry cant find that!404')
    }else{
        next()
    }

})
var server = app.listen(CONFIG.get('port'), CONFIG.get('url'), () => {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});複製代碼

config>index.js 配置信息

const CONFIG = new Map()
//設置端口
CONFIG.set('port', 3000)
//設置url
CONFIG.set('url', '127.0.0.1')
export default CONFIG複製代碼

3.編寫router api

api.js router分發

import {Router} from 'express'
import jwt from 'jsonwebtoken'
import retoken from './retoken'
import indexController from '../controllers'

const router = Router()
//設置跨域
router.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Request-Headers:content-type,xfilecategory,xfilename,xfilesize");
  res.header("X-Powered-By",' 3.2.1')
  if(req.method=="OPTIONS") res.send(200);/*讓options請求快速返回*/
  else  next();
});
//添加token認證
router.use(retoken)

//實現登陸
router.use('/login', (req, res, next) => {
  console.log(111)
 //設置我的信息
  const userToken = {
    name: '1',
    loginAt: +new Date
  }
  //簽發token 指定過時時間2h
  const token = jwt.sign(userToken, 'chen', { expiresIn: '2h' });
  res.json({
    code: 200,
    data: token
  })
})

router.use('/index', (req, res, next) => {
    res.json({
        code: 200,
        data: 'henhao'
    })
})
//路由
router.use('/user',indexController)
export default router複製代碼

retoken.js token認證

import jwt from "jsonwebtoken";
import api from "./unLogin";
let unLogin = api.unLogin
export default function (req, res, next) {
  let method = req.method.toLowerCase()
  let path = req.path
    //接口不須要登錄:直接next
    //判斷method類型,而且是否包含path
    if(unLogin[method] && unLogin[method].indexOf(path) !== -1){
      console.log('到這裏不用驗證喔')
      return  next()
    }
    const token = req.headers.authorization
    // console.log(req.headers)
    //沒有token值,返回401
    if (!token) {
        return res.json({
            code: 401,
            msg: 'you need login:there is no token'
        })
    }
   //認證token
    jwt.verify(token, 'chen', (err, decoded) => {
        console.log('這邊須要驗證才行喔')
        if(err){
            return res.json({
                code: 401,
                msg: err.msg
            })
        } else {
            // 將攜帶的信息賦給req.user
            req.user = decoded
            return next()
        }
    })
}複製代碼

unLogin.js 不須要登陸認證的接口

export default {
  unLogin: {
    get: [
      '/index',
      '/user'
    ],
    post: [
      '/login'
    ],
    put: [],
    delete: [],
  }
}複製代碼

4.編寫controllers models

controllers>index.js

import express from 'express'
import indexMode from '../model'
let router = express.Router()
router
  .get('/', (req, res, next) => {
    indexMode.getData(function (data) {
      res.json(data)
    })
  })
  .put('/', (req, res, next) => {
    res.json({
      code:200,
      data: 'put'
    })
  })

export default router複製代碼

models>index.js

let indexModel={
  //這裏操做數據庫
  getData:function (cb) {
    var data = {
      code:200,
      data:{
        username:111,
        password:222
      }
    }
    cb(data)
  }
}
module.exports=indexModel複製代碼

5.須要安裝的包

使用nedemon 啓動nodegit

"dependencies": {
  "body-parser": "^1.18.3",
  "cookie-parser": "^1.4.3",
  "express": "^4.16.3",
  "express-session": "^1.15.6",
  "jsonwebtoken": "^8.3.0",
  "log4js": "^3.0.2"
},
"devDependencies": {
  "babel-cli": "^6.26.0",
  "babel-preset-es2015": "^6.24.1",
  "babel-preset-stage-2": "^6.24.1",
  "nodemon": "^1.18.3"
}複製代碼
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "dev": "nodemon app.js --exec babel-node --presets es2015,stage-2"
},複製代碼

使用npm run dev 啓動後

訪問 http://127.0.0.1:3000/indexgithub


訪問 http://127.0.0.1:3000/user
web


這樣便實現了node server的jwt認證,鏈接數據庫那方面,等下次更新,下一步須要在前端那邊作相關的配置了。數據庫

6.使用wrk壓測一下

安裝

wrk支持大多數類UNIX系統,不支持windows。須要操做系統支持LuaJIT和OpenSSL,不過不用擔憂,大多數類Unix系統都支持。安裝wrk很是簡單,只要從github上下載wrk源碼,在項目路徑下執行make命令便可。express

git clone https://github.com/wg/wrk複製代碼

make以後,會在項目路徑下生成可執行文件wrk,隨後就能夠用其進行HTTP壓測了。
npm

壓測

在當前目錄下輸入 ./wrk -t8 -c200 -d30s --latency 'http://127.0.0.1:3000/index'

使用8個線程200個鏈接,對http://127.0.0.1:3000/index進行了30秒的壓測

Running 30s test @ http://127.0.0.1:3000/index
  8 threads and 200 connections
  Thread Stats   Avg      Stdev     Max     +/- Stdev
               (平均值) (標準差) (最大值)(正負一個標準差所佔比例)
    Latency    65.99ms   15.58ms 185.51ms   89.74%
    (延遲)
    Req/Sec    380.14    126.58   505.00     57.24%
 (處理中的請求數)
  Latency Distribution (延遲分佈)
     50%   60.90ms
     75%   62.99ms
     90%   82.57ms
     99%  127.67ms
90428 requests in 30.06s, 93.72MB read(30.06秒內共處理完成了90428個請求,讀取了93.72MB數據)
Socket errors: connect 0, read 145, write 0, timeout 0
Requests/sec:   3008.58  (平均每秒處理完成3008.58個請求)
Transfer/sec:   3.12MB  (平均每秒讀取數據3.12MB)複製代碼

待續......

相關文章
相關標籤/搜索