2017-09-16 86 views
0

我正在開發一個web項目(HTML,CSS,JavaScript,後端在PHP中)。我已經使用他們簡單的API成功地開展了Google Sign-in的工作,但無法讓Microsoft的功能發揮作用。官方在線解決方案似乎依賴於.NET或PHP Composer。我會嘗試作曲家,如果這是唯一的方法,但純JS/PHP方法將是最簡單的。 我試圖使用以下命令:如何創建Microsoft帳戶登錄到我的網站,類似於Google?

https://github.com/microsoftgraph/msgraph-sdk-javascript

https://github.com/AzureAD/microsoft-authentication-library-for-js

下面的代碼是我來工作的解決方案最接近。我可以得到某種用戶ID(這對每個用戶來說都是獨一無二的)。這可能足以建立我想要的登錄系統,但如果我也可以獲取他們的名字和個人資料圖片,這將是理想的。

 <script class="pre"> 
       var userAgentApplication = new Msal.UserAgentApplication("MY CLIENT ID", null, function (errorDes, token, error, tokenType) { 
         // this callback is called after loginRedirect OR acquireTokenRedirect (not used for loginPopup/aquireTokenPopup) 
        }) 
        userAgentApplication.loginPopup(["user.read"]).then(function (token) { 
         var user = userAgentApplication.getUser(); //this is good 
         //user.userIdentifier seems to be a unique ID 
         //I will store this and use it for future verification 
         console.log(user); 

         //START 

         // get an access token 
         userAgentApplication.acquireTokenSilent(["user.read"]).then(function (token) { 
          console.log("ATS promise resolved"); 
         }, function (error) { 
          console.log(error); 
          // interaction required 
          if (error.indexOf("interaction_required") != -1) { 
           userAgentApplication.acquireTokenPopup(["user.read"]).then(function (token) { 
            // success 
            console.log("s2"); 
           }, function (error) { 
            console.log("e2"); 
            // error 
           }); 
          } 
         }); 

         //END 

         // signin successful 
        }, function (error) { 
         console.log(error); 
         // handle error 
        }); 
</script> 

(因爲我已經粘貼此代碼將無法運行,因爲它依賴於從第二GitHub的鏈接MSAL腳本,需要應用程序客戶端ID)

回答

1

獲得訪問之後與範圍user.read令牌,你可以調用微軟圖形API來get sign-in user's profile information如顯示名,businessPhones:

https://graph.microsoft.com/v1.0/me 
Content-Type:application/json 
Authorization:Bearer {token} 

要獲得user's profile photo

GET https://graph.microsoft.com/v1.0/me/photo/$value 

另外,如果你在第一個鏈接使用Microsoft圖表JavaScript客戶端庫,您可以通過獲取用戶的顯示名稱和個人資料照片:

  client 
      .api('/me') 
      .select("displayName") 
      .get((err, res) => { 
       if (err) { 
        console.log(err); 
        return; 
       } 
       console.log(res); 
      }); 
     // Example of downloading the user's profile photo and displaying it in an img tag 
     client 
      .api('/me/photo/$value') 
      .responseType('blob') 
      .get((err, res, rawResponse) => { 
       if (err) throw err; 
       const url = window.URL; 
       const blobUrl = url.createObjectURL(rawResponse.xhr.response); 
       document.getElementById("profileImg").setAttribute("src", blobUrl); 
      }); 

請參考代碼示例here

相關問題