Office 365 graph api from javascript: how to authenticate correctly

I don't hate Oauth, but I hate myself for not being able to plunge into the concept. Having said that, here is my question: I am trying to call the Office Graph REST api from vanilla javascript. Therefore, I am doing the usual XMLHttpRequest on graph.microsoft.com, from the page that is running on my SharePoint Online site (so the code should be run from my security context since I logged in). Call returns 403 Authentication Required. I assume that I need to register the application in Azure AD, and I did, so I have a client ID and a secret. However, I can’t find what to do next programmatically (I think I understand the concept, I need to get the token that I have to provide when calling the Graph api). There seems to be tons of code for anything but javascript. Does anyone have pointers?

Update: I know the involvement of the token and that part that I can’t wrap my head on (see Original Question / Comment); I have a client ID, I have a secret, and I have this (VERY regular) code:

function graphRead(whatToRead) { switch(whatToRead) { case "userinfo" : officeUser = JSON.Parse(loadXMLDoc("GET","https://graph.microsoft.com/v1.0/me")); break; default: }; }; function loadXMLDoc(mMethod,uURL) { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE ) { if(xmlhttp.status == 200){ return(xmlhttp.responseText); } else if(xmlhttp.status == 400) { alert('There was an error 400') } else { alert('something else other than 200 was returned') } } }; xmlhttp.open(mMethod, uURL, true); xmlhttp.send(); }; 

Question: what do I need to do to set the token and send it to the API?

+5
source share
2 answers

If you do this on the client side in JavaScript, you probably want to implement what is called an "implicit permission" stream. Azure has a process entry: https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-protocols-implicit/ .

Basically, your page will either have a “login” link or it will automatically go to the Azure authorization page with all the parameters encoded in the URL, for example, your client ID and areas that you request on the chart. If necessary, the user will have to log in, but in your case they may not need to. After the user logs in with their credentials (again, if necessary), they will be asked to provide consent to access your application. Assuming they say yes, Azure will redirect back to your page using an access token in the request hash. You will need to have a JS code to retrieve the access token from the hash. For example, a redirect would look something like this:

 https://localhost/myapp/# access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q... &token_type=Bearer &expires_in=3599 &scope=https%3a%2f%2fgraph.microsoft.com%2fmail.read &id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q... &state=12345 

<strong> pseudo-steps

  • When loading the page, check if there is an access token in the URL fragment.
    • If so, it indicates a download after authorization redirection, and you can start calling Graph.
    • If not, you need to request the user or automatically redirect the authorization endpoint.
  • You need to pass the token in the Authorization http header when calling Graph. You can do this by adding the following line to your code (before send ): xmlhttp.setRequestHeader("Authorization", "Bearer " + token);

But why should I do this?

The answer is that OAuth works as an application, not as a user. Thus, the old model of authenticating the application as a user is not applied. The user must provide permissions to access his data.

So, really, what is happening here is not that the application should "log in again as a user", it should be auth as itself! This is really what you are doing (providing your client id). As part of this process, a user can log in to verify their identity, then provide consent.

Your client secret will not be used at all in an implicit stream. Essentially, your application will "prove" that it is truly on its own, using the client ID and being present on the URL that you register as part of registering your application.

+3
source

The ADAL.js library will make life a lot easier for all OAuth authentications against Azure AD, including what you are trying to do using the implicit OAuth consent from the js SharePoint unit.

  • Register the application in the Azure AD Applications section. Edit the manifest and activate implicit OAuth. Add " https://mytenant.sharepoint.com " to the list of application URLs.
  • Paste this JS code into the SharePoint Script editor web part to authorize the user, get the access token and call the Graph API:

 <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.10/js/adal.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <body> <div><a href="#" onclick="login();return false;">login</a> </div> <div><a href="#" onclick="getToken();return false;">get access token and user info</a> </div> </body> <script type="text/javascript"> var configOptions = { clientId: "insert Azure App ClientId here", postLogoutRedirectUri: window.location.origin, } var accessToken = null; 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); accessToken = token; getUsers(); }) } function login() { authContext.login(); } function getUsers() { $.ajax({ url: "https://graph.microsoft.com/v1.0/me", type: 'GET', headers: { "Authorization": "Bearer " + accessToken }, crossDomain: true, success: function(response) { console.log(response); alert(response.userPrincipalName); } }); } </script> 
+2
source

All Articles