Angular2 with MSAL: Display in a frame denied due to 'X-Frame-Options' set to 'deny'

Hello, I am currently using the code below to log in using AAD B2C. It redirects to the login page and seems to be functioning properly, but when the user ID and password are correct, it redirects back to localhost:4200 without capturing the login details. Upon checking the console logs, I noticed the error message stating 'Refused to display in an iframe because it set 'X-Frame-Options' to 'deny' due to the iframe option. Can anyone offer assistance on how to resolve this issue?

import { Injectable } from '@angular/core';
import '../../../node_modules/msal/out/msal';
/// <reference path="../../../node_modules/msal/out/msal.d.ts"

@Injectable()
export class AuthService {
private applicationConfig: any = {
        clientID: 'df7cc9df-8073-4017-a108-85869852',
        authority: "https://login.microsoftonline.com/tfp/mylogintest.onmicrosoft.com//B2C_1_SiUpIn",
        b2cScopes: ["https://mylogintest.onmicrosoft.com/user.read"],
        webApi: 'http://localhost:4200',
    };

    private app: any;

    constructor() {
        this.app = new Msal.UserAgentApplication(this.applicationConfig.clientID, this.applicationConfig.authority, (errorDesc, token, error, tokenType) => {
            // callback for login redirect          
        });
    }
    public login() {
                return this.app.loginPopup(this.applicationConfig.b2cScopes).then(idToken => {
                this.app.acquireTokenSilent(this.applicationConfig.b2cScopes).then(accessToken => {
                   // updateUI();
                   console.log(this.app.getUser());
                }, error => {
                    this.app.acquireTokenPopup(this.applicationConfig.b2cScopes).then(accessToken => {
                        console.log(this.app.getUser());
                      //  updateUI();
                    }, error => {
                        console.log("Error acquiring the popup:\n" + error);
                    });
                })
            }, error => {
                console.log("Error during login:\n" + error);
            });
    }

    public logout() {
        this.app.logout();
    }
    public getToken() {
        return this.app.acquireTokenSilent(this.applicationConfig.graphScopes)
            .then(accessToken => {
                return accessToken;
            }, error => {
                return this.app.acquireTokenPopup(this.applicationConfig.graphScopes)
                    .then(accessToken => {
                        return accessToken;
                    }, err => {
                        console.error(err);
                    });
            });
    }
}

Answer №1

Encountered the same issue with my angular 5 app, which was caused by MSAL's usage of Iframes.

MSAL.js employs hidden iframes for acquiring and renewing tokens in the background. When Azure AD returns the token to the specified redirect_uri, typically the app's root page, the iframe loads the HTML content of the redirect_uri due to the 302 response, causing a reload.

The solution is detailed here: Solution

  • Use a different HTML for the iframe.
  • Conditionally initialize in the main app file.

The wiki provides guidance on achieving this.

Answer №2

After making some adjustments to the login function code, I am pleased to report that it is now functioning perfectly.

`public login() {
    return this.app.loginPopup(this.applicationConfig.graphScopes)
        .then(idToken => {
            const user = this.app.getUser();
            console.log(user);
            if (user) {
                console.log(user);
                return user;
            } else {
                return null;
            }
        }, () => {
            return null;
        });`

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

Determining the best application of guards vs middlewares in NestJs

In my pursuit to develop a NestJs application, I aim to implement a middleware that validates the token in the request object and an authentication guard that verifies the user within the token payload. Separating these components allows for a more organi ...

Improving Angular component performance with a multitude of subcomponents

Some time back, I created a grid component for an Angular application. Each Grid consists of rows represented by Row components, and each Row contains cells that are also components called Cell. These cells can hold various "objects" which are essentially ...

Tips for creating a unit test case in Angular 5 for API failures

Greetings! Currently, I am in the process of developing unit test cases for an Angular 5 application that involves utilizing APIs within the project. While I have successfully completed writing test cases for positive scenarios, I am facing challenges with ...

Using AngularJS to inject a service into a static property of a standard class

For my current project, I am combining TypeScript and AngularJS. One of the challenges I'm facing is how to instantiate a static member of a public class (not controller, just a normal class) with a service object. When it comes to controllers, utiliz ...

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

