2016-11-11 70 views
1

I請求OAuth2服務器的authorization code。 我的目的是授權用戶與我的微軟應用程序。 Refered DocumentOAuth2訪問原始錯誤

我對GET呼叫嘗試:

function httpGet(){ 
     var theUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id="client_id"&response_type=code&redirect_uri="redirect_uri"&response_mode=query&resource=https%3A%2F%2Fservice.contoso.com%2F&state=12345"; 

     var req = new XMLHttpRequest(); 
     req.open('GET', theUrl, true); 
     req.onreadystatechange = function() { 
      if (req.readyState === 4) { 
       if (req.status >= 200 && req.status < 400) { 
        console.log(req.responseText) 
       } else { 
        console.log("error") 
       } 
      } 
     }; 
     req.send(); 
    } 

但是這給下面的錯誤:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

然後我加入req.setRequestHeader("Access-Control-Allow-Origin", "*");

,但它提供了以下錯誤:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

+0

你需要在服務器上配置這一點,而不是角應用 – jonrsharpe

+0

@jonrsharpe什麼你的意思「做你需要在服務器上配置它「? –

+0

我的意思是你提出請求的服務器。儘管這似乎超出了你的控制範圍。 – jonrsharpe

回答

0

不使用我想出瞭解決方案的任何frontend谷歌庫。

window.open("url") 

完成認證後,我得到了codeurl params並將其發送backend和實現access token, refersh token.......etc,

1

要在JavaScript中集成AAD,我們建議您使用azure-activedirectory-library-for-js這是一個JavaScript前端的庫,用於輕鬆集成AAD。

有2個選項,我們需要注意的,我們使用ADAL的JS面前:

下面是代碼示例從微軟收購圖形訪問令牌:

<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.10/js/adal.min.js"></script> 

<body> 
<a href="#" onclick="login();">login</a> 
<a href="#" onclick="getToken()">access token</a> 
</body> 
<script type="text/javascript"> 
    var configOptions = { 
     tenant: "<tenant_id>", // Optional by default, it sends common 
     clientId: "<client_id>", 
     postLogoutRedirectUri: window.location.origin, 
    } 
    window.authContext = new AuthenticationContext(configOptions); 

    var isCallback = authContext.isCallback(window.location.hash); 
    authContext.handleWindowCallback(); 

    function getToken(){ 
     authContext.acquireToken("https://graph.microsoft.com",function(error, token){ 
      console.log(error); 
      console.log(token); 
     }) 
    } 
    function login(){ 
     authContext.login(); 
    } 
</script>