Unable to by pass amazon cognito authentication using cypress

Viewed 337

I am trying to get login, but login functionality takes place in 'AWS Cognito Authetication', which is making my life little mess.

What happens, when user enters base url on browser, app navigates to 'AWS Cognito' message, where I enter my credentials, after adding credentials, app is showing me an alert message i.e.

An error was encountered with the requested page.

Screenshot is attached. I have checked network logs, but it is showing me that:

{"error":{"name":"UnauthorizedError","message":"No authorization token was found"}}

I need to know , where to start the procedure, I have gone through AWS Cognito Credentials section, but nothing happened yet. Can someone help me there, how to start and how to work with it?

enter image description here

1 Answers

Cypress documentation has advice on how to authenticate with Cognito.

It could be more complete though, this blog post by Nick Van Hoof offers a more complete solution.

First install aws-amplify and cypress-localstorage-commands libs.

Add a Cypress command like:

import { Amplify, Auth } from 'aws-amplify';
import 'cypress-localstorage-commands';

Amplify.configure({
  Auth: {
    region: 'your aws region',
    userPoolId 'your cognito userPoolId',
    userPoolWebClientId: 'your cognito userPoolWebClientId', 
  },
});

Cypress.Commands.add("signIn", () => {
  cy.then(() => Auth.signIn(username, password)).then((cognitoUser) => {
    const idToken = cognitoUser.signInUserSession.idToken.jwtToken;
    const accessToken = cognitoUser.signInUserSession.accessToken.jwtToken;

    const makeKey = (name) => `CognitoIdentityServiceProvider.${cognitoUser.pool.clientId}.${cognitoUser.username}.${name}`;

    cy.setLocalStorage(makeKey("accessToken"), accessToken);
    cy.setLocalStorage(makeKey("idToken"), idToken);
    cy.setLocalStorage(
      `CognitoIdentityServiceProvider.${cognitoUser.pool.clientId}.LastAuthUser`,
      cognitoUser.username
    );
  });
  cy.saveLocalStorage();
});

Then your test:

describe("Example test", () => {
  before(() => {
    cy.signIn();
  });

  after(() => {
    cy.clearLocalStorageSnapshot();
    cy.clearLocalStorage();
  });

  beforeEach(() => {
    cy.restoreLocalStorage();
  });

  afterEach(() => {
    cy.saveLocalStorage();
  });

  it("should be logged in", () => {
    cy.visit("/");
    // ...
  });
});
Related