2017-05-09 66 views
0

我是nodejs的新手,並且爲了好玩而進行概念驗證。如何在nodejs中實現這個?

背景: 我有一個用戶信息(如用戶名,密碼和其他信息)的雲目錄。這個雲目錄可以用來僅通過平靜的API來認證用戶(即不使用LDAP或JDBC等的直接連接)。

目標: 爲此雲目錄構建LDAP接口。首先我只對認證(LDAP綁定)感興趣。

指定流動

  1. 的ldapclient啓動一個標準的LDAP簡單綁定請求: 主機:主機在那裏我的NodeJS應用程序將運行 端口:1389(端口,我的NodeJS應用程序將被綁定到) 用戶名:來自雲目錄的用戶 密碼:用戶密碼

  2. 此請求由我的NodeJS應用程序(我正在使用ldapjs模塊)接收。

    // process ldap bind operation 
    myLdapServer.bind(searchBase, function (bindReq, bindRes, next) { 
        // bind creds 
        var userDn = req.dn.toString(); 
        var userPw = req.credentials; 
        console.log('bind DN: ' + req.dn.toString()); 
    ... 
    ... 
    } 
    
  3. 在上述回調,我必須使用http.request火寧靜API(POST),以與I從BIND請求接收到的詳細信息(即用戶名,密碼)雲目錄。

  4. 如果restful api的響應狀態是200(auth成功),那麼我必須返回成功到LDAPClient,否則我必須返回無效憑證錯誤。

成功:

bindRes.end(); 
    return next(); 

失敗:

Console.log("returning error"); 
    return next(new ldap.InvalidCredentialsError()); 

問題:

這可能使用的NodeJS?由於上面涉及的嵌套問題(在回調中調用REST API)。此外,由於這是一個認證操作,這意味着是一個阻塞操作

感謝, Jatin

UPDATE(?):

感謝Klvs,我的解決辦法是多還是少一樣,你發佈。請看看下面的代碼片段:

// do the POST call from within callback 
    var postRequest = https.request(postOptions, function(postResponse) { 
     console.log("statusCode: ", postResponse.statusCode); 
     if(postResponse.statusCode!=200) { 
      console.log("cloud authentication failed: "+postResponse.statusCode); 
      return next(ldapModule.InvalidCredentialsError()); 
     } else { 
      postResponse.on('data', function(d) { 
       console.info('POST result:\n'); 
       process.stdout.write(d); 
       console.info('\n\nPOST completed'); 
      }); 
      res.end(); 
      return next(); 
     } 
    }); 

    // write json data 
    postRequest.write(postData); 
    postRequest.end(); 
    postRequest.on('error', function(e) { 
     console.error("postRequest error occured: "+e); 
    }); 

成功認證工作正常,但是,失敗的認證不發送任何響應迴向ldapclient在所有。我的客戶端只是超時而不是顯示身份驗證失敗錯誤。我確實看到了「雲認證失敗:」節點控制檯,這意味着下面的語句日誌消息沒有做什麼,我想讓它做的事:

  return next(ldapModule.InvalidCredentialsError()); 

注意上面的語句的工作,當我刪除了REST調用等等,然後將錯誤返回給客戶端。

我錯過了什麼嗎?

感謝, Jatin

+0

更新,請參閱我對我的回答的評論。 – klvs

回答

0

當然,這是可能的的NodeJS。如果我明白你想向服務器發出一個認證請求,並讓它失敗或成功。

const request = require('request') 
// process ldap bind operation 
myLdapServer.bind(searchBase, function (bindReq, bindRes, next) { 
    // bind creds 
    var userDn = req.dn.toString(); 
    var userPw = req.credentials; 
    console.log('bind DN: ' + req.dn.toString()); 
    request.post({username: userDn, password: userPw}, (err, res, body)=>{ 
    if(err) { 
     console.log("returning error"); 
     next(new ldap.InvalidCredentialsError()); 
    } else { 
     bindRes.end(); 
     next(); 
    } 
    }) 
} 

這是你在找什麼?如果是這樣,你只需要習慣於回調。

+0

謝謝klvs,請你回顧我的問題更新? – Jatin

+0

我不確定你使用的是什麼框架,但我確實注意到,如果它沒有進行身份驗證,你沒有發送響應。如果成功,您可以調用'res.end()',但如果失敗則不會這樣做。通過不發送回覆,您可以在客戶端等待回覆時使其超時。 – klvs

+0

謝謝klvs,我的壞 不正確: return next(ldapModule.InvalidCredentialsError()); 正確: return next(new ldapModule.InvalidCredentialsError()); – Jatin