我当前正在实施JWT身份验证-我根据本教程https://medium.com/dev-bits/a-guide-for-adding-jwt-token-based-authentication-to-your-single-page-nodejs-applications-c403f7cf04f4实施了它。而且,虽然我的代码有效,但是我无法弄清楚如何使用密码和用户名从我的前台发送发帖请求。本教程使用此命令在终端中运行以登录:
curl --header "Content-Type: application/json" \
--request POST \
--data '{"password":"password", "username":"admin"}' \
http://localhost:8000/login
如何将该命令转换为以下形式的发布请求:
http.post('URL', <data>)
这样我可以从前端发出请求?
后端登录处理后的登录请求后,将调用HandlerGenerator类的登录方法,您可以在此处找到它:
const express = require('express');
const bodyParser = require('body-parser');
let jwt = require('jsonwebtoken');
let config = require('./config');
let middleware = require('./middleware');
class HandlerGenerator {
login (req, res) {
let username = req.body.username;
let password = req.body.password;
// For the given username fetch user from DB
let mockedUsername = 'admin';
let mockedPassword = 'password';
if (username && password) {
if (username === mockedUsername && password === mockedPassword) {
let token = jwt.sign({username: username},
config.secret,
{ expiresIn: '24h' // expires in 24 hours
}
);
// return the JWT token for the future API calls
res.json({
success: true,
message: 'Authentication successful!',
token: token
});
} else {
res.send(403).json({
success: false,
message: 'Incorrect username or password'
});
}
} else {
res.send(400).json({
success: false,
message: 'Authentication failed! Please check the request'
});
}
}
index (req, res) {
res.json({
success: true,
message: 'Index page'
});
}
}
// Starting point of the server
function main () {
let app = express(); // Export app for other routes to use
let handlers = new HandlerGenerator();
const port = process.env.PORT || 3000;
////////////////////////////////////////////////////////////////////////////////////
app.use(bodyParser.urlencoded({ // Middleware
extended: true
}));
app.use(bodyParser.json());
// catch 404 and forward to error handler
app.use(function(req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
////////////////////////////////////////////////////////////////////////////////////
// Routes & Handlers
app.get('/', middleware.checkToken, handlers.index);
////////////////////////////////////////////////////////////////////////////////////
app.post('/login', handlers.login);
////////////////////////////////////////////////////////////////////////////////////
app.listen(port, () => console.log(`Server is listening on port: ${port}`));
module.exports = app;
}
main();
如果发出带有令牌而不是登录信息的请求,则使用中间件来验证令牌:
let jwt = require('jsonwebtoken');
const config = require('./config.js');
let checkToken = (req, res, next) => {
let token = req.headers['x-access-token'] || req.headers['authorization']; // Express headers are auto converted to lowercase
if (token) {
if (token.startsWith('Bearer ')) {
// Remove Bearer from string
token = token.slice(7, token.length);
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.json({
success: false,
message: 'Token is not valid'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.json({
success: false,
message: 'Auth token is not supplied'
});
}
};
module.exports = {
checkToken: checkToken
};
如果您能告诉我如何将用于通过终端登录的命令转换为正确的帖子请求(可以在我前面使用),那将非常有帮助...非常感谢您的帮助!
最好的问候,山姆
答案 0 :(得分:0)
应该是
http.post(
'http://localhost:8000/login',
{ password: 'password', username: 'admin' },
{ headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }
);