Error Access to XMLHttpRequest at "http"rom origin has been blocked by CORS policy - Graph API -

Patrick Rote 101 Reputation points
2021-06-02T07:15:58.857+00:00

Hi All,
I would like to retrieve list of recent files from a particular document library or site for the logged on user

This is using a content editor on a sharepoint classic site

When i run the code below i get error

Access to XMLHttpRequest at 'https://login.microsoftonline.com//oauth2/v2.0/token/' from origin 'https://tenant.sharepoint.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Using the code below to get an access token and i get the error above

var token;  
$(document).ready(function () {  
    requestToken();  
});  

function requestToken() {  
    var clientId = ""
    var clientSecret = ""
    var tenantID = ""
    var uri = "https://login.microsoftonline.com/"+ tenantID + "/oauth2/v2.0/token"

    $.ajax({  
        "async": true,  
        "crossDomain": true,  
        "url": "https://login.microsoftonline.com/tenantName/oauth2/v2.0/token", // Pass your tenant 


        "method": "POST",  
        "headers": {  
            "content-type": "application/x-www-form-urlencoded"  
        },  
        "data": {  
            "grant_type": "client_credentials",  
            "client_id ": clientId, //Provide your app id      
            "client_secret": clientSecret, //Provide your secret      
            "scope ": "https://graph.microsoft.com/.default",
            "redirectUri" :  "https://tenantName.sharepoint.com"
        },  
        success: function (response) {  
            console.log(response);  
            token = response.access_token;  
            console.log(token);  

        },  
        error: function (error) {  
            console.log(JSON.stringify(error));  
        }  
    })  
}  

I have setup the app registrations and also added Redirect URIs for SPA and Web

Not sure what else I'm missing

Thanks in Advance

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,901 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,908 questions
{count} votes

Accepted answer
  1. MichaelHan-MSFT 18,016 Reputation points
    2021-06-03T07:50:13.267+00:00

    Hi @Patrick Rote ,

    I followed this post and could get the access token successfully,

    You need to change the url in AJAX call to: https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/tenant.onmicrosoft.com/oauth2/v2.0/token

    My demo code for you:

    $(document).ready(function () {  
            requestToken();  
          });  
          var token;  
          function requestToken() {  
            $.ajax({  
              async: true,  
              crossDomain: true,  
              url: "https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/tenant.onmicrosoft.com/oauth2/v2.0/token", //pass your tenant  
              method: "POST",  
              headers: {  
                "content-type": "application/x-www-form-urlencoded",  
              },  
              data: {  
                grant_type: "client_credentials",  
                "client_id ": "xxx", //Provide your app id  
                client_secret: "xxx", //Provide your client secret genereated from your app  
                "scope ": "https://graph.microsoft.com/.default",  
              },  
              success: function (response) {  
                console.log(response);  
                token = response.access_token;  
                console.log(token);  
              },  
              error: function (error) {  
                console.log(JSON.stringify(error));  
              },  
            });  
          }  
    

    Test result:

    101997-image.png


    If an Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Wirasak Chomphu 5 Reputation points
    2023-06-16T06:26:16.82+00:00

    Michael

    I'm now facing the same issue:
    It seem the request doesn't pass access control check, and it redirects to login again then gets the error. Can you please advise how I can fix it?

    app.module.ts

    MsalModule.forRoot( new PublicClientApplication({
        auth: {
            clientId: environment.appRegistry.clientId,
            authority: 'https://login.microsoftonline.com/' + environment.appRegistry.tenantId,
            redirectUri: environment.appRegistry.appUrl,
            
        },
        cache: {
          cacheLocation: BrowserCacheLocation.LocalStorage,
        }
      }), {
        interactionType: InteractionType.Redirect,
        authRequest: {
          scopes: ['https://xxx.azure.xx.com/user_impersonation']
         }
      }, {
        interactionType: InteractionType.Redirect, 
        protectedResourceMap: new Map([ 
            ['https://graph.microsoft.com/v1.0/me', ['user.read']],
            [environment.apiUrl,['https://xxx.azure.chevron.com/user_impersonation']],
            [environment.appRegistry.appUrl,['https://xxx.azure.xx.com/user_impersonation']],    
        ])
      })
    
    
    
    app.module.ts   
            
    GET https://login.windows.net/xxxx/oauth2/authorize?response_type=code+id_token&redirect_uri=https%3A%2F%2Fwso-python-dev.azure.chevron.com%2F.auth%2Flogin%2Faad%2Fcallback&client_id=27c70009-086b-4631-b32a-54dbcebc7775&scope=openid+profile+email&response_mode=form_post&resource=https%3A%2F%2Fgraph.microsoft.com&session_mode=token&domain_hint=chevron.com&nonce=6e37a3d3679b4ac8a84c5d4393606e6f_20230616062159&state=redir%3D%252Fapi%252FRunWSOJob%253FScenarioID%253D1133%2526JobType%253DUnconstraint%2526ProjectReserveType%253DDetMean%2526RequestedBy%253Dwcld%XXXXX net::ERR_FAILED
    
    1 person found this answer helpful.

  2. Patrick Rote 101 Reputation points
    2021-06-10T06:22:35.5+00:00

    Thanks and you are right it did the trick. Awesome.
    But now i have another quick question for you.

    I am trying to use this grap api endpoints

    var upn = "validemailaddress"

    I have registered an app registration and have a delegated permission to scope - Sites.Read.All ( this is according to the MSDN api documents insights-list-used)

    But i keep getting this error below - when i use - https://graph.microsoft.com/v1.0/me/insights/used

    104103-insightserror.png

    I'm acquiring a token by using

    url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.OAuth.Token/Acquire",

    Is there anything i'm missing as all the other endpoints work.
    My aim is to display recent files of logged in user on a sharepoint classic page

    Thanks in Advance