关于koa-jwt使用的疑问
发布于 1 年前 作者 1261407209LHH 1845 次浏览 来自 问答

在入口文件中对login、register过滤不需要进行验证,通过isRevoked对其他的接口的token验证。为什么访问getuserinfo的时候不加 Bear token请求头authoration也能访问到接口的信息。网上搜寻了很多博客文章,还是直接可以不加token的header访问到别的接口,表示很疑问

  • app.js入口文件
	const Koa = require("koa");
	const app = new Koa();
	const json = require("koa-json");
	const onerror = require("koa-onerror");
	const bodyparser = require("koa-bodyparser");
	const logger = require("koa-logger");
	const koaJwt = require("koa-jwt");
	const router = require("./routes/index");
	const config = require("./config/index");
	const util = require("./util/index");
	const errorHandle = require("./util/error.js");
	const { connect } = require("./model/init");
	onerror(app);
	
	app.use(
	  bodyparser({
		enableTypes: ["json", "form", "text"]
	  })
	);
	app.use(json());
	app.use(logger());
	app.use(require("koa-static")(__dirname + "/public"));
	app.use(async (ctx, next) => {
	  const start = new Date();
	  await next();
	  const ms = new Date() - start;
	  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
	});
	app.use(errorHandle);
	app.use(router.routes(), router.allowedMethods());
	app.use(
	  koaJwt({
		secret: config.secret,
		isRevoked: util.verify
	  }).unless({
		path: [/\/login/, /\/register/]
	  })
	);
	(async () => {
	  await connect();
	})();
	app.on("error", (err, ctx) => {
	  console.error("server error", err, ctx);
	});
	module.exports = app;
  • jwt的401,errorhandle文件
	module.exports = (ctx, next) => {
	// console.log(ctx.request.body);
	return next().catch(err => {
	  if (err.status === 401) {
		ctx.status = 401;
		ctx.body = "UnAthoration to get the data";
	  } else {
		throw err;
	  }
	});
  };
  • 路由控制文件
	const userModel = require("../model/userModel.js");
	const config = require("../config/index.js");
	const util = require("../util/index");
	module.exports = {
	  register: async (ctx, next) => {
		console.log("****",ctx);
		let { name, password } = ctx.request.body;
		if (name && password) {
		  password = util.createHash(password);
		  const result = await new userModel({
			name: name,
			password: password
		  }).save();
		  console.log("register result is", result);
		  if (!result)
			return (ctx.body = {
			  code: "400",
			  message: "register fail"
			});
		  else
			return (ctx.body = {
			  code: "200",
			  message: "register success!"
			});
		}
	  },
	  login: async (ctx, next) => {
		const data = ctx.request.body;
		if (!data.name || !data.password) {
		  return (ctx.body = {
			code: "",
			data: null,
			message: "the usernumber or password can't be null"
		  });
		}
		data.password = util.createHash(data.password);
		const result = await userModel.find({
		  name: data.name,
		  password: data.password
		});
		if (result && result.length) {
		  const token = util.sign(result);
		  return (ctx.body = {
			code: "200",
			token: token,
			message: "login success"
		  });
		} else {
		  return (ctx.body = {
			code: "400",
			data: null,
			message: "usernumber or password is error"
		  });
		}
	  },
	  getuserinfo: async (ctx, next) => {
		return (ctx.body = {
		  msg: "nothing"
		});
	  }
	};

  • jwt验证文件
	const crypto = require("crypto");
	const config = require("../config/index");
	const jwt = require("jsonwebtoken");
	module.exports = {
	  createHash: value => {
		const hmac = crypto.createHash("sha256", config.secret);
		hmac.update(value);
		return hmac.digest("hex");
	  },
	  sign(result) {
		return jwt.sign(
		  {
			_id: result._id,
			name: result.name
		  },
		  config.secret,
		  config.expiresIn
		);
	  },
	  verify(ctx, decodedToken, token) {
		let ret = true;
		try {
		  const payload = jwt.verify(token, config.secret);
		  console.log(payload);
		  if(payload)
			ret = false;
		} catch (err) {
		  console.log(err.name);
		}
		return ret;
	  }
	};
2 回复

挪到 app.use(router.routes(), router.allowedMethods()); 前面试试?

@zengming00 还真的可以了,谢谢老铁。太粗心了,别人的博客文章都没仔细去看

回到顶部