Cypress with Vue.js - programmatic login

Hello!

Thanks in advance for any advice or support.

Use case: Login to our Vue.js app using the auth0-js helper library.

Setup: Auth0’s tutorial for authentication, Cypress.io for front end testing, Following this fantastic auth0 guide by Johnny Reilly.

The guide has got us almost all the way. Here’s the commands.js Cypress file (The login setup).


const auth0 = require('auth0-js');

Cypress.Commands.add('loginAsAdmin', (overrides = {}) => {
  Cypress.log({
      name: 'LoginWithAuth0'
  });

  const webAuth = new auth0.WebAuth({
      domain: Cypress.env('auth_url'), 
      clientID: Cypress.env('auth_client_id'), 
      responseType: 'token id_token'
  });
  
  webAuth.client.login(
      {
          realm: 'Username-Password-Authentication',
          username: Cypress.env('auth_username'),
          password: Cypress.env('auth_password'),
          audience: Cypress.env('auth_audience'), 
          scope: 'openid email profile'
      },
      function(err, authResult) {
            window.sessionStorage.setItem('access_token', authResult.accessToken);
            window.sessionStorage.setItem('id_token', authResult.idToken);
            window.sessionStorage.setItem('expires_at', authResult.expiresIn * 1000 + new Date().getTime());
            window.localStorage.setItem('loggedIn', 'true');

              
          } else {
              console.error('Problem logging into Auth0', err);
  throw err;
          }
      }
  );
});

authResult returns an object with the (I think) correct information:

{
  accessToken: <access_token>
  expiresIn: 86400
  idToken: <id_token>
  scope: "openid email profile read:current_user update:current_user_metadata delete:current_user_metadata create:current_user_metadata create:current_user_device_credentials delete:current_user_device_credentials update:current_user_identities"
  tokenType: "Bearer"
}

The simple Cypress test using cy.loginAsAdmin(); -

describe('login', () => {
  it('should successfully log into our app', () => {
    cy.loginAsAdmin();
    cy.visit('/dashboard') // only seen whilst logged in.
  });
});

But to no luck - it still asks me to log in to the app.

I’ve noticed that the vue.js documentation for auth0 doesn’t mention storing any of the parts that made up authResult earlier in sessionStorage/localStorage. So i’m unsure if this is the method to get through the auth using these technologies.

Am I missing something? Is there an alternative flow for a Cypress/Vue mix?

Quick edit: Let me know if there’s any information required to help debug.

Many thanks in advance,

Ryan

Hey there @R_Chaps, welcome to the Auth0 Community!

Are you seeing any errors in terminal or in the logs when you hit this challenge? Generally we avoid storing anything in Browser local storage (or session storage) as it’s not a secure place to store sensitive information. Any data stored there:

I also have included a blog article below written from the Auth0 blog this year that dives into Cypress as a point of reference.

Hey @James.Morrison, thanks for the response.

So since posting, we did decide to go down the route of using your solution(Which is great, thanks!). Which does get us through auth0 and logged into the app.

The problem we’re facing now is that we can’t navigate to any pages using cy.visit() without losing the authenticated state. Presumably because we’ve parsed all the information through using the callbackUrl.

We can do all the navigation within the app as it’s a SPA, but if we need to get access to a page that you can’t navigate to, then we hit a wall.

Is there a way to combine your solution with being able to use cy.visit() to get to pages?

Thanks

From reviewing the Cypress documentation it looks like you should be able to do so.

Example: cy.visit('/contact.html')

Thanks for the response @James.Morrison
Unfortunately that’s the issue, it doesn’t work.

When using cy.visit():

’ There was an error fetching the SSO data. This is expected - and not a problem - if the tenant has Seamless SSO enabled. If the tenant doesn’t have Seamless SSO enabled, this could simply mean that there was a problem with the network. But, if a “Origin” error has been logged before this warning, please add “<our_url>” to the “Allowed Web Origins” list in the Auth0 dashboard: “<link_to_change>” ’

The url it’s suggesting is already in the Allowed Web Origins, and this fails every time, so I have no reason to believe it’s an connectivity issue.

Have you got any advice for this?

Thanks,

Ryan

To follow up @R_Chaps, when you get a chance can you snag us a HAR file of the workflow and direct message it over to me? Please be sure to select “Preserve log” to catch redirects and scrub the file of user passwords before passing, thanks!

Sure thing, i’ll message it now.

After looking at this HAR file with another engineer @R_Chaps, we are not seeing the breakdown. Can you Direct Message me a test user that we can give a go and see if we can replicate the problem? Thanks in advance!

Hey @James.Morrison,

We’re happy to give you a test user to play with. I was thinking that at this stage, it may be worth arranging call between you, me and our dev to talk this through properly. We can timebox it as to not take up too much of your time, and pick a time that suits you.

Note that anything that we discover i’ll write up as a comment here in case any future readers get stuck with a similar problem.

Would you be up for that?

We’re UK based if that helps with timing.

I wanted to follow up @R_Chaps, I am unable to do that from the Community stand point but what I can do is connect you with our next level support team that can do something like that but that may require a higher tier account status. That being said, I want to help and am willing to continue diving into this challenge together. Please let me know how you would like to proceed forward.

Thanks for the information.

Our Dev is on holiday for the next week. I’m under the impression we can pass across a test account, and the Cypress test that is causing the error - but I need to confirm with our dev first. Thank you for keeping with this, I’ll respond on this thread when I can.

1 Like

No problem, keep me posted. I want to continue to help you and your team move forward.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.