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

Using (javascript:) within Href attributes

Recently, I've noticed some people including "javascript:" in the href attribute of an a tag. My question is: what is the purpose of this? Does it guarantee that clicking on the a tag directs the function of the click to JavaScript for handling, rathe ...

Tips for effectively parsing extensive nested JSON structures?

JSON Data on PasteBin I need assistance in converting this JSON data into an Object. It seems valid according to jsonlint, but I'm encountering issues with parsing it. Any help would be greatly appreciated. "Data":[{...},{...},] // structured like t ...

Access JSON value using jQuery by key

Creating a JSON structure that contains information about attendees: { "attendees": [ { "datum": "Tue, 11 Apr 2017 00:00:00 GMT", "name": " Muylaert-Geleir", "prename": "Alexander" }, { "datum": "Wed, 12 Apr 2017 ...

Watch mp4 clips in various languages with ExpressJs

I have a question regarding streaming videos within my local network. My mp4 files contain multiple audio tracks in different languages. Is there a way to select a specific audio track to stream? For instance, could you specify a language as a query parame ...

What is the best way to conceal a bootstrap directive tooltip in Vue.js for mobile users?

Currently, I'm tackling a project with Vuejs and Laravel. There's a tooltip directive incorporated that relies on Bootstrap's functionality. Check it out below: window.Vue.directive("tooltip", function(el, binding) { // console ...

The functionality of scope.$observe is unavailable within an AngularJS Directive

Consider the snippet below: appDirectives.directive('drFadeHighlight', ['$animate', '$timeout', function ($animate, $timeout) { return { scope: { isWatchObject: '=' }, restric ...

What is the best way to attach every sibling element to its adjacent sibling using jQuery?

I've been working with divs in Wordpress, where each div contains a ul element. <div class="list-item"> <div class="elimore_trim"> Lorem ipsum </div> <ul class="hyrra-forrad-size-list"> <li>Rent 1< ...

Convert JSON data into an HTML table using JavaScript without displaying the final result

I need help troubleshooting my JavaScript code that is supposed to populate an HTML table with data from a JSON file. However, the table remains empty and I can't figure out why. Sample JSON Data [{"User_Name":"John Doe","score":"10","team":"1"}, { ...

I am experiencing an issue with my d3 force directed graph where the links are not

I am relatively new to d3 and have limited experience with web frontend development. In my current web application project, I am attempting to create a force directed graph. Despite spending several hours trying to make it work, I have been unable to displ ...

Error message: "The jQuery function is unable to recognize the

I am working with a JSON object that looks like this: {"a":"111","b":"7"} In addition, I have a select box with options for "a" and "b". I want the selected value to display either "111" or "7" from the JSON object. Here is the jQuery code I wrote for t ...

What is the best way to cycle through a JSON array of objects using JavaScript and jQuery?

Currently, my focus is on understanding JavaScript and JSON objects along with arrays. One of the tasks assigned to me involves iterating through the following array: {"6784": {"OD": [ { "od_id":"587641", ...

Removing the element generated by Angular from the DOM

I've hit a roadblock with this issue. Here is the delete function in my mainController. $scope.delete = function($posts) { $http.delete('/api/posts/' + $posts._id) .success(function(data) { // remove element from DOM ...

Does running npm install automatically compile the library code as well?

I have a query regarding npm and its functionality. I also posted the same question on Reddit, but haven't received a satisfying answer yet. Let's use the jQuery npm package as a case study. Upon running the command npm install jquery, I notic ...

Custom Email Template for Inviting Msgraph Users

I'm currently exploring the possibility of creating an email template for the MS Graph API. I am inviting users to join my Azure platform, but the default email they receive is not very visually appealing. public async sendUserInvite(body: {email: < ...

Is incorporating re-routing into an action a beneficial approach?

My main concern involves action design strategies: determining the best timing and method for invoking actions. In my project using Mantra (utilizing React for the front-end and Meteor's FlowRouter for routing), there is a UI component that includes ...

In Laravel Blade, I am looking to display a Modal popup and dynamically pass data based on the user's ID

When a user clicks on the "View Details" Button, I need to display a popup modal with information specific to that user. The data for each user is stored in the $user variable. I would like to achieve the same functionality as demonstrated on this website ...

Encountered an issue while trying to send an email through the Gmail API: Unfortunately, this API does not provide

I am attempting to use the Gmail API to send emails. I collect user data and convert it to a base64url string. After obtaining the raw value, I attempt to send the email using a POST request. var ss=new Buffer(message).toString('base64') var ...

Steps for mocking an async action creator in Redux using Jest

I am currently working on writing a unit test for a redux async action creator using jest. asyncActions.js: const startSignInRequest = () => ({ type: START_SIGNIN_REQUEST }); // this is the action creator for successfully signing in a user export c ...

Guide the user to a specific website and replicate the user's action of pressing the down arrow or clicking a button three consecutive times

Currently, I am facing an issue with a WordPress slider that lacks anchors for linking to specific sections. I am wondering if there is a way to direct a user to a URL and simulate the action of pressing the down arrow or clicking a button multiple times ...

I encountered a parsing issue while trying to compile my Vue project

Issue: The component name "Header" should always consist of multiple words. Fix: Change the component name to a multi-word format according to Vue standards (vue/multi-word-component-names). ...