In our project we use Auth0 with Google login and don't use username/password login. We started to write tests for our app, but we can't login in Cypress framework. We need login using Google auth (but it's not possible to do it using request). Also, we don't store token in localStorage, because frontend part uses auth0 react sdk for it.
I tried to find how to login in Cypress using auth0, but found only solutions for username/password login.
Possible solution from this post:
Cypress.Commands.add("login", () => {
cy.clearLocalStorage();
const email = "";
const password = "";
const client_id = "";
const client_secret = "";
const audience = "";
const scope = "";
cy.request({
method: "POST",
url: "",
body: {
grant_type: "password",
username: email,
password,
audience,
scope,
client_id,
client_secret,
},
}).then(({ body: { access_token, expires_in, id_token, token_type } }) => {
cy.window().then((win) => {
win.localStorage.setItem(
`@@auth0spajs@@::${client_id}::${audience}::${scope}`,
JSON.stringify({
body: {
client_id,
access_token,
id_token,
scope,
expires_in,
token_type,
decodedToken: {
user: JSON.parse(
Buffer.from(id_token.split(".")[1], "base64").toString("ascii")
),
},
audience,
},
expiresAt: Math.floor(Date.now() / 1000) + expires_in,
})
);
cy.reload();
});
});
});
I can get token using client_credentials
grant type, but I can't use it in this solution, because it uses id_token
instead of the access_token
.
Is it possible to use client_credentials
grant type for this login? Or should we turn ON username/password login for it?
Request for client_credentials
grant type:
curl --request POST \
--url 'https://YOUR_DOMAIN/oauth/token' \
--header 'content-type: application/x-www-form-urlencoded' \
--data grant_type=client_credentials \
--data client_id=YOUR_CLIENT_ID \
--data client_secret=YOUR_CLIENT_SECRET \
--data audience=YOUR_API_IDENTIFIER
It returns:
{
"access_token":"eyJz93a...k4laUWw",
"token_type":"Bearer",
"expires_in":86400
}
We turned ON username/password way for login, and used UI for login. After the first login, Cypress don't show login page again, because we are already logged.
My solution (we use only username/password without additional info from Auth0):
Cypress.Commands.add('loginAuth0', (username = Cypress.env('auth0_username'), password = Cypress.env('auth0_password')) => {
cy.visit(`/`);
cy.wait(4000); // wait when auth0 modal is loaded (if user is not logged in)
cy.document().then(doc => {
if (doc.querySelector("#username") != null && doc.querySelector("#password") != null) {
cy.get('#username').type(username);
cy.get('#password').type(password);
cy.get('button[name="action"]').click();
} else {
cy.log("User is already logged.");
}
});
});