Store MSAL logged-in users and precheck them before doing a request on node.js web app

In my node project I have the following basic code to connect to Azure via a token. The login/logout works great together with our Azure:

const express = require("express");
const msal = require('@azure/msal-node');
const SERVER_PORT = process.env.PORT || 3000;
const config = {
    auth: {
        clientId: "XXX",
        authority: "https://login.microsoftonline.com/common",
        clientSecret: "XXX"
    },
    system: {
        loggerOptions: {
            loggerCallback(loglevel, message, containsPii) {
                console.log(message);
            },
            piiLoggingEnabled: false,
            logLevel: msal.LogLevel.Verbose,
        }
    }
};
const pca = new msal.ConfidentialClientApplication(config);
const app = express();

app.get('/', (req, res) => {
    res.send("<a href=\"login\">Login</a> <a href=\"logout\">Logout</a>");
});
app.get('/dashboard', (req, res) => {
    // check here for valid token...
});
app.get('/login', (req, res) => {
    const authCodeUrlParameters = {
        scopes: ["user.read"],
        redirectUri: "http://localhost:3000/redirect",
    };
    pca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
        res.redirect(response);
    }).catch((error) => console.log(JSON.stringify(error)));
});
app.get('/logout', (req, res) => {
    res.redirect('https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=http://localhost:3000/');
});
app.get('/redirect', (req, res) => {
    const tokenRequest = {
        code: req.query.code,
        scopes: ["user.read"],
        redirectUri: "http://localhost:3000/redirect",
    };
    pca.acquireTokenByCode(tokenRequest).then((response) => {
        console.log("\nResponse: \n:", response);
        res.sendStatus(200);
    }).catch((error) => {
        console.log(error);
        res.status(500).send(error);
    }); 
});
app.listen(SERVER_PORT, () => console.log(`Msal Node Auth Code Sample app listening on port ${SERVER_PORT}!`))

But how to properly check after that logging in if the token is still valid?

So the question is, how can I be save that the user on /dashboard has still a valid token or is logged in?

app.get('/dashboard', (req, res) => {
    // check here for valid token...
});

At the end I need a node.js application that:

  • is safe (token-based)
  • has user auth (msal)
  • can give granular permissions on routes

Can I do all that in node.js or better doing that in client-side? But am I then reducing the security?

4 thoughts on “Store MSAL logged-in users and precheck them before doing a request on node.js web app”

Leave a Comment