unable to signup using keycloak through cypress

See original GitHub issue

Current behavior:

In my application, user management is done through Keycloak. Manual signup works fine but while testing my application end to end through cypress, I come across an issue. When I sign up user through it, it gives the following error:

We’re sorry. An error has occurred, please login again through your application.

I have noticed that in test case cypress is appending session_code to the request url after I click on submit button. While doing manual test I don’t get session code. This can be cause of this issue. Please share your views if you think of any other reason for this issue. Below is the url generated through cypress

.../login-actions/registration?session_code=LsZbmsVVLwEH9s-xwFJ2JdDtaCu1_xzqAGOQCpjxGJI&execution=06fac3bb-fb19-474b-8659-2572586ae371&client_id=web_app&tab_id=PSlmfgdv0ls

Where as manually generated url is like following

.../login-actions/registration?client_id=web_app&tab_id=PSlmfgdv0ls

My application backend is Spring boot and front-end is in React and next.js

It would be really helpful if anyone from your team could guide us for this issue. Please let me know if you need more information about our application.

Desired behavior:

Desired behavior is to able to signup through cypress tests

Steps to reproduce: (app code and test code)

You can use this test case

{
  "baseUrl": "",
  "pageLoadTimeout": 180000,
  "defaultCommandTimeout": 50000,
  "env":{
    "ENVIROMENT":"mock"
  },
  "reporter": "mochawesome",
  "reporterOptions": {
    "reportDir": "reports",
    "reportFilename": "test-report",
    "reportTitle": "Carbook Test Run",
    "overWrite": true,
    "saveHtml": true
  }
}
describe("Carbook Registration Page", () => {
  before(() => {
    cy.visit("/")
  })

  it("Verify that user is access registration page", () => {
    cy.get("#nav-sign-in").should('be.visible')
    cy.get("#nav-sign-in").click()
    cy.wait(5000)
    cy.get("a").contains("Register").should('be.visible')
    cy.get("a").contains("Register").click()
  })

  it("Verify that user able to go back to login page", () => {
    cy.get("#kc-form-options").should('be.visible')
    cy.get("#kc-form-options").click()
    cy.get("#kc-page-title").should('be.visible')
  })

  it("Verify that user is able to register for carbook", () => {
    cy.get("#firstName").type("Test")
    cy.get("#lastName").type("Test")
    cy.get("#email").type("wajeeha@test.com")
    cy.get("#password").type("test@123")
    cy.get("#password-confirm").type("test@123")
    cy.get('input[name="user.attributes.phone"]').type("12341234567")
    cy.get('input[name="user.attributes.cnic"]').type("1234512345678")
    cy.get('input[value="Register"]').click()
    cy.wait(10000)
  })
})

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:13 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
pouriaMalekicommented, May 30, 2019

@ZijlkerVR I have followed steps 1 to 3 using this Blog Post of @vrockai, still can’t figure out why it won’t work.

It might be because of step 4 and 5 of your guide, can you provide more detailed information about that?

context('Logged in user', () => {
  beforeEach(() => {
    cy.kcLogin('testuser', 'testuserpass');
  });

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

  it('Should render logged user name somewhere on the page', () => {
    cy.visit('http://SAMPLE.com'); // still not logged in, although beforeEach is successful.
    cy.get('#username').should('contain', 'testuser');
  });
});
2reactions
ZijlkerVRcommented, Jun 3, 2019

@pouriaMaleki Interesting blog post. His method is comparable to my first 2 steps. He has a cleaner way of retrieving the ActionURL though. He creates a UUID to fill state in step 1 but, atleast in my case, it’s optional so I just skipped it and get it later. Although creating a state UUID beforehand might actually decrease the number of steps I need in total so gotta look into that. Not sure if it’s the case.

I noticed he stops after his POST. In my case it would only give me KC cookies, but not site specific login cookies. I really need to follow through to atleast 3 more requests untill our site specific cookie will be set. Again… it might be specifically related to our implementation since they have build quite some code around Keycloak here. It’s been build by external supplier so lacking the knowledge on site.

Notice that my step 3 is a specific call back to the login page. Now that KC cookies are available it triggers our site to process and eventually end up with site specific auth cookies.

If I would follow redirect after step 2 POST I would get stuck. Might also be your problem.

Unfortunately I don’t understand why steps 4 and 5 are needed. I would expect followRedirect=true in step 3 to work, but I had to disable followRedirect and manually catch and explicitly request them in order to get a successfull login cookie. Could be a Cypress bug.

My advice would be to go through the requests step by step by catching en requesting manually like I did. Will give more control and insight. When we login through UI there is even more than these 5 requests/redirects, but I cut it off as soon as I get the cookie.

My code might help (simplified a bit by removing our environment specific condition) :

Cypress.Commands.add("login", (user, pass) => {
    Cypress.log({ name: 'Login' })
    const userName = (user != undefined) ? user : Cypress.env('user')
    const passWord = (pass != undefined) ? pass : Cypress.env('pass')
    cy.clearCookies()

    // Non UI login - awesomely fast
    // 1. Get login params from auth
    // 2. Post form to authenticate
    // 3. Get back to /login
    // 4. Follow redirect to auth
    // 5. Follow redirect to origin

    const getStartBody = {
        url: 'Cypress.config('baseUrl')' + '/auth/realms/*REALM*/protocol/openid-connect/auth',
        followRedirect: false,
        qs: {
            scope: 'name,email',
            response_type: 'code',
            approval_prompt: 'auto',
            redirect_uri: Cypress.config('baseUrl') + '/userauth',
            client_id: 'account'
        }
    }
    // Step 1
    cy.request(getStartBody).then((getStartResp) => {

        const actionUrl = getStartResp.body.match(/action\=\"(.*)\" /)[1].replace(/&/g, '&');
        const postLoginBody = {
            method: 'POST',
            url: actionUrl,
            followRedirect: false,
            form: true,
            body: { username: userName, password: passWord }
        }
        // Step 2
        cy.request(postLoginBody)
        // Keycloak cookies now set

    }).then(() => {
            // Step 3
            cy.request({
                url: '/login?redirect=/',
                followRedirect: false
            }).then((redirectResp1) => {
                // Step 4
                cy.request({
                    url: redirectResp1.redirectedToUrl,
                    followRedirect: false
                })
            }).then((redirectResp2) => {
                // Step 5
                cy.request({
                    url: redirectResp2.redirectedToUrl,
                    followRedirect: false
                })
            }).then(() => {
                // Finally got the site cookie
                cy.getCookie('cookie').should('exist')
            })
    })
Read more comments on GitHub >

github_iconTop Results From Across the Web

Unable to signup using Keycloak through Cypress
When I sign up a user, it gives the following error: We're sorry. An error has occurred, please login again through your application....
Read more >
cypress-io/cypress - Gitter
Hi everyone, I'm trying to signup on keycloak using cypress but experiencing an error on keycloak. Here is the detail of issue,. In...
Read more >
unable to signup using keycloak through cypress - Bountysource
In my application, user management is done through Keycloak. Manual signup works fine but while testing my application end to end through ......
Read more >
Cypress.io and Keycloak : r/softwaretesting - Reddit
Cypress.io looks to be a promising tool for UI software testing. I have tried, without success, to perform a login with a keycloak...
Read more >
Cypress E2E testing using keycloak-js - Getting advice
By adding "chromeWebSecurity": false I can navigate to the keycloak login page, however cypress is then unable to interact with the login ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found