Search code examples
node.jsazureadal

How to verify a access token using adal-node authentication context?


I have created a azure web api using adal-node authentication context and a angularjs application, jwt token(access token) has been passed through the angularjs application in order to call the web API. I need to verify the user from jwt token before allowing the user to access the web API. How can I do this jwt verification using adal-node authentication context.

sample code for generating the access token

function getToken(TENANT) {
    var promise = new Promise(function (resolve, reject) {
        try {
            //const authContext = new adal.AuthenticationContext(`https://login.microsoftonline.com/${TENANT}`);
            const authContext = new adal.AuthenticationContext('https://login.microsoftonline.com/'+TENANT);
            authContext.acquireTokenWithClientCredentials(GRAPH_URL,CLIENT_ID,CLIENT_SECRET,function(err,tokenRes)
            {
                if (err)
                {
                    reject(err);
                }
                var accesstoken = tokenRes.accessToken;
                resolve(accesstoken);
            })
        }
        catch (ex) {
            reject(ex);
        };
    });
    return promise;
}

Solution

  • Actually, according to the document of adal-node:

    The ADAL for node.js library makes it easy for node.js applications to authenticate to AAD in order to access AAD protected web resources. It supports 3 authentication modes shown in the quickstart code below.

    So, in a word, adal-node doesn't have the functionality to verify JWT as an IDP server.

    However, if you want to prevent the people to access your web api who don't have permission. You can leverage the Authentication and Authorization feature of Azure App Service in a ease. You can use AAD to secure your Web API, and all the requests against to this Web API need to set the access token from AAD in their Authorization header.

    You can refer to Authentication and authorization for API Apps in Azure App Service for more info.

    Meanwhile, if you consist to verify JWT yourself, you can leverage some 3rd party module, e.g. https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback