简体   繁体   English

passport-azure-ad:使用哪种策略

[英]passport-azure-ad: which strategy to use

We have front end developed in AngularJS and backend APIs in NodeJs.我们在 AngularJS 中开发了前端,在 NodeJs 中开发了后端 API。 We are using Azure AD for authentication.我们使用 Azure AD 进行身份验证。 Frontend Angular is usingadal-angular javascript library for azure authentication.前端 Angular 使用adal-angular javascript 库进行 azure 身份验证。 So when user comes to web site, he gets redirected to https://login.microsoftonline.com and upon successful authentication he gets redirected back to our web site.因此,当用户访问网站时,他会被重定向到https://login.microsoftonline.com,并且在成功进行身份验证后,他会被重定向回我们的网站。 So far so good.到目前为止一切顺利。
I have to protect backend api's using passport-azure-ad library.我必须使用passport-azure-ad库来保护后端api。 Only the frontend is calling these APIs.只有前端调用这些 API。 There are two strategies available using this library使用此库有两种策略可用
1> OAuth2Bearer strategy 1> OAuth2Bearer 策略
2> OIDCStrategy for Open ID Connect 2> Open ID Connect 的 OIDC 策略

I was under impression Azure AD by default uses OpenID Connect for authentication.我的印象是 Azure AD 默认使用 OpenID Connect 进行身份验证。 So I was planning to use OIDCStrategy to protect Node web api as discussed here所以我计划使用 OIDCStrategy 来保护 Node web api,正如这里讨论的
However in fiddler I see the following request client (ie angular frontend) is making when it invokes web API但是,在 fiddler 中,我看到以下请求客户端(即角度前端)在调用 Web API 时正在发出

GET http://localhost:4030/api/getemployees HTTP/1.1  
Host: localhost:4030  
Connection: keep-alive  
Accept: application/json, text/plain, */*  
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36  
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi………………………  
Referer: http://localhost:4030/  
Accept-Encoding: gzip, deflate, sdch  
Accept-Language: en-US,en;q=0.8  

Note Authorization tag starts with “Bearer“ so I am assuming client is sending Bearer token to the server.注意 授权标签以“Bearer”开头,所以我假设客户端正在向服务器发送 Bearer 令牌。

Q
1>which strategy I should be using here? 1>我应该在这里使用哪种策略?
2>when should we use one over the other? 2>我们什么时候应该使用一个?

I maintain passport-azure-ad .我维护passport-azure-ad The difference here is between "authorization" and "authentication".这里的区别在于“授权”和“认证”之间。

OAuth2 is used for authorization (do I have access to this?). OAuth2用于授权(我可以访问吗?)。

OpenID Connect is used for authentication (this is who I am). OpenID Connect用于身份验证(这就是我)。

When you are connecting to web APIs, the user most likely already has an identity (they've been through authentication ) and now you just want to ensure that the user has access to the APIs ( authorization ).当您连接到 Web API 时,用户很可能已经拥有身份(他们已经通过身份验证),现在您只想确保用户可以访问 API(授权)。 OAuth2 is used to protect resources and consumes tokens from an IdP to ensure tokens are valid and that the user has access to that resource. OAuth2 用于保护资源并使用来自 IdP 的令牌以确保令牌有效并且用户有权访问该资源。 Bearer is just the type of token that we (and the industry) use for OAuth2. Bearer 只是我们(和行业)用于 OAuth2 的令牌类型。 If someone comes to you without a token at all, you reject them and then it's up to the client that called you to know where to take them to get the right token you need.如果有人在没有令牌的情况下来找你,你会拒绝他们,然后由打电话给你的客户知道如何带他们去获取你需要的正确令牌。

OpenID Connect is built on top of OAuth2 and is purely for logging people in and getting the tokens that you will then eventually send to a Web API (which would in turn use OAuth2 with Bearer token). OpenID Connect 建立在 OAuth2 之上,纯粹是为了让人们登录并获取令牌,然后您将最终将这些令牌发送到 Web API(进而将 OAuth2 与不记名令牌一起使用)。 So OpenID Connect is used for authentication .所以 OpenID Connect 用于身份验证

In your scenario you are using Angular which is doing the OpenID Connect authentication for you, so your Web APIs should be using The Bearer strategy.在您的场景中,您使用的是为您执行 OpenID Connect 身份验证的 Angular,因此您的 Web API 应该使用承载策略。

I have written a sample that walks you through all of this here: https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-webapi-nodejs/ that uses the MEAN stack, and which uses an iOS sample application I wrote as a front end.我在此处编写了一个示例,引导您完成所有这些: https ://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-webapi-nodejs/ 使用 MEAN 堆栈,其中使用我编写的 iOS 示例应用程序作为前端。 Playing with both of these, it's easy to see how one acts as the authentication piece (iOS app) and the other sits there and protects the API acting as the authorization piece (the node.js app)使用这两者,很容易看出一个是如何充当身份验证部分(iOS 应用程序),另一个是如何保护作为授权部分(node.js 应用程序)的 API

Code for node.js app: https://github.com/Azure-Samples/active-directory-node-webapi node.js 应用程序代码: https : //github.com/Azure-Samples/active-directory-node-webapi

Code for iOS app: https://github.com/Azure-Samples/active-directory-ios iOS 应用程序代码: https : //github.com/Azure-Samples/active-directory-ios

Deeper dive in to these topics is here: https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/更深入地了解这些主题: https : //azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/

Let me know if you have any other questions!如果您有任何其他问题,请告诉我!

You can use the following. 您可以使用以下内容。 I have recently implemented one with my react application with nodejs backend 我最近在我的带有nodejs后端的react应用程序中实现了一个

You can find the key values for BearerStrategyOptions at https://github.com/AzureADQuickStarts/AppModelv2-WebAPI-nodejs/blob/master/node-server/config.js 您可以在以下网址找到BearerStrategyOptions的键值https://github.com/AzureADQuickStarts/AppModelv2-WebAPI-nodejs/blob/master/node-server/config.js

Allow FYI I used the following common endpoint ' https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration for identityMetadata 允许仅供参考,我使用了以下通用端点' IdentityMetadatahttps://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration

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

You can find the key values for OIDCStrategyOptions at https://github.com/AzureADQuickStarts/AppModelv2-WebApp-OpenIDConnect-nodejs/blob/master/config.js 你可以找到OIDCStrategyOptions键值https://github.com/AzureADQuickStarts/AppModelv2-WebApp-OpenIDConnect-nodejs/blob/master/config.js

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

For Authentication: 对于身份验证:

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

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 并授权路由使用下面的代码在您的API

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

Done! 做完了! Hope this helps :) for someone looking to use passport-azure-ad 希望这有助于:)有人希望使用passport-azure-ad

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM