我创建了一个Rest Api,它在mysql数据库上执行一些查询。通过使用oclif构建的CLI访问api。我试图在执行查询之前验证令牌。我想在同一文件(routes.js)中进行验证。该文件如下所示:
module.exports = app => {
const entry = require("../controlers/entry.controller.js");
const sql = require("../models/db.js");
const bcrypt = require('bcrypt');
var express=require('express');
// Retrieve a single Entry with Id
var fs=require('fs');
var privateKey = fs.readFileSync('private.key');
var jwt=require('express-jwt');
app.use(
jwt({
secret: privateKey,
credentialsRequired: false,
getToken: function fromHeaderOrQuerystring (req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return null;
}
}));
app.get("/entry/:Id", entry.findOne);
app.post("/energy/api/Login", function(req,res){
var jwt=require('jsonwebtoken');
sql.query(`SELECT user,pass,quota,apikey,email FROM users WHERE user=?`,[req.query.username],(err,res1) => {
//console.log(res1);
const password=res1[0].pass;
const e=res1[0].email;
const a=res1[0].apikey;
const q=res1[0].quota;
const p=res1[0].privileges;
if(bcrypt.compareSync(req.query.passw,password)){
var jwt=require('jsonwebtoken');
var privateKey = fs.readFileSync('private.key');
var token = jwt.sign({user:req.query.user ,passw: req.query.passw,email: e, quota: q,apikey: a,privileges: p }, privateKey, { algorithm: 'HS256' });
res.status(200).send(token);
}
else res.status(400).send("Bad Request");
});
});
在登录部分,创建令牌并将其返回给CLI。然后cli会执行以下操作:
axios.defaults.headers.common['X-OBSERVATORY-AUTH']="Bearer " + token;
await cli.anykey();
//create new user
if (`${flags.newuser}` !== "undefined" && `${flags.passw}` !== "undefined" && `${flags.email}` !== "undefined" && `${flags.quota}` !== "undefined" ){
let hash = bcrypt.hashSync(`${flags.passw}`,10);
await axios.post('https://localhost:8765/energy/api/Admin/users?username=' +`${flags.newuser}` +'&passw=' + hash +'&email=' + `${flags.email}` +'"a=' + `${flags.quota}`);
}
但是,当routes.js文件获得post命令时,它会像这样处理它:
app.put("/energy/api/Admin/users/:username",async function(req,res){
if (req.params.username !== "undefined" && req.query.email !== "undefined" && req.query.quota !== "undefined"){
console.log(req.params.username);
sql.query(`UPDATE users SET pass=?,email=?,quota=? WHERE user=?`,[req.query.passw,req.query.email,req.query.quota,req.params.username],(err,res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
});
}
res.send("Successful");
});
我想添加一些中间件来验证令牌,并还要检查参数quota是否大于0,以及是否将其减少一。我该怎么办?
Declaration:此代码编写在node.js,express.js
中首先,您的代码未模块化。并且您必须编写路由中间件来保护路由,而不是全局中间件
我认为该项目将帮助您理解jwt,express code(https://github.com/ahari884/simple-node-boilerplate)请检查它,您将在Express中找到如何为路由编写jwt身份验证
您可以像这样编写专用的中间件:
const jwt = require('jsonwebtoken');
export async function verifyJWTToken(request, response, next) {
/*
* Normally JWTs are specified as Bearer Tokens.
* Authorization Header will have something like 'Bearer <token>'
*/
const header = request.headers.authorization;
if (header && header.startsWith('Bearer ')) { tokens
const token = header.slice(7, header.length);
const secret = process.env.JWT_SECRET;
try {
jwt.verify(token, secret);
next();
} catch (error) {
next(new Error('Authentication Failed'));
}
} else {
next(new Error('Missing Authentication Token'));
}
}
您可以通过在控制器功能之前提供中间件来保护路由:
app.route('/users').get(verifyJWTToken, getUsers) //getUsers() is the controller function