Create an authentication middleware in ExpressJS

Create an authentication middleware in ExpressJS

In ExpressJS we can create middleware to check if a user is authenticated.

In ExpressJS we can create middleware to check if a user is authenticated.

Assuming the use of express-session for the management of user sessions, what we have to do is check if it is present in the current session a property that indicates the successful authentication by the user.

Se questa proprietà non è presente o non possiede il valore atteso, possiamo reindirizzare l'utente alla pagina di login.

'use strict';

module.exports = (req, res, next) => {
    if (!req.session.isLoggedIn) {
        return res.redirect('/login');
    }
    next();
};

The middleware thus created can be used as an argument in the definition of our routes. To apply it to a specific route we can write:

'use strict';

const app = require('express')();
const auth = require('./middleware/auth');
const PORT = process.env.PORT || 3000;

app.get('/backend', auth, (req, res, next) => {
    //...
});

app.listen(PORT);

To apply it to a group of routes we can use it as the middleware of a Router object.

'use strict';

const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');

router.use(auth);

router.get('/', (req, res, next) => {
    //...
});
router.get('/files', (req, res, next) => {
    //...
});
router.get('/orders', (req, res, next) => {
    //...
});

module.exports = router;

At this point in the main file we define the mount point of our router within the app.

'use strict';

const app = require('express')();
const auth = require('./middleware/auth');
const PORT = process.env.PORT || 3000;
const adminRoutes = require('./routes/admin');

app.use('/backend', adminRoutes);

app.listen(PORT);

This way the /backend route and all its child routes will be protected by our authentication middleware.