Redis use

Install radis

Install radis in Linux

sudo apt-get install redis-server

Check the Redis server system process

ps -aux|grep redis

Check the status of the Redis port

netstat -nlt|grep 6379

/ / start
/etc/init.d/redis-server start
/ / stop
/etc/init.d/redis-server stop
/ / restart
/etc/init.d/redis-server restart
Copy the code

Install Redis using Docker

// Download the version
docker pull redis  // The latest version of Redis is pulled by default
 
docker images // Check whether the image is successfully installed

docker run -itd --name redis-test -p 6379:6379 redis // Start redis container port 6379

docker start redis-test / / start redis

docker stop redis-test / / close the redis

docker restart redis-test / / restart redis
Copy the code

In the eggjs environment, redis and jsonwebtoken are used to implement token authentication

npm install jsonwebtoken
Copy the code

Middleware middleware

​ jwt.js

'use strict'
const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken') / / introduce jsonwebtoken

module.exports = (options, app) = > {
  return async function userInterceptor(ctx, next) {
    let authToken = ctx.header.authorization // Get the authorization in the header
    if (authToken) {
      authToken = authToken.substring(7)
      const res = verifyToken(authToken) // Decrypt the obtained Token
      if (res.corpid && res.userid) {
        // If you need to restrict single-end login or disable a token during use, or change the permission of the token. That is, once a JWT is issued, it remains valid until it expires
        // Save using redis here
        const redis_token = await app.redis.get('loginToken').get(res.corpid + res.userid) // Get the saved token
        if (authToken === redis_token) {
          ctx.locals.corpid = res.corpid
          ctx.locals.userid = res.userid
          await next()
        } else {
          ctx.body = { code: 50012.msg: 'Your account has been logged in elsewhere'}}}else {
        ctx.body = { code: 50012.msg: 'Login status expired'}}}else {
      ctx.body = { code: 50008.msg: 'Please log in and try again.'}}}}// Decrypt, verify
function verifyToken(token) {
  const cert = fs.readFileSync(path.join(__dirname, '.. /public/rsa_public_key.pem')) // Public key
  let res = ' '
  try {
    const result = jwt.verify(token, cert, { algorithms: [ 'RS256' ] }) || {}
    const { exp } = result,
      current = Math.floor(Date.now() / 1000)
    if (current <= exp) res = result.data || {}
  } catch (e) {
    console.log(e)
  }
  return res
}
Copy the code

Using middleware

// Method 1: Use middleware in your application
config.middleware = [ 'jwt' ]

config.jwt = {
    enable: true.ignore: [ '/api/v1/test/'.'/public/'].// Which requests do not require authentication
}

// Method 2: Use middleware on the router
module.exports = app= > {
  const jwt = app.middleware.jwt();
  app.router.get('/api/v1/test/', jwt, app.controller.test.test);
};
Copy the code

To generate the token

Write in helper, easy to call

// Method 1: Use middleware in your application
config.middleware = [ 'jwt' ]

config.jwt = {
    enable: true.ignore: [ '/api/v1/test/'.'/public/'].// Which requests do not require authentication
}
config.redis = {
    client: {
      host: '127.0.0.1'.port: '6379'.password: ' '.db: 0,}};// Method 2: Use middleware on the router
module.exports = app= > {
  const jwt = app.middleware.jwt();
  app.router.get('/api/v1/test/', jwt, app.controller.test.test);
};
Copy the code

Invoke the token generation mode

// Method 1: Use middleware in your application
config.middleware = [ 'jwt' ]

config.jwt = {
    enable: true.ignore: [ '/api/v1/test/'.'/public/'].// Which requests do not require authentication
}

// Method 2: Use middleware on the router
module.exports = app= > {
  const jwt = app.middleware.jwt();
  app.router.get('/api/v1/test/', jwt, app.controller.test.test);
};
Copy the code

Generate private and public keys using OpenSSL

Generate a public key: openssl genrsa -out rsa_private_key.pem1024Generate the private key openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
Copy the code