首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Azure、ReactJS和NodeJS认证用户并使用图形API

使用Azure、ReactJS和NodeJS认证用户并使用图形API
EN

Stack Overflow用户
提问于 2016-11-28 00:58:00
回答 1查看 3.7K关注 0票数 5

我有一个使用NodeJS + ReactJS创建的项目应用程序,我只想使用Azure对用户进行身份验证,并使用Azure的图形API获取用户的姓名、组、图片、职业等数据。

我已经在Azure门户上正确地配置了Azure广告和应用程序。包括权限、授权和所有这些工作人员。

我试着去理解怎样做才是最好的方法,但没有成功。我一直在谷歌,StackOverflow,微软的文档,甚至项目样本上寻找。

有些示例已经成功了,但是没有一个我能够理解并投入到我的项目中作为一个生产应用程序工作。

我使用它来验证用户,但是返回的AccessToken不能调用Graph:

代码语言:javascript
复制
passport.use(new OIDCStrategy({
    redirectUrl: config.creds.returnURL,
    realm: config.creds.realm,
    clientID: config.creds.clientID,
    clientSecret: config.creds.clientSecret,
    oidcIssuer: config.creds.issuer,
    identityMetadata: config.creds.identityMetadata,
    skipUserProfile: config.creds.skipUserProfile,
    responseType: config.creds.responseType,
    responseMode: config.creds.responseMode,
    allowHttpForRedirectUrl: config.creds.allowHttpForRedirectUrl
  },
  function(iss, sub, profile, accessToken, refreshToken, done) {
    console.log(accessToken);
    profile = profile._json;
    if (!profile.email) {
      return done(new Error("No email found"), null);
    }
    // asynchronous verification, for effect...
    process.nextTick(function () {
      findByEmail(profile.email, function(err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
          // "Auto-registration"
          users.push(profile);
          return done(null, profile);
        }
        return done(null, user);
      });
    });
  }
));

和这个AccessToken给了我使用图形API的权利,但是我不知道如何使用它而不是Passport:

代码语言:javascript
复制
function createAuthorizationUrl(state) {
  var authorizationUrl = templateAuthzUrl.replace('<client_id>', sampleParameters.clientId);
  authorizationUrl = authorizationUrl.replace('<redirect_uri>',redirectUri);
  authorizationUrl = authorizationUrl.replace('<state>', state);
  authorizationUrl = authorizationUrl.replace('<resource>', resource);
  return authorizationUrl;
}

// Clients get redirected here in order to create an OAuth authorize url and redirect them to AAD.
// There they will authenticate and give their consent to allow this app access to
// some resource they own.
app.get('/auth', function(req, res) {
  crypto.randomBytes(48, function(ex, buf) {
    var token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');

    res.cookie('authstate', token);
    var authorizationUrl = createAuthorizationUrl(token);

    res.redirect(authorizationUrl);
  });
});

// After consent is granted AAD redirects here.  The ADAL library is invoked via the
// AuthenticationContext and retrieves an access token that can be used to access the
// user owned resource.
app.get('/getAToken', function(req, res) {
  if (req.cookies.authstate !== req.query.state) {
    res.send('error: state does not match');
  }
  var authenticationContext = new AuthenticationContext(authorityUrl);
  authenticationContext.acquireTokenWithAuthorizationCode(req.query.code, redirectUri, resource, sampleParameters.clientId, sampleParameters.clientSecret, function(err, response) {
    var message = '';
    if (err) {
      message = 'error: ' + err.message + '\n';
    }
    message += 'response: ' + JSON.stringify(response);

    if (err) {
      res.send(message);
      return;
    }

    // Later, if the access token is expired it can be refreshed.
    authenticationContext.acquireTokenWithRefreshToken(response.refreshToken, sampleParameters.clientId, sampleParameters.clientSecret, resource, function(refreshErr, refreshResponse) {
      if (refreshErr) {
        message += 'refreshError: ' + refreshErr.message + '\n';
      }
      message += 'refreshResponse: ' + JSON.stringify(refreshResponse);

      res.send(message); 
    }); 
  });
});

如果有人能帮我做一些真正的应用程序样本,视频或其他什么,将是非常好的。我都快疯了想办法了。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-29 05:56:02

护照的OIDCStrategy遵循授权使用OpenID连接和Azure Active访问web应用程序对用户进行身份验证和授权。如果您需要访问资源,则仍然需要完成使用授权代码请求访问令牌的步骤。

我添加了一些基于openid连接示例的代码片段

返回路由函数将获得使用code获取访问令牌并保存到user seesion对象中的信息。

代码语言:javascript
复制
app.post('/auth/openid/return',
  passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
  function (req, res) {
    let option = {
      method:'POST',
      uri:'https://login.microsoftonline.com/<tenant_id>/oauth2/token',
      headers:{
        'Content-Type':'application/x-www-form-urlencoded'
      },
      form:{
        grant_type:'authorization_code',
        client_id:'<client_id>',
        resource:'https://graph.windows.net',
        client_secret:'<secret_key>',
        code:req.body.code,
        redirect_uri:'http://localhost:3000/auth/openid/return'
      }
    }
    console.log(option);
    request(option,function(err,res,body){
      req.user.access_token = JSON.parse(body).access_token;
    })

    // log.info('We received a return from AzureAD.');
    res.redirect('/');
  });

路由'/me‘是采样以使用访问令牌来要求资源。

代码语言:javascript
复制
app.get('/me',ensureAuthenticated ,function(req,response){
  request.get("https://graph.windows.net/<tenant_id>/me?api-version=1.5", {
    'headers': {
      'Authorization': "Bearer " + req.user.access_token,
      'Content-Type': 'application/json'
    }
  }, function(err, res, body){
    if(err){
      console.log("err: " + err);
    }
    else{
      console.log("res: " + res);
      response.send(res);
    }
  });
});

如有任何进一步的关注,请随时通知我。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40835723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档