The issue with Cypress AzureAD login is that it consistently redirects users away from the intended Cypress window

Trying to incorporate the automation of Azure AD login using Cypress, I have been facing some challenges. Even after configuring the local session storage according to the instructions in this GitHub repository https://github.com/juunas11/AzureAdUiTestAutomation, the tests keep redirecting to the Microsoft authentication page and opening outside the Cypress window. Any assistance on resolving this issue would be highly appreciated as it has halted my progress with the automation. enter image description here

/// <reference types="cypress" />

import { decode, JwtPayload } from 'jsonwebtoken';
import authSettings from './authsettings.json';

// All necessary details stored in a separate file (authSettings.js)
const {
    authority,
    clientId,
    clientSecret,
    apiScopes,
    username,
    password,
    apiScopesEntity,
    targetScopes,
} = authSettings;

const environment = 'login.windows.net';

// Functions for building different token entities

const injectTokens = (tokenResponse) => {
    // Code for injecting tokens into local and session storage
};

export const login = () => {
    let tokenResponse = null;
    cy.request({
            url: authority + '/oauth2/v2.0/token',
            method: 'POST',
            body: {
                grant_type: 'password',
                client_id: clientId,
                client_secret: clientSecret,
                scope: apiScopes,
                username: username,
                password: password,
            },
            form: true,
        })
        .then((response) => {
            injectTokens(response.body);
            tokenResponse = response.body.access_token;
        })
        .reload()
        .then(() => {
            return tokenResponse;
        });
};

Answer №1

Upon experiencing a similar issue, I identified the root cause behind the redirection problem. The issue stems from discrepancies between the data stored in local storage and the expectations of the MSAL or login library used in the frontend. This misalignment leads to unwanted redirections.

Follow these steps to resolve the issue:

1- To prevent redirection and analyze the local storage values and console.logs, halt the visit to the Microsoft request by commenting out cy.visit("/") after making the request. Ensure you can view the decoded token response with console.log('idToken', idToken);

2- Take note of the tokenResponse when inserting the token into local storage. In some cases, the response may be stored in an access_token variable instead of id_token.

3- Examine the local storage of the application (the actual frontend, not the one undergoing testing with Cypress) and compare the values within. Focus on differences in object values rather than keys.

4- Update the missing fields in the local storage to match the values present in the frontend app (not the Cypress browser window). After making adjustments, rerun the test. Review the console.log output and additional token response data for guidance. In my case, minor modifications were required in the token injection process:

console.log('token response', tokenResponse);
const idToken = decode(tokenResponse.access_token);
console.log('idToken', idToken);
const localAccountId = idToken.oid || idToken.sid;
// const realm = idToken?.tid;
const realm = 'my-sign-up-sign-in-policy';
// const homeAccountId = `${localAccountId}.${realm}`;
const homeAccountId = `${localAccountId}-${realm}.a-string-that-i-took-from-the-frontend-local-storage`;
// const username = idToken.preferred_username;
const username = idToken.emails[0];

In summary, by aligning the data in the response with the real app's local storage and the Cypress browser window, the issue was resolved. Identify any missing data and make necessary adjustments to achieve synchronization. Each situation may vary, so adapt accordingly.

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

Creating a dynamic effect to blur slideshow content located underneath a specific div

Struggling to figure out how to achieve a blur effect on a slideshow with moving elements? Most resources focus on static images, but I need help with objects in motion. My project involves a jQuery Cycle slideshow, and I want the background areas of over ...

Identify the moment a dialogue box appears using jQuery

I'm facing a situation where multiple dialogs are opened in a similar manner: $("#dialog").load(URL); $("#dialog").dialog( attributes, here, close: function(e,u) { cleanup } The chall ...

When using Node.js, you may encounter the error message: "TypeError: brevo.ApiClient is not a constructor

My goal is to set up an automatic email sending system that, upon receiving details like name and email, will send a confirmation email to the provided email address with the message "subscribed." I've been working on this task for about 7 hours strai ...

Node.js PDFKit Measurement Units

Can you clarify the measurement unit used in PDFKit (Node.js)? For example, we have: doc.text(20, 20, 'Message') What exactly does 20(x) and 20(x) represent? Are they measured in centimeters, millimeters, inches, or something else? Can I conver ...

