如何在Node.js App / API中从Azure AD发行令牌?

时间:2018-10-11 18:43:27

标签: node.js express azure-active-directory passport.js passport-azure-ad

我正在构建具有快速后端的节点应用程序。要求之一是使用Azure AD进行身份验证。我已经安装了passport-azure-ad模块,并将其设置如下:

import * as passportAD from "passport-azure-ad";
// ... <snip> ....
const tenantName = "<MY_TENANT_NAME>"";
const clientID = "<MY_CLIENT_ID>";

app.use(passport.initialize());
app.use(passport.session());
const bearerStrategy = new passportAD.BearerStrategy(
  {
    identityMetadata: `https://login.microsoftonline.com/${tenantName}.onmicrosoft.com/.well-known/openid-configuration`,
    clientID
  },
  (token: any, done: any) => {
    console.log(token);
    return done(null, {}, token);
  }
);
passport.use(bearerStrategy);

然后我将授权添加到了这样的路由:

const myHandler = () => (req, res) => return res.json({});
app.get('/my/route',
        passport.authenticate("oauth-bearer", { session: false }),
        myHandler()
);

这将按预期返回401状态,但是我无法找到有关如何从Azure AD向客户端发行令牌的文档。我想接受在主体中具有用户名和密码的登录端点的POST,并返回Azure AD令牌。这可能吗?

3 个答案:

答案 0 :(得分:2)

您还可以执行以下操作。我最近用nodejs后端的react应用程序实现了一个

您可以在https://github.com/AzureADQuickStarts/AppModelv2-WebAPI-nodejs/blob/master/node-server/config.js

中找到 BearerStrategyOptions 的键值

仅供参考,我将以下公共端点'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration用于 identityMetadata

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

您可以在https://github.com/AzureADQuickStarts/AppModelv2-WebApp-OpenIDConnect-nodejs/blob/master/config.js

找到 OIDCStrategyOptions 的键值
const OIDCStrategyOptions = {
  identityMetadata,
  clientID,
  responseType,
  responseMode,
  redirectUrl,
  allowHttpForRedirectUrl,
  clientSecret,
  validateIssuer,
  isB2C,
  issuer,
  passReqToCallback,
  scope,
  nonceLifetime,
  nonceMaxAmount,
  useCookieInsteadOfSession,
  cookieEncryptionKeys,
  clockSkew
};

用于身份验证:

 passport.use(
    new OIDCStrategy(OIDCStrategyOptions, function(
      iss,
      sub,
      profile,
      accessToken,
      refreshToken,
      done
    ) {
      if (!profile.oid) {
        return done(new Error("No oid found"), null);
      }
      // asynchronous verification, for effect...
      process.nextTick(function() {
        findByOid(profile.oid, function(err, user) {
          if (err) {
            return done(err);
          }
          if (!user) {
            // "Auto-registration"
            users.push(profile);
            // console.log("---------profile----------", profile)
            return done(null, profile);
          }
          // console.log("-----------user---------", user)
          return done(null, user);
        });
      });
    })
  );

用于授权:

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);
      });
    })
  );

要授权路线,请在您的api中使用以下代码

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

完成!希望对您有所帮助:)对于希望使用passport-azure-ad

的用户

答案 1 :(得分:0)

Azure AD令牌的唯一发行者是Azure AD。您应该在客户中收集用户名/密码,并且应在服务中接受它们。

您的客户端应用程序仅需要使用MSAL(或ADAL或任何OpenID Connect客户端库)将用户发送到Azure AD,让他们登录,并作为响应获得API的访问令牌。

例如,如果您的客户端是JavaScript单页应用程序,则可以使用MSAL for JavaScript执行以下操作:

var userAgentApplication = new Msal.UserAgentApplication(
    '0813e1d1-ad72-46a9-8665-399bba48c201', // AppId of you client app
    null, function (errorDes, token, error, tokenType, instance) {
        // This callback only used loginRedirect OR acquireTokenRedirect.
    }
);

var scopes = ["https://api.example.com/permission.scope"];
userAgentApplication.loginPopup(scopes).then(function (token) {

    // Get the signed-in user
    var user = userAgentApplication.getUser();

    // Get an access token for the signed-in user
    userAgentApplication.acquireTokenSilent(scopes).then(function (token) {

        // Use the access token to call your API
        $.ajax({
            url: 'https://api.example.com/foo',
            type: 'GET',
            dataType: 'json',
            headers: { 'Authorization': 'Bearer ' + token },
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                // TODO: Do something cool with the API response.
            },
            error: function (error) {
                // TODO: Do something smart if there's an error
            }
        });
    }, function (error) {
        // TODO: Silent token acquisition failed, retry with acquireTokenPopup()
    });
}, function (error) {
    // TODO: Deal with error.
});

(当然,您可以在其他各种平台上执行此操作。)

答案 2 :(得分:-1)

passport-azure-ad模块中,关于天蓝色广告如何发行令牌,您可以参考doc1doc2

  

我想使用用户名和密码接受到登录端点的POST   正文中输入密码并返回Azure AD令牌。这可能吗?

是的,有可能。如果您想这样做,可以参考here