Issue encountered while trying to obtain user authorization_code from Microsoft Graph

I am encountering an issue with obtaining the Authorization code for the user.

After the user logs in, I extract the user code from the URL and then use Ajax to fetch the access_token. However, during this process, I encounter the following error :

AADSTS90023: Cross-origin token redemption is allowed only for the 'Single-Page Application'

Below is my code snippet :

const url = window.location.href;
    const code = url.slice((url.indexOf("=")+1), url.indexOf("&"));
    console.log(code)
    let form = new FormData();
    form.append("client_id", "48701536-c150-48f2-917b-730d855f316b");
    form.append("client_secret", "RzZ7Q~-GEYd6WayuMKmVXvH2w.Q7GjuaoHNEy");
    form.append("scope", "https://graph.microsoft.com/user.read");
    form.append("redirect_uri", "http://localhost:3000/Page1.html");
    form.append("grant_type", "authorization_code");
    form.append("code", `${code}`);
    
    $.ajax({
        url: "https://login.microsoftonline.com/consumers/oauth2/v2.0/token",
        method: 'POST',
        "timeout": 0,
        crossDomain: true,
        async: false,
        processData: false,
        mimeType: "multipart/form-data",
        contentType: false,
        data: form,
        success(response) {
            console.log(response)
        }, error(response){
            console.log(response)
        }
    })

Answer №1

Check out the msal.js package on this link

<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script src="js/msal.js"></script>
    </head>
    <body>
        <div style="font-size: 12px;">
            This example utilizes implicit grant flow to obtain an access token
        </div>
            <div style="margin-top: 15px; background-color: #DDDDDD;">
                <button type="button" id="signIn" onclick="signIn()">Sign In</button>
                <button type="button" id="getAccessToken" onclick="getAzureAccessToken()">getAccessToken</button>
                <button type="button" id="accessApi" onclick="accessApi()">getApiResponse</button>
                <h5 class="card-title" id="welcomeMessage">Please sign-in to see your profile and read your mails</h5>
            </div>
            <script type="text/javascript">
                const msalConfig = {
                    auth: {
                        clientId: "<applicationId>",
                        authority: "https://login.microsoftonline.com/<tenantId>",
                        redirectUri: "http://localhost:8848/Demo0819/new_file.html",
                    },
                    cache: {
                        cacheLocation: "sessionStorage", // This configures where your cache will be stored
                        storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
                    }
                };
        
                const loginRequest = {
                    scopes: ["openid", "profile", "User.Read"]
                };
                
                
                const myMSALObj = new Msal.UserAgentApplication(msalConfig);
        
                function signIn() {
                    myMSALObj.loginPopup(loginRequest)
                        .then(loginResponse => {
                            console.log("id_token acquired at: " + new Date().toString());
                            console.log(loginResponse);
        
                            if (myMSALObj.getAccount()) {
                                showWelcomeMessage(myMSALObj.getAccount());
                            }
                        }).catch(error => {
                            console.log(error);
                        });
                }
        
                function showWelcomeMessage(account) {
                    document.getElementById("welcomeMessage").innerHTML = `Welcome ${account.name}`;
                }
            </script>
    </body>
</html>

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

Utilizing nested v-for in Vue.js with lodash's groupBy function

