内容纲要

目录结构

[code]
├── controllers
│ └── authenticate-controller.js
├── node_modules
├── config.js
├── index.js
└── package.json
[/code]

package.json

[code language=”js”]
{
"name": "jwt",
"version": "1.0.0",
"description": "jwt authentication",
"main": "index.js",
"dependencies": {
"body-parser": "^1.17.1",
"express": "^4.14.1",
"jsonwebtoken": "^7.3.0",
"mysql": "^2.13.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
[/code]

express module is the very popular Node framework.

body-parser module is used to get data from POST request.

jsonwebtoken module is used to generate and authenticate our JSON Web Tokens.

mysql module is how you work with database.

config.js

[code language=”js”]
var mysql = require(‘mysql’);
var connection = mysql.createConnection({
host : ‘localhost’,
user : ‘root’,
password : ”,
database : ‘test’
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports = connection;
[/code]

index.js

[code language=”js”]
var express=require("express");
var bodyParser=require(‘body-parser’);
var jwt= require("jsonwebtoken");
var app = express();
var router=express.Router();
var authenticateController=require(‘./controllers/authenticate-controller’);
process.env.SECRET_KEY="thisismysecretkey";
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post(‘/api/authenticate’,authenticateController.authenticate);
app.use(‘/secure-api’,router);
// validation middleware
router.use(function(req,res,next){
var token=req.body.token || req.headers[‘token’];
if(token){
jwt.verify(token,process.env.SECRET_KEY,function(err,ress){
if(err){
res.status(500).send(‘Token Invalid’);
}else{
next();
}
})
}else{
res.send(‘Please send a token’)
}
})
router.get(‘/home’,function(req,res){
res.send(‘Token Verified’)
})
app.listen(8012);
[/code]

controllers/authenticate-controller.js

[code language=”js”]
var jwt=require(‘jsonwebtoken’);
var connection = require(‘./../config’);
module.exports.authenticate=function(req,res){
var email=req.body.email;
var password=req.body.password;
connection.query(‘SELECT * FROM users WHERE email = ?’,[email], function (error, results, fields) {
if (error) {
res.json({
status:false,
message:’there are some error with query’
})
}else{
if(results.length >0){
if(password==results[0].password){
var token=jwt.sign(results[0],process.env.SECRET_KEY,{
expiresIn:5000
});
res.json({
status:true,
token:token
})
}else{
res.json({
status:false,
message:"Email and password does not match"
});
}

}
else{
res.json({
status:false,
message:"Email does not exits"
});
}
}
});
}
[/code]

运行服务器
[code]
node index.js
[/code]
 

登录


Generate token using JWT

测试 JWT 认证

Invalid token

发送带 token 请求

Vefiry token with JWT

发表评论

电子邮件地址不会被公开。 必填项已用*标注