Setting up CORS for Azure Active Directory

My goal is to programmatically obtain an access token from Azure Active Directory in an Angular 6 application using the method below.

    let body1 = new FormData()
    body1.append("resource", environment.config.clientId)
    body1.append("grant_type", "client_credentials")
    body1.append("client_id", environment.config.clientId)
    body1.append("client_secret", "*****")

    return this._http.post("https://login.microsoftonline.com/" + environment.config.tenant + "/oauth2/token", body1)

While I successfully obtained an access token through this method in Postman, I encountered CORS blockage when attempting the same in my application. The error message is as follows.

    Failed to load https://login.microsoftonline.com/*****/oauth2/token: 
Response to preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requested resource. Origin 
'http://localhost:4200' is therefore not allowed access.

I am seeking guidance on how to enable CORS on Azure Active Directory for all domains.

Answer №1

It's important to consider the security implications when obtaining tokens from your app.

By exposing your app's client secret, you risk it being captured by malicious actors since requests are made from the user's device.

Previously, the token endpoint did not support CORS due to this vulnerability, but it now does with proper configuration of a reply URL on the SPA platform, enabling Authorization Code flow with PKCE.

To securely acquire tokens from a front-end JS app, consider using Implicit Grant Flow or Authorization Code flow with PKCE. For app-only tokens, perform the request from a back-end application.

ADAL.JS/MSAL.JS can assist in obtaining tokens directly from the authorization endpoint, ensuring user identity validation in the process.

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

Is there a way to update a BehaviorSubject value without using the next method?

I am looking for a solution to update the value of my BehaviorSubject without causing any subscriptions to be triggered. I attempted the following: this.mySubject = new BehaviorSubject(newVal); Unfortunately, this approach also removes all existing subs ...

The 'ngModel' property cannot be bound to the 'input' element as it is not recognized. Error code: ngtsc(-998002)

When attempting to add [(ngModel)]="email" to my Angular app, I encountered the error message "can't bind to 'ngModel' since it isn't a known property of 'input'". Despite already including import { FormsModule } fro ...

The crosshair functionality in Zing Chart is causing a CPU leak

After enabling the crosshair feature on my chart, I noticed a significant issue when using Chrome 57 (and even with versions 58 and ZingChart 2.6.0). The CPU usage spikes above 25% when hovering over the chart to activate the crosshair. With two charts, th ...

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

When a custom header is added, cookies are not included in cross-origin jQuery AJAX requests

An issue arises when sending an ajax request from our main domain to a subdomain (cross-origin) through jQuery. Despite having CORS implemented and functional, we encounter a problem when attempting to include a custom header in the request. The presence o ...

I am puzzled as to why I keep receiving the error message "Cannot read property 'poPanel' of undefined"

CSS In my project, I am implementing a feature that displays an ordered list by looping through an array of objects and adding them on a button click. It works smoothly for adding items, but when I try to implement a remove function to delete each item, I ...

Is there a way to help my KafkaJS consumer stay patient while waiting for a broker to become available?

My KafkaJS consumer setup looks like this: // Create the kafka client const kafka = new Kafka({ clientId, brokers, }); // Create the consumer const consumer = this.kafka.consumer({ groupId, heartbeatInterval: 3000, sessionTimeout: 30000, }); // ...

The code within a for loop may not function properly when placed within the ngOnInt() function

I am struggling with running a for loop inside ngOnInit in Angular. I have a service that has a method getAllNews() which returns an array, not an observable. Since I can't use the subscribe() method, I want to iterate over this array. When I console ...

I have noticed that my unit test case does not include coverage for the if statement

Here is the function I have in my TypeScript file: routeToIndividualPortal(sessionToken: string) { let redirectUrl = this.relayState; console.log("Pre-source-check Indivual URL : " + redirectUrl); let url = ""; if(redirectUrl.includes(this. ...

Angular 2: Harnessing the power of Observables with multiple Events or Event Handlers

In the component template, I have grouped multiple Inputs and their events like this: <tr (input)="onSearchObjectChange($event)"> <th><input [(ngModel)]="searchObject.prop1"></th> <th><input [(ngModel)]="searchObje ...

pdfMake introduces a page breaking effect when the canvas is utilized with the type "line"

Can anyone shed some light on why a canvas declaration with the type "line" is causing a page break in the generated PDF? I've tried removing all canvases and the page break disappears, but I can't identify the root cause. Any insights would be ...

Encountering a bug in Typescript where a Prisma relation list field fails when provided with an argument

While attempting to initiate a new project using Prisma Client, I encountered an error when passing it with args, even when using an empty array list such as []. Here is the Prisma model: generator client { provider = "prisma-client-js" } dat ...

What is the way to retrieve an array property in a typescript interface?

Imagine a scenario with three interfaces structured as follows: registration-pivot.ts export interface RegistrationPivot { THead: RegistrationPivotRow; TBody: RegistrationPivotRow[]; } registration-pivot-row.ts export interface RegistrationPivotR ...

Tips for retrieving modified data from a smart table in Angular 4

Currently, I am working on an angular project where I am utilizing smart table. Here is a snippet of my .html file: <ng2-smart-table [settings]="settings" [source]="source" (editConfirm)="onSaveConfirm($event)" (deleteConfirm)="onDeleteConfirm($event ...

The router is unable to direct when an item is clicked

I am encountering an issue with my routing setup - when I click on an item in the list-item component, it does not successfully route to the detail-component. Here is a glimpse of my source code: product-list.component.html: <h1>Product List Compon ...

Post-Angular migration (going from version 12 to 14), there are still lingering security risks associated with the "d3-color vulnerable to ReDoS" issue

Following the migration to Angular 14, I made sure to update my "@swimlane/ngx-charts" version to "20.1.2" and the "d3" version to "7.8.4". However, even after running the npm install command, I am still encountering 5 high severity vulnerabilities in my p ...

Issue with clearing subscription upon navigating to another page is not functioning as expected

Currently, I am working on building a basic search screen to gain a better understanding of Angular subscriptions, which I have found to be quite perplexing. On my home page, I have set up two components - one for filtering and the other for displaying sea ...

Tips for incorporating conditional types into function parameters based on existing input

The title might be confusing, so allow me to clarify. My Objective I am referring to the code snippet below. I aim to specify the route property based on the types property as either a string or a function that returns a string. The Code Let's b ...

Utilize Angular6 and NodeJS to exhibit images stored on a server file system

Successfully uploaded images to a server but struggling to find a tutorial on how to display these images using Angular6 and NodeJS. Any help would be greatly appreciated. Thank you in advance. Edit: After many trials and errors, I was able to retrieve a ...

Using NodeJS to perform asynchronous tasks with setImmediate while also incorporating private class

Today marks my first time experimenting with setImmediate. I've come to realize that it may not be able to run private class methods. Can someone shed some light on this? Why is that the case? Not Functioning Properly When trying to use a private cl ...