Learn about JSON Web Tokens

According to Wikipedia, a JSON WEB Token (JWT) is a JSON-based Token used to make a claim on the WEB. A JWT usually consists of three parts: header, payload, and signature.

The header specifies the signature algorithm used by the JWT:

header = '{"alg":"HS256","typ":"JWT"}'
Copy the code

The message body contains the intent of JWT:

payload = '{"loggedInAs":"admin","iat":1422779638}'
Copy the code

The signature is computed using a private key:

key = 'secretkey'  
unsignedToken = encodeBase64(header) + '. ' + encodeBase64(payload)  
signature = HMAC-SHA256(key, unsignedToken) 
Copy the code

Finally, the base64URL-encoded signature (again separated by “.”) is concatenated at the end of the unsigned token, which is JWT:

token = encodeBase64(header) + '. ' + encodeBase64(payload) + '. ' + encodeBase64(signature) 
Copy the code

An Egg. Js JWT practice

Install the egg-jWT plugin

npm install egg-jwt --save
Copy the code

2. Enable the egg-jWT plugin

// {app_root}/config/plugin.js
exports.jwt = {
  enable: true,
  package: "egg-jwt"
};
Copy the code

3. Configure the JWT private key

// {app_root}/config/config.default.js
exports.jwt = {
  secret: "123456"// self-set value};Copy the code

4. Configure routes

// {app_root}/app/router.js      
  router.get('/', controller.home.index);
  router.post('/user',app.jwt,controller.home.user);
  router.get('/login',controller.home.login);
Copy the code

5. The Login method

onst user = ctx.request.body
    if(user && user.name) {
        let userToken = {
            name: user.name
        }
        const token = app.jwt.sign(userToken, secret, {expiresIn: '1h'}) // Token signature valid for 1 hour ctx.body = {message:'Token obtained successfully',
            code: 1,
            token
        }
    } else {
        ctx.body = {
            message: 'Parameter error',
            code: -1
        }
    }
	  }
Copy the code

6. The User

Const token = ctx.header.authorization // Get JWTlet payload
    if (token) {
        payload = await app.jwt.verify(token.split(' 'Body = {payload}} body = {payload}}else {
        ctx.body = {
            message: 'token error',
            code: -1
        }
    }
Copy the code

Using curl to simulate a request

Curl http://127.0.0.1:7001/user / / return the Authentication Erro / / validation errors, explain our JWT has been effectiveCopy the code

Visit http://127.0.0.1:7001/login take a parameter name

curl -d "name=tiptoe"/ / returns the {http://127.0.0.1:7001/api/login"message":"Obtaining token successfully"."code": 1,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoidGlwdG9lIiwiaWF0IjoxNDk2Mzg4NzgwLCJleHAiOjE0OTYzOTIzODB9.N2e-84Pmf466D QJ2x3ldd1AWC1IL97ZRWwiDR-Oebhs"}
Copy the code

Then add token in the header, on a visit to http://127.0.0.1:7001/user

// Authorization: Bearer: Bearer curl -H"Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoidGlwdG9lIiwiaWF0IjoxNDk2Mzg4NzgwLCJleHAiOjE0OTYzOTIzODB9.N2e-84Pmf466DQ J2x3ldd1AWC1IL97ZRWwiDR-Oebhs" http://127.0.0.1:7001/user
Copy the code

If the following information is displayed, the authentication is successful

{"payload": {"name":"tiptoe"."iat": 1496398614,"exp": 1496402214}}Copy the code