Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 618
Lutando Avatar asked Nov 15 '16 07:11

Lutando


1 Answers

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.');
            }
        });
    }
like image 67
tensai Avatar answered Oct 24 '22 20:10

tensai