最近在app的开发过程中,做了一个基于token的用户登录认证,使用vue+node+mongoDB进行的开发,前来总结一下。
token认证流程:
1:用户输入用户名和密码,进行登录操作,发送登录信息到服务器端。
2:服务器端查询数据库验证用户名密码是否正确,正确,通过jsonwebtoken生成token,返回给客户端;否则返回错误信息给客户端。
3:通过本地存储存储获取的token信息,并且会跳转到路由指定的页面。
4:当客户端需要请求数据时,发送请求,并且在请求的头文件中添加本地存储的token信息。
5:服务器端获取到请求头文件中的token信息,解析token信息,验证是否有效,有效,查询数据库,返回请求的数据。
客户端与服务器端关于token的验证示意图:
1:用户登录的模型骨架文件user.js
‘use strict‘; let mongoose = require(‘mongoose‘), Schema = mongoose.Schema; let userSchema = new Schema({ "username": String, "password": String, "token": String, "create_time": Date }); let users = mongoose.model(‘users‘, userSchema); module.exports = users;
2:服务器端api请求文件api.js
const express = require(‘express‘); const router = express(); const db=require(‘../db/db.js‘); const User=require(‘../db/user.js‘); const Login=require(‘../db/login.js‘); const Fan=require(‘../db/fan.js‘); const Power=require(‘../db/power.js‘); const createToken = require(‘../token/createToken‘); const checkToken = require(‘../token/checkToken‘); // 注册 router.post(‘/add‘, function(req, res, next){ let username = req.body.username, password = req.body.password; let newUser = new User({ username: req.body.username, password: req.body.password }); User.findOne({"username":username},(err, result) => { if(err){ console.log(‘error:‘ + err); return; } console.log(‘result:‘,result); if(!result){ newUser.save(function(err, result){ if(err){ console.log(‘error:‘ + err); return; } res.send({success: true, msg: ‘注册成功‘}); }); }else{ res.send({success: false, msg: ‘用户名已经存在‘}); } }); }); // 登录 router.post(‘/login‘, function(req, res, next){ let username = req.body.username, password = req.body.password; User.findOne({"username":username},(err, result) => { if(err){ res.send({success: false, msg: ‘用户名不存在‘}) console.log(‘error:‘ + err); return; } console.log(‘result:‘,result) if(result.password === password){ console.log(‘登录成功‘) // 调用token生成函数 let _token = createToken(username); // 保存token到数据库中 result.token = _token; result.save((err) => { if(err){ console.log(‘error:‘ + err + ‘token‘) } }) if(result){ res.send({success: true, msg: ‘登录成功‘, token: _token}); }else{ res.send({success: false, msg: ‘登录失败‘}); } }else{ res.send({success: false, msg: ‘密码错误‘}); } }); }); // token router.post(‘/createtoken‘, function(req, res, next){ let username = req.body.username; User.findOne({"username":username},(err, result) => { if(err){ res.send({success: false, msg: ‘用户名不存在‘}) console.log(‘error:‘ + err); return; } console.log(‘result:‘,result) let token = createToken(username); result.token = token; result.save((err) => { if(err){ console.log(‘error:‘ + err + ‘token‘) } }) if(result){ res.send({success: true, msg: ‘登录成功‘, token: token}); }else{ res.send({success: false, msg: ‘登录失败‘}); } }); }); // 删除用户// 删除用户时,验证token信息是否过期 router.get(‘/delete‘, checkToken, function(req, res, next){ let _username = req.body.username; User.remove({username: _username}, (err, result) => { if(err){ console.log(‘error:‘ + err); return; } res.send(result); }); }); module.exports = router;
3:服务器端token生成文件createToken.js
const jwt = require(‘jsonwebtoken‘); module.exports = function(user_id){ const token = jwt.sign({ user_id: user_id }, ‘[email protected]‘, { expiresIn: 60 //过期时间设置为60 }); return token; };
4:服务器端验证token是否正确文件checkToken.js
const jwt = require(‘jsonwebtoken‘); //检查token是否过期 module.exports = function(req, res, next) { // 获取请求头文件中的token信息 let token = req.body.token || req.query.token || req.headers[‘authorization‘]; console.log(token) // 解析 token if (token) { // 确认token是否正确 let decoded = jwt.decode(token, ‘[email protected]‘); console.log(decoded,44444) // 验证token是否过期 if(token && decoded.exp <= new Date()/1000){ return res.json({ success: false, message: ‘token过期‘ }); }else{ return next(); } } else { // 如果没有token,则返回错误 return res.status(403).send({ success: false, message: ‘没有提供token!‘ }); } };
5:服务器端启动文件
const express = require("express"); var bodyParser=require(‘body-parser‘); const app = express(); const api = require(‘./router/api‘) // 跨域设置 app.all("*", function(req, res, next) { res.header("Access-Control-Allow-Credentials", true); res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); res.header("Content-Type", "application/json;charset=utf-8"); // 设置请求头类型 添加token res.header(‘Access-Control-Allow-Headers‘, ‘Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild‘); next(); }); app.use(bodyParser.urlencoded({extended:true})); app.use("/api", api); app.get(‘/‘, (req, res) => { res.send(‘Hello World‘); }); const port = process.env.PORT || 3001; app.listen(port, () => { console.log(‘Express server listening on port ‘ + port); }); module.exports = app;
6:vue中用户登录操作
login () { let params = new URLSearchParams(); params.append(‘username‘, this.login_username); params.append(‘password‘, this.login_password); let _token = localStorage.getItem(‘token‘); let that = this; console.log(_token) axios.post(‘http://localhost:3001/api/login‘, params, {headers:{‘Content-Type‘:‘application/x-www-form-urlencoded‘,‘Authorization‘: _token}}) .then(function(res){ console.log(res) if(res.data.success){ let token = res.data.token; localStorage.setItem(‘token‘, token); that.$router.push({ path: ‘/index‘ }) } }) .catch(function(err){ console.log(err) }); },
原文地址:https://www.cnblogs.com/sk-3/p/9188168.html
时间: 2024-10-10 06:11:14