When fetching data from a database, I am using lodash groupby to group my data like so: var vm = this axios.get(this.buildURL()) .then(function(response) { Vue.set(vm.$data, 'model', response.data.model) vm.groupData = _.groupBy(vm.model ...

Can file input buttons be custom styled?

Since I am using Material-UI, the traditional methods are not working for me. I have a form with two buttons positioned next to each other. One button is an "Upload File" input for users to upload a file, and the other is a submit button. I want both butto ...

Having trouble with the Angular router link suddenly "failing"?

app.routes.ts: import { environment } from './environment'; import { RouterModule } from "@angular/router"; import { ContactUsComponent } from './static/components/contact-us.component'; import { HomeComponent } ...

With Crypto-JS, a fresh hash is always generated

I'm looking to integrate crypto-js into my Angular 8 application. Here is a snippet of my code: import {Injectable} from '@angular/core'; import * as CryptoJS from 'crypto-js'; @Injectable() export class HprotoService { public ...

react-ga4 is sending multiple view events repeatedly

After setting up a Google Analytics account and creating a new property, I integrated the tracking ID with react-ga4 for my Album ItemPage as shown below: const ItemPage = () => { const {user} = useContext(AuthContext); let { item } = useParams ...

Having issues with the submit button functionality on Laravel Crud when employing Ajax and jQuery

I have been experiencing an issue with submitting the form after completing all the fields. Despite filling out the form and trying to submit it, I am not able to do so and there are no error messages appearing in the console or network tab either. Here i ...

Avoiding ChartJS tooltips from being cut off

I've been exploring how to prevent chartjs from cutting off its tooltips, but I haven't been able to find a config option to address this issue. https://i.sstatic.net/Knzvd.png Here's what I've attempted so far: <script> ...

Improper headings can prevent Chrome from continuously playing HTML5 audio

Recently, I encountered a peculiar and unlikely issue. I created a custom python server using SimpleHTTPServer, where I had to set my own headers. This server was used to serve .wav files, but I faced an unusual problem. While the files would play in an ...

Tips for reducing the size of your JavaScript buffer

Is it the correct way to convert a buffer to a string, trim it, and then convert back to a buffer in Node.js v6.12.x? var buf = Buffer.alloc(xxxxxx); ..... // buffer receives its value ..... let buffParsed = String.fromCharCode.apply(null, buf); buffPa ...

I encountered an issue with npm run build when attempting to launch a react application on Firebase, resulting in an error

npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\Myname\Desktop\god\package.json npm ERR! errno -4058 npm ERR! enoent ENOENT: file 'C:\Users\Myname\Desktop\god\package.json' not f ...

Unable to align span vertically using font-style "Luckiest Guy" in CSS

I have encountered an issue with vertically centering a span using the font-style "Luckiest Guy". https://i.sstatic.net/Lz8o3.png I attempted to use display: flex;align-items: center; on the span, but it did not work. App.vue <template> <div ...

Change classes of sibling elements using Angular 2

Imagine you have the following code snippet: <div id="parent"> <div class="child"> <div class="child"> <div class="child"> </div> I am looking to automatically assign the class active to the first child element. ...

Alter data in MongoDB based on specific circumstances

Currently, I am utilizing node.js and mongoose for a project. The task at hand involves updating database information only if the required field either does not exist in the database or its value is less than 'x'. Specifically, this pertains to ...

javascript: obtain the height of the pseudo :before element

Can someone help me figure out how to get the height of a pseudo :before element? I've tried using jQuery but it's not working as expected. Here's what I attempted: $('.test:before').height() // --> null If you want to take a ...

How can I save variable values to a text file or Excel file using Cypress.io?

Is there a way to write the values of a variable on a Text or Excel sheet? I have a variable called tex that stores string values, and I want to output these values onto text files or an Excel sheet if possible. beforeEach(() => { cy.visit('ht ...

Warning: data and salt parameters are necessary, please provide them

Issue: I am encountering an error with registering a new user, specifically when using Postman. I'm not sure why this error is occurring only in Postman. Additionally, I am facing proxy problems where requests cannot be proxied from localhost:3000 to ...

Why was the 'Symbol' type introduced in ECMA-262-v6 and what purpose does it serve?

Can you explain the purpose of the 'Symbol' type in ECMA-262-v6? Is it used for fast path implementation for object keys? How does it work internally - does it hash with the assurance that the underlying data remains unchanged? ...

How can I modify this section of the code in Google Script to retrieve all columns?

My question is, how can I modify this code to fetch all columns from the array instead of just [0,1,2,3] Here is the line of code in question: const new_table = [0,1,2,3].map(x => make_row_from_col(this_table, x)).join('\n'); Using obje ...

How can we enhance our proxyURL in Kendo UI with request parameters?

As outlined in the Kendo UI API documentation, when using pdf.proxyURL with kendo.ui.Grid, a request will be sent containing the following parameters: contentType: Specifies the MIME type of the file base64: Contains the base-64 encoded file content fil ...

How can I capture the 'ended' event from an HTML5 video tag using Ember in a controller?

I am having an issue with an hbs file that contains an html5 video tag: <video id="externalVideo" controls loop> <source src="../assets/videos/test.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> I am ...