我正在尝试为我的服务器创建登录请求。我想学的是什么 如何在用户登录时创建令牌。在创建令牌后,我想用该令牌控制用户的请求。这是我的代码示例。请告诉我哪里出错了。如果一切正确,你能解释一下如何创建吗?
var port = 8080;
var express = require("express");
var bodyParser = require('body-parser');
var mysql = require('mysql');
var bcrypt = require('bcrypt');
var session = require('express-session');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "123456",
database: "circles",
debug: false
});
process.on('uncaughtException', function (err) {
console.log('UNCAUGHT', err.stack);
});
var app = express();
app.use(express.static("localhost" + "/public")); //use static files in ROOT/public folder
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({secret: 'letsputasmile',
proxy: true,
resave: true,
cookie: { maxAge : 2628000000 },
saveUninitialized: true
}));
app.get("/", function(request, response){ //root dir
response.send("Hello!!");
console.log(response);
});
app.post("/register", function (request, response) {
var name = request.body.name;
var username = request.body.username;
var pass = request.body.pass;
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(pass,salt);
console.log(name);
console.log(username);
console.log(pass);
con.query("Insert Into user(name,username,password) Values(\"" + name + "\"," + "\"" + username + "\"," + "\"" + hash + "\")",
function (err,result) {
if(err) response.send("nop");
else response.send("success");
});
});
app.post("/login", function(request, response) {
var username = request.body.username;
var pass = request.body.pass;
var passer;
con.query("select password from user where username = " + "\"" + username + "\"",function (err, result) {
if(err) throw err;
if(result.length === 1) {
passer = result[0].password;
}
bcrypt.compare(pass, passer, function (err, res) {
if(res) response.send("success");
else response.send("nop");
});
});
});
app.listen(port);
答案 0 :(得分:1)
你可以做的是创建一个jwt
(json webtoken)。您基本上签署了一些有效负载(无论您想要给客户端提供什么元数据),然后客户端可以在请求内容时将令牌传回,服务器可以验证令牌(对称密钥)是否正确并且还可以解析输出服务器所需的数据,例如user_id
或类似的。