egg.js使用egg-jwt实现鉴权登录

                                                egg.js使用egg-jwt实现鉴权登录

1、安装egg-jwt:

npm i egg-jwt --save

2、配置plugin.js:

                              egg.js使用egg-jwt实现鉴权登录_第1张图片

3、配置config.default.js:

                                egg.js使用egg-jwt实现鉴权登录_第2张图片

4.编写controller:  login.js

/*
 * @Description: 文件描述:
 * @Autor: hwf
 * @Date: 2020-12-28 18:06:51
 * @LastEditors: Seven
 * @LastEditTime: 2021-04-22 14:26:17
 */
'use strict';

const Controller = require('egg').Controller;

class LoginController extends Controller {

	// 登录
	async login() {
		const { ctx, app } = this;
		const { userName, password } = ctx.request.body;
		const { result } = await ctx.service.login.login(userName, password);

		if (result.length > 0) {
			const token = app.jwt.sign({
				'userName': userName, //需要存储的 token 数据
			}, app.config.jwt.secret, { expiresIn: '2h' }); // 2分钟token过期

			ctx.set({ 'token': token })//设置headers

			ctx.body = {
				code: '200',
				data: [{
					token: token,
					userName: result[0].userName,
					userId: result[0].userId
				}],
				message: 'success'
			};

		} else {
			ctx.body = {
				code: '401',
				data: result,
				message: '账号或密码错误'
			};
		}
	}
	async logOut() {
		const { ctx, app } = this;
		try {
			const userInfo = { ...ctx.state.userInfo };
			const res = await ctx.service.login.index.redisDelUserToken(userInfo.id);
			if (!res) {
				throw new Error('userInfo not found');
			}
			ctx.body = {
				code: 200,
				status: 'success',
				msg: '退出登录成功',
				data: {},
			};
		} catch (err) {
			switch (err.message) {
				case 'userInfo not found':
					ctx.body = {
						code: 403,
						status: 'fail',
						msg: '退出登录失败',
						data: {},
					};
					break;
				default:
					ctx.body = {
						code: 403,
						status: 'fail',
						msg: '数据异常',
						data: {},
					};
			}
		}
	}
}

module.exports = LoginController;

5.编写services:

/*
 * @Description: 文件描述:
 * @Autor: hwf
 * @Date: 2020-12-28 18:06:57
 * @LastEditors: Seven
 * @LastEditTime: 2021-04-22 14:46:42
 */
'use strict';

const Service = require('egg').Service;
const crypto = require('crypto');

class LoginService extends Service {
	getMd5Data(data) {
		return crypto.createHash('md5').update(data).digest('hex');
	}
	async login(username, password) {
		const psd = this.getMd5Data(password);
		const data = await this.app.mysql.query(`SELECT * FROM user WHERE user_name='${username}' and user_pwd='${psd}'`);
		const result = JSON.parse(JSON.stringify(data));
		return { result };
	}
}

module.exports = LoginService;

6.编写中间件:jwtErr.js

/*
 * @Description: 文件描述:
 * @Autor: hwf
 * @Date: 2021-04-22 11:36:59
 * @LastEditors: Seven
 * @LastEditTime: 2021-04-22 14:47:31
 */

// 接口先去header判断是否存在token,存在就验证,不存在就返回信息。
module.exports = (options, app) => {
    return async function jwtErr(ctx, next) {
        const token = ctx.request.header.token;
        if (token) {
            try {
                ctx.app.jwt.verify(token, options.secret); // 验证token 
                await next();
            } catch (error) {
                ctx.status = 401;
                ctx.body = {
                    massage: 'token已过期,请重新登录',
                    code: -1,
                }
                return;
            }
        } else {
            ctx.status = 401;
            ctx.body = {
                message: 'token不存在',
            };
            return;
        }
    }
}

7.配置路由:       
egg.js使用egg-jwt实现鉴权登录_第3张图片

8.最终效果:
 

egg.js使用egg-jwt实现鉴权登录_第4张图片

 请记得加请求头token:egg.js使用egg-jwt实现鉴权登录_第5张图片

9:总结:

           这里只是实现了简单的验证登录,如果需要实现单端登录,需要引入redis进行存储,然后进行相应的比较,登录功能还有问题。

你可能感兴趣的:(egg,node.js)