1. Learn about JWT (JSON Web Token)
- JWT is an open JSON-based standard implemented to deliver declarations in network application environments.
- JWT is used to pass authenticated user identity information between the identity provider and the service provider. In simple terms, it is used for authentication, such as login verification, like cookies we used earlier.
- JWT can use HMAC algorithm or RSA public and private key pair for signature to ensure information reliability.
2. Application scenarios
In a scenario such as authentication, once a user is logged in, each subsequent request contains JWT for authentication information. As the communication parties use JWT to encode the data, its information is signed, so it can ensure the security of the information.
3. JWT compares cookies
Cookie shortcomings
- The client sends a request to the server. After the server plants cookies, each request will bring cookies, wasting bandwidth
- Cookies cannot be accessed across servers and are not supported across domains
- The server needs to store logged user objects, wasting server memory
JWT advantages
- JWT is not state-based, so you do not need to carry tokens with each request to save traffic
- The server takes no memory and the information is relatively reliable
- It can be shared across servers
4. JWT structure
- Header Header: {typ:’ JWT ‘,alg:’HS256’} ALg: the current encryption algorithm; The Base64Url encoding is used to form the first part of the JWT structure
- PlyLoad load: A place to store valid information
- Signature: Create a Signature using an encoded header, payload, and a secret key. For example, if you want to use the HMACSHA256 algorithm, the signature should be HMACSHA256(base64UrlEncode(header) + “.” + base64UrlEncode(payload), secret).
The complete JWT output is a three-segment Base64-encoded secret separated by. The secret is stored on the server, which generates tokens and authentications based on this key, so it needs to be protected.
5. Give me an example
Express +vue+ Mongoose back-end app.js, including registration, login, obtain order interface
let express = require('express')
let bodyParser = require('body-parser') / / middlewarelet jwt = require('jwt-simple')// JWT library // databaselet User = require('./model/user'// Listen to the functionlet app = express()
let {secret} = require('./config'Json (a= B&C =d), text, urlencoded(a= B&C =d) app.use(bodyParser.json())function(req, res, next){
res.setHeader('Access-Control-Allow-Origin'.The '*'); // Simply accept all res.setheader ('Access-Control-Allow-Headers'.'Content-type,Authorization');
res.setHeader('Access-Control-Allow-Methods'.'GET,POST,DELETE,PUT,OPTIONS');
if(req.method === 'OPTIONS') {
res.end()
}else{next()}}) // Register app.post('/reg', async function(req, res, next){
let user = req.body;
try {
user = await User.create(user) //在数据库中插入数据
res.json({
code: 0,
data: {
user: {
id: user._id,
username: user.username
}
}
})
} catch (error) {
res.json({
code: 1,
data: 'Registration failed'})}}) // Log in app.post('/login', async function(req,res,next){
letuser = req.body; User = await user.findone (user)// find in databaseif(user) {
letToken = jwt.encode({// encode id: user._id, username: user.username},secret); Res. json({// return message code: 0, data: {token}})}else {
res.json({
code: 1,
data: 'User does not exist'})}}) // User validation middlewarelet auth = function(req, res, next){// Add Headers Authorization: Bearer token values when post simulation is performedlet authorization = req.headers['authorization']
if(authorization) {
let token = authorization.split(' ') [1]; Try {// check whether the token is valid, decode, if the string is changed token can not be solved, enter the exception pageletuser = jwt.decode(token, secret); req.user = user; // Next (); // Next} catch (error) {console.log(error) res.status(401).send('Not Allowed')}}else {
res.status(401).send('Not Allowed'); }} // send the request to see if it can not verify the success of auth, if it can get the returned data app.get('/order', auth, function(req,res,next){
res.json({
code: 0,
data: {
user: req.user
}
})
})
app.listen(3000)
Copy the code
Database page
// Operate the databaselet mongoose = require('mongoose');
let {DB_URL} = require('.. /config');
mongoose.connect(DB_URL,{useNewUrlParser:true}) /** * Connect successfully */ mongoose.connection.on('connected'.function () {
console.log('Mongoose connection open to '+ DB_URL); }); /** * connection error */ mongoose connection.on('error'.function (err) {
console.log('Mongoose connection error: '+ err); }); // Create Schema data modellet UsrSchema = new mongoose.Schema({
username: String,
password: String
});
module.exports = mongoose.model('User', UsrSchema);
Copy the code
Axios simple encapsulation
import axios from 'axios'
import router from '.. /src/router'
axios.defaults.baseURL = 'http://localhost:3000'/ / axios interceptors to intercept axios. Get data interceptors. Response. Use (function(res){
if(res.data.code ! = = 0) {return Promise.reject(res.data.data)
}
return res.data;
},res=>{
if(res.response.status === 401){// No permission to jump to the login page router.history.push('/login');
}
return Promise.reject('Not Allowed'); }); / / to send request unification and token, to verify whether I login axios. Interceptors. Request. Use (function(config){
let token = localStorage.getItem('token')
if(token) {
config.headers.Authorization = `Bearer ${token}`}return config;
})
export default axios
Copy the code
config.js
module.exports = {
'DB_URL': 'mongodb://localhost:27017/jwt'.'secret': 'jeffywin'// Add salt to key}Copy the code
Vue – CLI scaffolding, nothing to say, login interface
<template>
<div class="main">
<div class="item">
<div style="width:100px"> login page </div> <inputtype='text' v-model='user.username'/>
</div>
<div class="item">
<div style="width:100px"> Password </div> <inputtype='text' v-model='user.password'/>
</div>
<button @click="login"</button> </div> </template> <script> import axios from'.. /.. /utils/axios'
export default {
data() {
return {
user: {
username: ' ',
password: ' '
}
}
},
methods: {
login() {
axios.post('/login',this.user).then(res => {
localStorage.setItem('token', res.data.token)// Store token this after login.$router.push('/order')
})
}
}
}
</script>
<style scoped lang="scss">
.main {
margin: 0 auto;
width: 300px;
.item {
display: flex;
margin-bottom: 10px;
}
}
</style>
Copy the code
The order interface
<template>
<div class="order"> <h1>This is an order page</h1> {{username}}// If login is successful, jump to the order interface, get the login user </div> </template> <script> import axios from'.. /.. /utils/axios'
export default {
data() {
return {
username: ' '}},mounted() {
axios.get('/order').then(res => {
this.username = res.data.user.username
})
},
}
</script>
Copy the code
Github github.com/jeffywin/jw…