Access Denied: Origin Issue with OAuth2

I am requesting an authorization code from the OAuth2 Server in order to authenticate a user with my Microsoft App. For more information, I consulted this document.

This is my attempt to make the call:

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();
    }

However, I encountered the following error:

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

To try and resolve the issue, I added

req.setRequestHeader("Access-Control-Allow-Origin", "*");

Despite this modification, I still received the following error:

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

Answer №1

To seamlessly integrate AAD into your JavaScript application, we highly recommend utilizing the azure-activedirectory-library-for-js. This JavaScript library simplifies the frontend integration of AAD.

Before implementing ADAL for JS, it is crucial to consider two key options:

  • As indicated in the node at https://github.com/OfficeDev/O365-jQuery-CORS#step-6--run-the-sample:

    Please note that this sample may not function properly in Internet Explorer. It is recommended to use an alternative browser like Google Chrome. ADAL.js utilizes an iframe for obtaining CORS API tokens for resources beyond the SPA's backend. These iframe requests necessitate access to the browser's cookies for Azure Active Directory authentication. Unfortunately, Internet Explorer cannot access cookies when the application is running locally.

  • Ensure the oauth2AllowImplicitFlow setting is enabled for your Azure AD application. Detailed steps can be found at .

Below is a code snippet demonstrating how to obtain an access token from Microsoft Graph:

<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>

Answer №2

Through my own innovation, I devised a solution without relying on any frontend Google libraries.

window.open("url") 

Upon successfully completing the authentication process, I extract the code from the URL parameters, send it to the backend, and obtain the

access token, refresh token.......etc,
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating the date with setState in Material UI components

I have a question about integrating the material ui datepicker into my project. I want the current date in the state to update whenever the user switches from one date to another. You can find the materialUi datepicker I am using at this link. I tried im ...

The largest contentful paint is anticipating an unidentified event

My website is encountering issues with Google Pagespeed and I'm unsure of the cause. The primary bottleneck appears to be the LCP time, which Google reports as taking between 7 and 11 seconds during each test. Upon analyzing the waterfall chart, it ...

Incorporating HTML themes within ReactJS

While I am still relatively new to ReactJS, I am eager to expand my understanding of it with this question. I have a preexisting HTML/CSS theme that I would like to integrate into a React application. Is there a method to incorporate this theme seamlessly ...

Ways to determine the length of a string that includes zero or negative width characters such as u0007 or 

Consider the following scenario: I have a string 'aa\b\u0007\u0007' var myString = 'aa\b\u0007\u0007'; console.log(myString); //=> 'a' (plus 2 beeps) console.log(myString.length); //=> 5 ...

Problems encountered with an API for newsletter signups

The form I created allows users to input their email and sends it to my Sendgrid contacts list. However, there are a couple of issues that need addressing: After submission, the page gets stuck on loading The frontend logic is not functioning as desi ...

ReactJS: What is the best way to rearrange elements within an array stored in an object's property?

I am attempting to swap the positions of two elements within an array, which is nested inside an object as a property. However, when I click on the second "^" button in my CodeSandbox example below, I encounter the error message TypeError: arr.container.ma ...

"Encountering a 'Cannot GET' error message while utilizing Rest API in Node.js

Currently, I am developing a project using nodejs along with the expressjs framework. My focus right now is on setting up and running a "Rest Api," but I seem to be encountering an error message that reads: Cannot GET /published Let me share my routes fil ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

What is the best way to create a compound query in Firebase?

I am working on a TypeScript script to search for a city based on its population... import { getFirebase } from "react-redux-firebase"; ... get fb() { return getFirebase(); } get fs() { return this.fb.firestore(); } getCollection(coll ...

What is the way to execute a function *once* all my ajax call functions have finished?

I am utilizing jQuery to execute some ajax requests: var information = {}; function process_information(item){ information[item.id] = item; } function perform(){ var calls = []; for(var i = 0; i < 10; i++){ var call = $.get(URL, ...

Managing iframes in React using reference methods

Trying to set the content of an iframe within a React component can be a bit tricky. There is a component that contains a handleStatementPrint function which needs to be called when the iframe finishes loading. The goal is to print the loaded iframe conten ...

Is it advisable to use type="text/plain" for JavaScript?

I recently came across instructions on how to implement a particular feature out of curiosity. I found it interesting but was puzzled when they mentioned that in order for it to function properly, certain steps needed to be followed: You must identify any ...

The skybox in Three.js appears to be malfunctioning following a camera rotation

Working with JavaScript, I am attempting to build a basic skybox inspired by this demo. Everything is going smoothly except for one issue - when I rotate the camera (using orbitControls.js) and the z value is not at its minimum, the textures start to glitc ...

The development chrome extension failed to load due to an invalid port or malformed URL pattern

I'm encountering an issue while trying to load my development chrome extension for debugging. The error message I am receiving is: Issue with 'content_scripts[0].matches[0]' value: Path cannot be empty. Manifest failed to load. This is th ...

Setting up dynamic routing in AngularJS for links

I am facing some confusion regarding routing in AngularJS. Normally, we can configure routes in angular.config() when the angular module is loaded. At that time, we define static information such as routePath, templateUrl, and controller. However, I am u ...

What is the best way to ensure that my transitionend event is triggered?

I'm currently exploring the <progress> element and attempting to incorporate a CSS transition to achieve a smooth progress bar effect as its value increases. Despite my efforts, I can't seem to trigger JS after the transitionend event occur ...

The conflict between Material UI's CSSBaseline and react-mentions is causing issues

Wondering why the CSSBaseline of Material UI is causing issues with the background color alignment of React-mentions and seeking a solution (https://www.npmjs.com/package/react-mentions) Check out this setup: https://codesandbox.io/s/frosty-wildflower-21w ...

After attempting to install @mui/system, I encountered an error. I decided to uninstall it, but now I am consistently facing this

ERROR in ./node_modules/@mui/material/Unstable_Grid2/Grid2.js 6:14-25 export 'createGrid' (imported as 'createGrid2') was not found in '@mui/system/Unstable_Grid' (module has no exports). Encountering an issue after installin ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Discover the method for populating Select2 dropdown with AJAX-loaded results

I have a basic select2 box that displays a dropdown menu. Now, I am looking for the most effective method to refresh the dropdown menu every time the select menu is opened by using the results of an AJAX call. The ajax call will yield: <option value=1 ...