Tips for effectively transmitting data while utilizing a declarative/reactive data access method with RxJS in Angular?

Angular typically follows a classic pattern for data access that looks like this: Traditional Data Access Pattern getProducts(): Observable<Product[]> { return this.http.get<Product[]>(this.productsUrl) .pipe( tap(data => consol ...

Node.js: The REST client delivers the response even before it has been officially returned

I've been experimenting with the node-rest-client REST client in Node.js. However, I'm facing an issue where when I run the code snippet below, it returns a value of null. Oddly enough, the response is printed to the console after that. Is there ...

Having trouble getting a basic jQuery UI tooltip to function properly

I attempted to recreate the demo found on this website: http://jqueryui.com/tooltip/#default Here is the HTML code I used: <h3 title='this is the title of hello world'>hello world</h3> And here is the JavaScript code: $(document). ...

Obtain output from a callback function

Is there a way to set a variable using the code var myVar = myFunction(); when myFunction contains a callback function that prevents it from returning a value directly? I am unsure of how to modify this code in order to allow for a return value from the ...

Adapting imports in Typescript for seamless npm distribution

Currently, I'm facing an issue with module resolution while compiling my NPM package written in Typescript for publishing. In my project, I've been using non-relative imports to avoid the hassle of excessive ../../../. However, according to TypeS ...

Is there a way to order the execution of two functions that each produce promises?

With my code, I first check the status of word.statusId to see if it's dirty. If it is, I update the word and then proceed to update wordForms. If it's clean, I simply update wordForms. I'm looking for advice on whether this is the correct a ...

"Encountering a Heroku error due to an oversized cookie while using Express.js and

Being unsure of the exact cause, I am encountering an issue with Heroku that gives me the error message t=error code=H25 desc="HTTP restriction: oversized cookie" whenever I attempt to authenticate myself with Discord OAuth. Interestingly, this problem onl ...

Express router parameter matching

Let's consider a scenario where I have two routes - one with parameters and one without: /foo?bar /foo I aim to assign different handlers for these routes. Instead of the conventional approach, I am looking for a way to simplify the code. app.use(&a ...

Is there a way to automatically activate the "Add" button when I hit the enter key in the text box?

Being someone who relies on to-do lists, I implemented a system where you can input tasks into a textbox and click the add button to see them listed below. However, I found it cumbersome to keep clicking the add button every time I wanted to quickly add mu ...

Ways to perform a redirect following data retrieval from a post request

I am working on a post method for a servlet, where the servlet returns a web page after forwarding a request to another page. Instead of directly redirecting using window.location = "/AnotherServlet", I have tried various solutions including passing parame ...

Received an error during the module.exports = client process

In my commands folder, I have multiple files that contain slash commands. I am trying to import the client instance from index.js to another file, but when I use module.exports = client;, it ends up executing the entire index.js script unintentionally. I ...

When using Google login in React and Node.js, the requested scope may not be returned as expected

Looking to get additional scope data from Google API during login on my app. I am utilizing react-google-login to obtain a token in my React application with the following scopes: scope='https://www.googleapis.com/auth/user.birthday.read https://www. ...

How can I use jQuery to target elements other than the vertical scrollbar when

Here is how I am utilizing the mouseleave jquery event $(document).ready(function(){ $(document).mouseleave(function(event) { //perform a task }); }); Is there any method to prevent this event from triggering when a user scrolls ...

Transform a PHP array into a JavaScript array with the help of a model

Looking to convert this JavaScript array into PHP: array: [ { width: 150, id: "id", type: "string", header: [{ text: "Unit ID" }], editing: false}, { width: 150, id: "project_name", header: [{ text: "Project" }, { c ...

WebGL Tips: Resizing an object using vector multiplication, achievement showcased (see image)

I'm currently exploring methods to scale an object without taking into consideration its local rotation. While I have achieved some success using morph animation, I am searching for a more dependable solution. ...

Deactivate the Mention and Hash tag in ngx-linkifyjs

I am currently utilizing ngx-linkifyjs to automatically convert URLs in text to clickable hyperlinks. However, I am facing an issue where it is also converting # and @ tags into links. Is there a way to prevent the conversion of # and @ while maintain ...