Chrome Driver Protractor Angular 2 encountering issue with unclickable element

My issue is with clicking the second level menu options to expand to the third level. I have tried using browser.driver.manage().window().setSize(1280, 1024) in the before all section. Here is my code snippet: it('Should trigger the expansion of the ...

Accessing Properties or Methods in Angular2 Components

My application consists of 3 main components: PageMenu, LoginSession, and LoginForm. The purpose is to establish a connection between the variables in LoginSession and PageMenu, allowing for the proper functionality of the LoginForm component. PageMenu: ...

Why is it necessary for the required type of a function parameter to be able to be assigned to

From Optional to Required Type const testFunc = (func: (param: number) => void): void => { func(3); }; testFunc((a?: number) => { console.log(a); }); From Required to Optional Type const testFunc = (func?: (param: number) => void): void = ...

The argument representing 'typeof Store' cannot be assigned to the parameter representing 'Store<AppState>'

I'm encountering an issue while trying to expand a service in Angular that utilizes ngrx. The error message I'm receiving is as follows: Argument of type 'typeof Store' is not assignable to parameter of type 'Store<AppState>& ...

Binding data with non-nested components

My dilemma involves two components - one with checkboxes and the other with a table. These components are not nested within each other. I want to manipulate certain classes in the table columns when a checkbox is unchecked. Can anyone suggest the most ef ...

Navigating with Angular Router: Strategies for managing routing within a submodule's router

Seeking guidance on handling a scenario where there is a router-outlet in a high-level component and another router-outlet within its sub-component. To resolve this issue, it appears necessary to place the sub-component in its own module and set up a dedi ...

Update the header background color of an AG-Grid when the grid is ready using TypeScript

Currently working with Angular 6. I have integrated ag-grid into a component and I am looking to modify the background color of the grid header using component CSS or through gridready columnapi/rowapi. I want to avoid inheriting and creating a custom He ...

How can dependencies for an entire class or module be mocked in the mocha ecosystem similar to jest.mock?

I am currently working on unit testing a module that resembles the following code structure: import { Countdown } from "./database/orm"; export class PersistentTimer { protected constructor(...) { ... } // To ensure database writing ...

Angular 9 TestBed RouterTestingModule: Exploring the router.url Readonly Property

While transitioning from Angular 8 to Angular 10 in stages, I encountered an issue when upgrading to version 9. All of my TestBed.get(Router).url calls started throwing errors because the property had become read-only. For instance, the code TestBed.get(R ...

Using Typescript and JSX to render a component that has been passed as an argument

I am seeking to create a function that will render a React component passed as an argument. I aim to accommodate both Component and StatelessComponent types with the following approach: function renderComponent(component: React.ComponentClass<any> | ...

options argument containing a keyof this

When defining a method type signature, it is possible to use keyof this to restrict an argument to the string name of a valid key of the class. However, using this approach does not work when the method accepts options-style arguments instead of positional ...

What is the best way to transfer the $event parameter from a dynamically generated function that requires the $event argument during a typical mouse click operation?

On an angular HTML template, I have a click handler that passes the $event argument to the handler function. My goal is to call this function programmatically on ngOnInit to initialize the component with default data as if the button had been clicked: Bel ...

Integrating additional JavaScript into an Ionic 2 project

Imagine we have a foo.js file containing a variable, function, and class that are not yet part of the project. Now suppose we want to access these elements in our home.ts method or make them globally available for use within a home.ts method. How can this ...

Issue with React TSX component in NextJs 14.0.4: Local MP3 files cannot be played, only external online MP3 files work

I have created a component that wraps around HTML audio and source tags. It functions perfectly when playing mp3 files from an external source, like this sound clip . However, it returns a GET 404 error when trying to access local mp3 files. Can anyone exp ...

Is it possible to invoke a component's function within the click function of a Chartjs chart?

How do I trigger a function in my Component from an onclick event in my chart.js? export class ReportesComponent implements OnInit { constructor(public _router: Router, private data: ReporteService) {} this.chart = new Chart('myChart', { ...