Basic use of KOA

const Koa = require('koa'); // const router = require('koa-router') const userRouter = require('./router/user') const app = new Koa(); App.use (userrouter.routes ()) // method not allow Used to determine a method is no support for the app. Use (userRouter. AllowedMethods ()) / / not found if all the middleware performed did not return a result, Use ((context, dispatch) => {// Body can try the object string, Buffer, array context.response.body = "hell10"}) app. Use ((CTX, Dispatch) => {if (ctx.request.url === '/login') {if (ctx.request.method === 'GET') {ctx.response.body = 'login succeeded'}}}) App.listen (8000, () => {console.log(' server started successfully ')})Copy the code

Cookies are used

const Koa = require('koa') const Router = require('koa-router') const app = new Koa(); const testRouter = new Router(); Testrouter. get('/test', (CTX, next) => {// set cookie maxAge in milliseconds ctx.cookies. Set ('name', 'lili', {maxAge: Get ('name') ctx.body = value}) testrouter. get('/s', (CTX, Get ('name') ctx.body = value}) app.use(testrouter.routes ()) App. Use (testRouter allowedMethods ()) app. Listen (3000, () = > {the console. The log (' service startup success ')})Copy the code

The session using

To take advantage of sessions you need to install a library, koA-Session

const Koa = require('koa') const Router = require('koa-router') const Session = require('koa-session'); const app = new Koa(); const testRouter = new Router(); Const session = session ({key: 'sessionID', maxAge: // signed: false, signed: true,}, app); App. keys = ["aa"]; app.use(session) testRouter.get('/test', (ctx, Next) => {// Set session ctx.session.users= {id, name}; // Set session ctx.session.users= {id, name}; ctx.body = value }) testRouter.get('/s', (ctx, next) => { console.log(ctx.session) console.log(ctx.session.users) ctx.body = ctx.session.users }) App. Use (testRouter. Routes ()) app. Use (testRouter. AllowedMethods ()) app. Listen (3000, () = > {the console. The log (' service startup success ')})Copy the code

Why JWT instead of Cookie Session

  1. Cookies are attached to each HTTP request to increase traffic, and some requests are not required
  2. Cookies are passed in plaintext and are secure
  3. Size is 4 KB
  4. On other clients outside the browser, ios and Android need to manually set cookies and sessions to be placed in the header of each request
  5. For distributed systems and server clusters, how to ensure that other systems can correctly resolve sessions (which is cumbersome and requires manual parsing)

JWT use

In node, jsonWebToken library is used to realize token authentication. Firstly, there are two encryption methods: symmetric encryption and asymmetric encryption. Symmetric encryption means that the server saves an encrypted key and uses this key to encrypt and decrypt the token. However, because the encrypted and decrypted keys are the same, the person who knows the key value can not only parse the token but also issue the token, which is very low security

Therefore, asymmetric encryption is often used in projects, using public key and private key to issue tokens with private key and decrypt tokens with public key. In this way, only the private key is protected. For example, the login module issues tokens with private key

Here is an article www.zhihu.com/question/30… About the way JWT

Symmetric encryption

const Koa = require('koa') const Router = require('koa-router') const bodyParser = require('koa-bodyparser') const JWT =  require('jsonwebtoken') const app = new Koa(); const UserRouter = new Router(); App.use (bodyParser()) // Key symmetric encryption const PUBLIC_KEY = '123abc' userrouter. post('/login', (CTX, Next) => {// issue token const user = ctx.request.body; const token = JWT.sign(user,PUBLIC_KEY, { algorithm: 'HS256', expiresIn: Log (ctx.query) ctx.body = token}) userRouter. post('/token', (CTX, next) => { const authorization = ctx.headers.authorization console.log(authorization, 'toklen') const getToken = authorization.replace('Bearer ', Const result = jwt. verify(getToken, const result = jwt. verify(getToken, PUBLIC_KEY) ctx.body = result} catch (error) {ctx.body = 'token invalid '}}) app.use(userrouter.routes ()) App. Use (UserRouter allowedMethods ()) app. Listen (3000, () = > {the console. The log (' service startup success ')})Copy the code

Asymmetric encryption

Use public key private key way, therefore, we want to master the public key and private key to use

Generate public and private keys in the keys folder

Key 1024 // Private key rsa -in private.key -pubout public.key // Public keyCopy the code
// const fs = require('fs') const Koa = require(' Koa ') const Router = require('koa-router') const bodyParser = require('koa-bodyparser') const JWT = require('jsonwebtoken') const app = new Koa(); const UserRouter = new Router(); App.use (bodyParser()) // Introduces symmetric key encryption const PRIVATE_KEY = fs.readfilesync ('./keys/private.key') const PUBLIC_KEY = fs.readFileSync('./keys/public.key') UserRouter.post('/login', (ctx, Next) => {// issue token const user = ctx.request.body; const token = JWT.sign(user,PRIVATE_KEY, { algorithm: 'RS256', expiresIn: Log (ctx.query) ctx.body = token}) userRouter. post('/token', (CTX, next) => { const authorization = ctx.headers.authorization const getToken = authorization.replace('Bearer ', Const result = jwt. verify(hash, PUBLIC_KEY, {algorithms: ['RS256'], }) ctx.body = result} catch (error) {ctx.body = 'token invalid '}}) app.use(userrouter.routes ()) App. Use (UserRouter allowedMethods ()) app. Listen (3000, () = > {the console. The log (' service startup success ')})Copy the code