当前位置:网站首页>Using jsonwebtoken to realize JWT authentication in node project
Using jsonwebtoken to realize JWT authentication in node project
2022-07-22 06:37:00 【Ke Xiaonan】
1、 Requirement specification
In front and back end separation development , Front end use Vue.js frame , adopt axios Send asynchronously HTTP request , The server cannot be used session Save the login information of the user , Because every asynchronous request from the client will be considered as a new one on the server session. We can use jwt(jsonwebtoken) To realize user verification .
2、 Installation dependent
Server side :
Used in this article Express As a server-side framework , You need to install the following on the server JWT rely on :
cnpm i jsonwebtoken --save
cnpm i express-jwt --save
front end :
Use... On the front end Vue.js frame , Need to install axios Used for sending HTTP request :
cnpm i axios --save
3、 Code implementation
3.1、 Server code
app.js Import file express-jwt
, The sample code is as follows :
var express = require('express');
var expressJwt = require('express-jwt');
var app = express();
app.use(expressJwt({
credentialsRequired:false,
secret: 'helloworld', // secret key
algorithms: ['HS256'] // There is no such configuration item , stay jwt6.0.0 The version will report an error :algorithms should be set
}).unless({
path: ['/login'] // Settings don't need token Verified route
}))
express-jwt
The... In the request header will be automatically verified token
Information .
stay routes/index.js Create a route for login and user query in the route file , The sample code is as follows :
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
// Route for user login , This route will not be token check
router.post('/login', function(req, res, next) {
let {
username,pwd} = req.body
// Simulate database query account password
if(username === 'admin' && pwd === '123456'){
// Generate Token Information jwt.sign(payload, secretOrPrivateKey, [options, callback])
//payload The parameter is the user information saved to the client ,
//secretOrPrivateKey As the key , Want to be with app.js In the document secret Consistent values for
//option For configuration items ,expiresIn yes token Effective time , The unit is in seconds , The value can also be a string , for example '2d' Express 2 God
let Token = jwt.sign({
name: username,role: 1},'helloworld',{
expiresIn: 60})
res.json({
code: 200,
token: 'Bearer '+Token // Responding to the client token You have to add ’Bearer ’ Prefix
})
}else{
res.json({
code: 500
})
}
});
// Route for querying user information , This route will verify token
router.get('/api/user/find', function(req,res,next){
res.json({
code: 200,
result: ['tom','jack','lily']
})
})
module.exports = router;
jwt.sign()
Method can also use asynchronous encryption , The sample code is as follows :
// Use asynchronous method to generate token
jwt.sign(
{
name:username,role:1},
'helloworld',
{
expiresIn:60},
function(err,token){
console.log(token)
}
)
3.2、 The front-end code
views/Login.vue User login component , The sample code is as follows :
<template>
<div>
<input type="text" v-model="username" placeholder=" user name "></input>
<input type="password" v-model="pwd" placeholder=" password "></input>
<button @click="login"> Sign in </button>
</div>
</template>
<script> import axiost from 'axios' export default {
data(){
return {
username: '', pwd: '' } }, methods: {
login(){
// Login button click event axios.post("/login",{
username: this.username, pwd: this.pwd }).then(res=>{
if(res.data.code === 200){
// preservation token Information localStorage.token = res.data.token } }) } } } </script>
The front-end check token There are several ways to do this :
(1) Use Vue Routing guard verification of
// Judge in the global front guard of the route token Whether there is
router.beforeEach((to , from, next) => {
// obtain token
if (localStorage.token)) {
if (to.name === 'login') {
// If the user is login page
next('/');
} else {
next();
}
} else {
router.push('/login')
}
});
(2) stay axios Request to add token Information
// axios Request interceptor
axios.interceptors.request.use(
config => {
if (localStorage.token) {
// Judge whether it exists token
config.headers.authorization = localStorage.token;
}
return config;
},
err => {
return Promise.reject(err);
});
//axios Response interceptors
axios.interceptors.response.use(res => {
return res;
}, err=> {
if (err.response.status === 401) {
//token Check failed , No access rights
// Output authorization failure error message
} else {
// Output other error messages
}
return Promise.reject(err);
}
);
You can also directly axios
Set headers
, The sample code is as follows :
let instance = axios.create({
baseURL: 'http://localhost:3000',
headers:{
authorization: localStorage.getItem('token')
}
})
instance.get('/xxx')
3.3、 Server-side validation token And get the user information
On the server side, you can use express-jwt
Automatic verification , You can also manually complete the verification , We can also get the user information saved to the client on the server . On the server side routes/index.js
Write a in the routing file for token Verify the test route , The sample code is as follows :
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
// Used to verify token And get the user information
router.get('/yz', function(req,res,next){
// Get... From the request header token Content
let token = req.headers.authorization
// because token Contained in the 'Bearer ' Prefix , You need to remove the prefix to get token value
token = token.replace('Bearer ','')
let result = null;
try{
//jwt.verify(token,secretOrPublicKey,[options,callback]) verification token Legitimacy
// secretOrPublicKey The parameter is the key , To and build token Keep your keys consistent
result = jwt.verify(token,'helloworld')
console.log(result)
}catch(err){
console.error(err)
}
res.json({
result
})
})
module.exports = router;
The result printed on the console is as shown in the following figure :jwt.verify()
The value returned by the method is jwt.sign()
Methods payload
Object parameters ,JWT Specifies the 7 Official fields , For selection , Namely :
- iss (issuer): Issued by people
- exp (expiration time): Expiration time
- sub (subject): The theme
- aud (audience): Audience
- nbf (Not Before): entry-into-force time
- iat (Issued At): The issuance of time
- jti (JWT ID): Number
边栏推荐
- β- Preparation of cyclodextrin derivative grafted hydroxypropyl chitosan hydrogel / carboxyl modified chitosan supported cyclodextrin hydrogel microspheres
- unity 设置物体不能被穿透
- Leetcode skimming: middle order traversal of binary trees
- 攻防演练进行时|知道创宇赵伟:让安全能力长在云上
- 2022-07-21日报:吴恩达撰文:如何建立适应AI职业生涯的项目
- CAD对象的夹点被编辑完成后调用事件(com接口VB语言)
- Preparation method of polyether / polyacrylamide monomethyl / Polyacrylamide / granular poly (N-isopropylacrylamide) chitosan hydrogel
- Height collapse and clear float
- DOM Series event object
- DOM系列之DOM事件流
猜你喜欢
随机推荐
Leetcode skimming: the penultimate node in the linked list
To create a private Ca, I use OpenSSL
Preparation of chitosan / dextran / nano hydroxyapatite composite hydrogel / fish gelatin galactose chitosan hydrogel liver scaffold
软件测试:等价类测试与基于判定表测试及综合题解析
化合物修饰壳聚糖水凝胶:丙烯酸接枝/聚乙烯醇/温敏淫羊藿苷/醛-亚胺-壳聚糖水凝胶的制备
LeetCode刷题:位运算(找不同 和 只出现一次的数字)
List labels and hyperlinks
Leetcode skimming: using stack to realize queue and string decoding
U++ 学习笔记 悬浮Actor
The orders in the same city are delivered in the same city, and the order explosion is still handy!
NI LABVIEW 2019安装教程,ATECLOUD免安装可在线使用
壳聚糖接枝聚乙醇酸共聚物水凝胶/木质素磺酸钠/聚唾液酸-壳聚糖衍生物水凝胶的制备
Detailed steps for installing and uninstalling MySQL
创建私有CA,我就用openSSL
Node+Express实现文件的上传下载与删除
Western Agricultural University C plus
IDEA 搭建和环境变量
Is the income of fixed income financial products certain?
LeetCode刷题:对称二叉树与二叉树的最大深度
Statistical analysis: cluster analysis (detailed explanation)