简体   繁体   中英

Unable to by pass amazon cognito authentication using cypress

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 ie

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?

在此处输入图像描述

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("/");
    // ...
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM