I'm currently getting started with ExpressJS and came across a problem with implementing token auth. First of all, here's the code:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const jsonwebtoken = require('jsonwebtoken');
const config = require('./config');
const User = require('./models/user');
// Connect to mongoose
mongoose.connect(config.db, { useMongoClient: true });
const db = mongoose.connection;
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.send('Please use /api/ with an existing endpoint.');
});
const router = express.Router();
router.post('/auth', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err)
throw err;
if (!user) {
res.json({
success: false,
message: 'Authentication failed. User not found.'
});
} else {
if (user.password != req.body.password) {
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
});
} else {
const token = jsonwebtoken.sign(user, config.secret, { expiresIn: "20 seconds" });
res.json({
success: true,
message: 'Authentication succeeded. Enjoy your token.',
token: token
});
}
}
});
});
router.use(function(req, res, next) {
const token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jsonwebtoken.verify(token, config.secret, function(err, decoded) {
if (err) {
res.status(403).json({
success: false,
message: 'Failed to authenticate token.'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
res.status(403).json({
success: false,
message: 'No token provided.'
});
}
});
router.get('/', function(req, res) {
res.send('Please use /api/ with an existing endpoint.');
});
router.get('/users', function(req, res) {
User.getUsers(function(err, users) {
if (err)
throw err;
res.json(users);
});
});
router.get('/users/:_id', function(req, res) {
User.getUserById(req.params._id, function(err, user) {
if (err)
throw err;
res.json(user);
});
});
router.post('/users', function(req, res) {
var user = req.body;
User.addUser(user, function(err, user) {
if (err)
throw err;
res.json(user);
});
});
router.delete('/users/:_id', function(req, res) {
var id = req.params._id;
User.removeUser(id, function(err, user) {
if (err)
throw err;
res.json(user);
});
});
app.use('/api', router);
app.listen(3000);
console.log('Listening at 3000');
So I try to require a token before using any kind of /api/users/ path. I also have a path /auth/ where you can get your token through authentication. But when using that path (/api/auth/) I also get "No token provided". Of course I want to GET that token there. Of course I didn't provide a token, I have none yet :)
What am I doing wrong? Is it the wrong use of middlewares? Or anything else?
A Second question is if I actually even need to use the express router. I used it because I was following this guide: https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens