Giter Club home page Giter Club logo

cypress-keycloak-commands's Introduction

cypress-keycloak-commands

All Contributors

Cypress commands for login with Keycloak.

  • Setup Keycloak configuration from Cypress configuration or environment variables
  • Use Fixtures to store users data
  • Returns you the tokens of the logged user for calling backend APIs from your test code
  • Fake login command for integration testing
  • Tested with Keycloak 4.8, 5, 6, 7 and 8

Usage

Installing

Install the package using npm:

npm i -D cypress-keycloak-commands

or Yarn:

yarn add -D cypress-keycloak-commands

Import the package in the file cypress/support/commands.js (or cypress/support/commands.ts):

import "cypress-keycloak-commands";

Setup Keycloak configuration

Setup the Keycloak configuration in cypress.json configuration file:

{
  "env": {
    "auth_base_url": "https://auth.server/auth",
    "auth_realm": "my_realm",
    "auth_client_id": "my_client_id"
  }
}

You can override this settings for some tests using Enviroment variabiles.

Login commands for E2E Tests

For logging in with Keycloak you must create a fixture containing the user credentials under the directory cypress/fixtures/users. For example you can create a file cypress/fixtures/users/user.json with this content:

{
  "username": "user",
  "password": "password"
}

When you have a fixture you can login using the kcLogin command, passing the name of the fixture, and you can perform a logout using the kcLogout command:

describe("Keycloak Login", () => {
  beforeEach(() => {
    cy.kcLogout();
    cy.kcLogin("user");
    cy.visit("/");
  });
});

You should always perform logout before logging in a user, following the best practice of cleaning the state in the beforeEach hook.

Get user tokens for calling APIs from E2E tests

If you need to call backend APIs from your tests using the token of the logged user (for example to set up the state bypassing the UI) you can get the retrieved user tokes from the kcLogin command:

describe("Keycloak Login", () => {
  beforeEach(() => {
    cy.kcLogout();
    cy.kcLogin("user").as("tokens");
    cy.visit("/");
  });

  it("should call an API with the token", () => {
    cy.get("@tokens").then(tokens => {
      cy.request({
        url: "/my_api"
        auth: {
          bearer: tokens.access_token
        }
      });
    });
  });
});

Note: if you use Typescript you have to specify the return type of the cy.get command:

cy.get<KcTokens>("@tokens");

Fake Login for Integration testing

If you are doing an integration test that doesn't call a real backend API, maybe you don't need to authenticate a real user to a running Keycloak instance, but if your app uses the Keycloak Javascript Adapter to check if a user is logged in, you will need to have a mocked user.

To create mocked user data, you need three tokens (access token, refresh token, id token) of a real user returned by your Keycloak instance. You can get them for example from the Dev Tools of your browser, searching for calls to the token endpoint of Keycloak. If your app calls the /account endpoint to retrieve user information you will also need to have the response returned for the API. Then you can create the fixture with the fake user data:

{
  "fakeLogin": {
    "access_token": "...",
    "refresh_token": "...",
    "id_token": "...",
    "account": {
      "username": "user",
      "firstName": "Sample",
      "lastName": "User",
      "email": "sample-user@example",
      "emailVerified": false,
      "attributes": {}
    }
  }
}

With the fixture in place, you can use the kcFakeLogin command to perform a fake login without hitting a real Keycloak instance.

The Fake Login is performed loading a page and passing some keycloak initialization parameters in the URL. If you need to visit a page different from the homepage you must pass its url to the kcFakeLogin command as second parameter (instead of using cy.visit):

describe("Keycloak Fake Login", () => {
  beforeEach(() => {
    cy.kcFakeLogin("user", "pageToVisit");
  });
});

Session Status iframe

At the moment within Cypress is not possible to mock iframe loading and APIs called from an iframe. For this reason, when you use kcFakeLogin you have to disable the Session Status iframe, otherwise the Javascript adapter will redirect you to the real Keyacloak instance. You can disable it only when the app is running inside Cypress:

const checkLoginIframe = window.Cypress ? false : true;

var initOptions = {
  responseMode: "fragment",
  flow: "standard",
  onLoad: "login-required",
  checkLoginIframe
};

Acknowledgements

Other solutions that have inspired this library:

License

MIT

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Gianluca Frediani

๐Ÿš‡ ๐Ÿ”ง โš ๏ธ ๐Ÿ“– ๐Ÿค” ๐Ÿ’ป

Ilkka Harmanen

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

cypress-keycloak-commands's People

Contributors

allcontributors[bot] avatar dependabot[bot] avatar fredx87 avatar groie avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.