Cross-Origin Request Blocked, Javascript frontend integration

Pablo Garcia 0 Reputation points
2024-02-23T22:45:07.52+00:00

Hey everyone, I'm working in a integration between onedrive documents and a service in Javascript. What I want to do is to use the URL in '@microsoft.graph.downloadUrl' field of a file and use it to get the response.blob of the petition. When I try to consume the url the response is the title error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ... (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401. Is there a permission that the administrator of my organization needs change/set in order to gain this access-control-allow-origin header?

Microsoft 365 and Office | OneDrive | For business | Windows
Microsoft Security | Microsoft Graph
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Deepanshu Sharma 500 Reputation points Microsoft External Staff
    2024-02-25T18:50:25.9266667+00:00

    Hi Pablo Garcia

    The Same Origin Policy restricts web pages from making requests to a different domain than the one that served the web page. This policy is enforced by web browsers to prevent security vulnerabilities. When you try to download a file from OneDrive using the @microsoft.graph.downloadUrl, it involves a 302 redirect. Unfortunately, CORS preflight checks fail for such redirects, especially when providing the Authorization header. OneDrive’s API documentation suggests an alternative approach: instead of using the /content API, select the @content.downloadUrl property directly. This URL points to the same location that /content would have redirected to.

    This is how you can handle It:

    • To retrieve the download URL for a file, make a request that includes the @microsoft.graph.downloadUrl property:
    GET /drive/items/{item-id}?select=id,@microsoft.graph.downloadUrl
    
    • Use the obtained URL directly with XMLHttpRequest or other methods to download the file content.
    • Remember that this approach avoids the 302 redirect and bypasses the CORS issue.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.