LP13
LP13

Reputation: 34109

How to authorize Node.js API with Azure AD?

We have application that is written using MEAN stack. Right now application is using home grown authentication. We are trying to replace it with Azure AD authentication.

There is nice article here that shows how to configure Angular for Azure Authentication using ADAL.JS library. This will protect client side resources. In the example the server side APIs are written using .Net Web API and OWIN is used to protect Web API. So OWIN is responsible for validating Bearer token send from the client.

With MEAN stack the server side API are written in Node.js, so how do we protect Node.js API if we switch to Azure AD? Is there any Node module available from Microsoft? Any Example will greatly appriciated.

Upvotes: 7

Views: 7221

Answers (4)

Dinesh Nadimpalli
Dinesh Nadimpalli

Reputation: 1491

I have recently implemented one with my react application with nodejs backend and with passport-azure-ad

You can refer to my post here for both authorization and authentication https://stackoverflow.com/a/58761942/8238968

You can find the key values for BearerStrategyOptions at https://github.com/AzureADQuickStarts/AppModelv2-WebAPI-nodejs/blob/master/node-server/config.js

Also, FYI I used the following common endpoint https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration for identityMetadata

const BearerStrategyOptions = {
  identityMetadata,
  clientID,
  validateIssuer,
  issuer,
  passReqToCallback,
  allowMultiAudiencesInToken,
  audience
};

For Authorization:

passport.use(
    new BearerStrategy(BearerStrategyOptions, function(token, done) {
      console.log("verifying the user");
      console.log(token, "was the token retreived");
      findByOid(token.oid, function(err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
          // "Auto-registration"
          console.log(
            "User was added automatically as they were new. Their oid is: ",
            token.oid
          );
          users.push(token);
          owner = token.oid;
          return done(null, token);
        }
        owner = token.oid;
        return done(null, user, token);
      });
    })
  );

And to authorize the routes use the following code in your api

 passport.authenticate('oauth-bearer', {session: false})

Done! Hope this helps :)

Upvotes: 4

Alex Zhang
Alex Zhang

Reputation: 1118

For authorize Node.js server with Azure AD, you can use the adal-node library in node.js.

Following Sample will demonstrate authentication Node.js with Azure AD, step by step:
https://code.msdn.microsoft.com/How-to-authorize-Nodejs-fdc580ed

Upvotes: 0

Gary Liu
Gary Liu

Reputation: 13918

This article configures the AAD tenant info in the angular scripts which will expose these info from clients, it increases risk of revealing sensitive info.

You can consider store all info and operate authentication and authorization flows at backend in Node.js applications. And only expose Apis for frontend angular clients.

You can refer to the sample provided by O365 at gitHub which leverages ADAL module. And the main authentication and authorization flows are written at https://github.com/OfficeDev/O365-Nodejs-Microsoft-Graph-Connect/blob/master/authHelper.js.

And the usage with access token in requests in Node.js you can refer to https://github.com/OfficeDev/O365-Nodejs-Microsoft-Graph-Connect/blob/master/requestUtil.js

update

I find the ADAL.js is designed follow the oauth2 authentication via response type of id_token. Which means it will only expose tenantId and AAD application clientId which are not so sensitive info. And the ADAL.js will store the access_token and several user info in html5 sesstionStorage. you can refer to http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/ and http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/ for more info.

About the ADAL.js usage, you can parse the access token via JWT in your backend app with your own logic, and you can refer to the sample at https://github.com/matvelloso/AADNodeJWT.

Meanwhile, in my opinion, you can separate your MEAN app into 2 independent Azure Web Apps. One to build your Angular App as the frontend, and other host your Expressjs Node.js App as the backend of our entire web app architecture.

In the backend Web App service, you can use Azure Active Directory as an authentication provider to protect your Web Apis. refer to https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-how-to-configure-active-directory-authentication/ for details.

And in the frontend Web App service, you can use adal.js and adal-angular.js in the Angular app for authentication and authorization.You can refer to the frontend part of https://github.com/matvelloso/AADNodeJWT.

When you successfully finish the authentication flow, the adal.js plugin will store the idtoken in html5 sesstionstorage, so we can leverage this token to request the backend app which is protected by AAD:

var token = sessionStorage.getItem('adal.idtoken');
$http.defaults.headers.common.Authorization= 'Bearer '+token;
$http.get('https://<your_backend_apis>').then(function (data){
      console.log(data);
})

Upvotes: 1

josh3736
josh3736

Reputation: 144912

Microsoft provides a passport plugin, passport-azure-ad.

passport-azure-ad is a collection of Passport Strategies to help you integrate with Azure Active Directory. It includes OpenID Connect, WS-Federation, and SAML-P authentication and authorization. These providers let you integrate your Node app with Microsoft Azure AD so you can use its many features, including web single sign-on (WebSSO), Endpoint Protection with OAuth, and JWT token issuance and validation.

Upvotes: 3

Related Questions