0
votes

Calling the API through fetch() in React but getting CORS error. https://login.microsoftonline.com/tenant_id/oauth2/v2.0/authorize?client_id=xxxxxxxxxxxxxxxxxxxxx&response_type=code&redirect_uri=http://localhost:3050&scope=user.Read.All&response_mode=query

Above URL has been made from Postman and working fine if pasted directly on the browser.

2.Is there a way to get code securely i.e get the response code in body and not in query? enter image description here

Tried passing header in the fetch for Allow-access-origin to *.

1
Please be descriptive while posting the question, can you provide the screenshot of request from Network Tab of browser. That would help alot to find the solution.Pranil Tunga
Added screenshot. Thanks FYI, tried ammended headers requestHeaders.set('Content-Type', 'application/json; charset=utf-8'); requestHeaders.set('mode',"no-cors") requestHeaders.set('referrerPolicy','no-referrer'); // requestHeaders.set('Access-Control-Allow-Origin','localhost:3050*') requestHeaders.set('Accept','/*')Sanjeev_gupta2812

1 Answers

2
votes

We need to use msal in react to avoid CORS problems. Microsoft also provides some samples for react application, you can see this document. Here I tested this sample code. I also registered an azure ad application and set the redirect url http://locahost:3000, And here's my configuration:

enter image description here enter image description here

And as you can see in the App.jsx, it uses the code below to generate access token and call graph api with it, it's no need to show auth code in the browser because the token is acquired silently. I think this could meet your requirement.

function RequestProfileData() {
        // Silently acquires an access token which is then attached to a request for MS Graph data
        instance.acquireTokenSilent({
            ...loginRequest,
            account: accounts[0]
        }).then((response) => {
            callMsGraph(response.accessToken).then(response => setGraphData(response));
        });
    }

========================UPDATE==================

For your question 2, I think this may help you:

enter image description here