2017-09-16 139 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

相关问题