Lutando Lutando - 23 days ago 7
Node.js Question

Use express-jwt as middleware to verify Azure AD issued tokens

I would like to know if its possible to use the

express-jwt
npm package as middleware to verify jwt tokens issued by Azure AD.

We have a web api written in express/node and would like to apply middleware pattern to protect our endpoints and to populate the user principle.

seems like:

server.use(jwt({
audience: '{UUID}',
issuer: 'https://sts.windows.net/{UUID}',
}).unless({path : ['/']}))


does not work as it requires a client secret, but from AD (much like in implicit flow) the tokens are retrieved via a user interaction and there is no client secret.

Answer

You can use "azure-ad-jwt". Its fairly straight forward and requires no injection into the middleware. You can inject it as an intermediary step in your own "middleware" function of course.

 private verifyToken(req: any, res: any) {
        var audience = "xxxxxxxxx";
        var tenantId = "xxxxxxxxx";

        var authorization = req.headers['authorization'];
        return Rx.Observable.create((observer) => {
            if (authorization) {
                var bearer = authorization.split(" ");
                var jwtToken = bearer[1];
                if (jwtToken) {
                    aad.verify(jwtToken, { audience: audience, tenantId: tenantId }, function (err, result) {
                        if (result) {
                            observer.next(true);
                        } else {
                            res.status(401).send('That is not a valid token!');
                        }
                    })
                } else {
                    res.status(401).send('No token in header.');
                }
            } else {
                res.status(401).send('Missing authorization attribute in header.');
            }
        });
    }