Adding basic auth to all requests in Cypress - authentication

I'm a Cypress newbie and need to add basic auth to all cy.visit() calls.
The auth credentials are dependent on the deployment (i.e. they are specific to the 'baseUrl' which we set in the environment config files).
Currently, I have;
cy.visit("/", {
auth: {
username: '...',
password: '...'
}
});
What I want is to move the 'auth' object to the evg config files so I only need cy.visit("/") in the specs.
Many thanks

If you plan to reuse the authentification then is better to create a separate method for authentication e.g.:
1. Create a new custom command in `cypress/support/commands.js,
since it is loaded before any test files are evaluated via an import statement in your supportFile (cypress/support/index.js by default).
Cypress.Commands.add('login', () => {
// (you can use the authentification via API request)
return cy
.request({
method: 'POST',
url: your_url,
form: true,
body: {
username: Cypress.env('username'),
password: Cypress.env('password'),
grant_type: 'password',
client_id: your_clientId,
client_secret: your_clientSecret,
scope: 'openid',
},
})
})
2. Then use it in your test:
describe('My Test Name', () => {
before(() => {
cy.login();
});
it('should visit my base URL', () => {
cy.visit('/');
});
});
Note 1: Check how to set the environment variables here: Cypress.io: Environments Variables
Note 2: Check how to use the custom commands here: Custom Commands - Correct Usage

EDIT: since your syntax is correct - I will just share a way I use to do it in my tasks.
If your auth is working correctly you can make custom command - visitAndAuthorise like this for example:
Cypress.Commands.add("shopAdmin_visitAndLogin", (url) => {
cy.log('shopAdmin_visitAndLogin')
cy.visit(url)
cy.get('[data-qa="emailInput"]')
.type(Cypress.env('credentials').email)
cy.get('[data-qa="passwordInput"]')
.type(Cypress.env('credentials').password)
cy.get('[data-qa="loginButton"]')
.click()
cy.get('[data-qa="logOutButton"]')
.should('be.visible')
})
And your cypress.env.json file would need to include an object for the credentials like this:
{
"credentials": {
"email": "myEmail#gmail.com",
"password": "myPassword"
}
}
Or following your syntax:
Cypress.Commands.add("shopAdmin_visitAndLogin", (url) => {
cy.log('shopAdmin_visitAndLogin')
cy.visit(url, {
auth: {
username: Cypress.env('credentials').username,
password: Cypress.env('credentials').password
}})
})

If you have HTTP basic auth for all pages add this code to your cypress/support/commands.js:
Cypress.Commands.overwrite('visit', (originalFn, url, options) => {
options = options || {}
options.auth = {
username: 'replace_this_with_the_username',
password: 'replace_this_with_the_password'
}
return originalFn(url, options);
});

This is how I handled Basic Auth with Cypress using cy.request:
cy.request({
method:'POST',
url:'myURL',
body: {
Name: name,
userId: userId,
languageId: languageId
},
headers: {
authorization: 'Basic lasdkfjlsdyZHRoYXRpa25vdzp'
},
}).then(response => {
expect(response.status).to.equal(201)
})
})
Basically, the "headers" object inside the cy.request do the magic.

Related

How can I pass body params in a Next.js rewrite?

I have this POST request:
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: JSON.stringify({
grant_type: "password",
client_id: "client",
client_secret: "clientsecret",
username: "matias#gmail.com",
password: "12341234"
})
};
const token = fetch("http://localhost:3000/connect/token", requestOptions)
.then(response => console.log(response))
.catch(error => console.log(error));
I would like to rewrite it so I can bypass CORS error in development environment. To achieve this, I have this code in my next.config.js file:
const nextConfig = {
reactStrictMode: false,
async rewrites() {
return process.env.NODE_ENV === "development"
? [
{
source: "/connect/token",
destination: "http://localhost:4446/connect/token",
}
]
: [];
},
}
How can I specify the body params (grant_type, client_id, client_secret, username and password) to this Next.js rewrite? The error I am getting suggest these values are not present in my rewrite:
fail: IdentityServer4.Validation.ClientSecretValidator[0]
No client identifier found
I don't know about Next.js, but have you tried to add the url to the client configuration as Allowed Cors Origins?
You could add in your develop client the url http://localhost:3000.

Cypress - Status: 401 - Unauthorized in token authentication to other API call

I would like to ask for your help regarding the authentication token to be used in other API calls.
Below are the scripts of the command and test case:
//command.js
import "cypress-localstorage-commands";
Cypress.Commands.add('login', () => {
cy.request({
method: 'POST',
url: Cypress.env('api_auth'),
body: {
email: Cypress.env('email'),
password: Cypress.env('password'),
}
})
.its('body')
.then(body => {
cy.window().then(win => win.localStorage.setItem('jwt', body.token))
})
//test case
describe('GET Data', ()=> {
before(() => {
cy.login();
cy.saveLocalStorage();
});
beforeEach(() => {
cy.restoreLocalStorage();
});
it('GET - View All Data', () =>{
cy.request({
method : 'GET',
url : Cypress.env('api_data'),
}).then((res) =>{
expect(res.status).equal(200)
})
})
In my approach i have the same command, but instead of storing the token in the local storage, I'm adding it to the cypress.env file in the object of the admin, because i have several admins so my object file goes like so
{
admins:
admin1:{
"username":"admin1",
"password": "123456",
"token":""
},
admin2:{
"username":"admin1",
"password": "123456",
"token":""
}
}
This way you can store several admins/user tokens and just attach as:
Cypress.env.admins.admin1.token
or
Cypress.env.admins.admin2.token
I think this approach is simpler and in about 300 tests i've seen no problems regarding speed of the test execution or anything other

KeystoneJS login via GraphQL mutation

I am trying to login to a Keystone 5 GraphQL API. I have setup the app so that I can login via the Admin Console, but I want to login from a Svelte application.
I keep finding references to the code below (I am new to GraphQL) but don't know how to use it.
mutation signin($identity: String, $secret: String) {
authenticate: authenticateUserWithPassword(email: $identity, password: $secret) {
item {
id
}
}
}
If I post that query "as is" I get an authentication error, so I must be hitting the correct endpoint.
If I change the code to include my username and password
mutation signin("myusername", "mypassword") {
authenticate: authenticateUserWithPassword(email: $identity, password: $secret) {
item {
id
}
}
}
I get a bad request error.
Can anyone tell me how I send username/password credentials correctly in order to log in.
The full code I am sending is this
import { onMount } from 'svelte';
let users = [];
onMount(() => {
fetch("http://localhost:4000/admin/api", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: `mutation signin($identity: String, $secret: String) {
authenticate: authenticateUserWithPassword(email: $identity, password: $secret) {
item {
id
}
}
}`
})
}).then(res => res.json())
.then(data => {
console.log(data)
})
})
Here is the response I get
{"errors":[{"message":"[passwordAuth:failure] Authentication failed","locations":[{"line":2,"column":3}],"path":["authenticate"],"extensions":{"code":"INTERNAL_SERVER_ERROR","exception":{"stacktrace":["Error: [passwordAuth:failure] Authentication failed"," at ListAuthProvider._authenticateMutation (/Users/simon/development/projects/keystone/meetings-api/node_modules/#keystonejs/keystone/lib/providers/listAuth.js:250:13)"]}},"uid":"ckwqtreql0016z9sl2s81af6w","name":"GraphQLError"}],"data":{"authenticate":null},"extensions":{"tracing":{"version":1,"startTime":"2021-12-03T20:13:44.762Z","endTime":"2021-12-03T20:13:44.926Z","duration":164684813,"execution":{"resolvers":[{"path":["authenticate"],"parentType":"Mutation","fieldName":"authenticateUserWithPassword","returnType":"authenticateUserOutput","startOffset":2469132,"duration":159500839}]}}}}
I found the answer eventually.
You have to provide an extra object in your body called variables
variables: {
var1: "value1",
var2: "value2"
}
Those variables will then replace the placehodlers in the query like $var1 or $var2
Here is the full fetch code that works.
fetch("http://localhost:4000/admin/api", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: `mutation signin($identity: String, $secret: String) {
authenticate: authenticateUserWithPassword(email: $identity, password: $secret) {
item {
id
}
}
}`,
variables: {
identity: "myusername",
secret: "mypassword"
}
})
}).then(res => res.json())
.then(data => {
console.log(data)
})
It's a shame that KeystoneJS don't provide any full code examples in their documentation. It would have saved me hours of searching.
As you say #PrestonDocks, if your query defines variables, you need to supply the variable values in a separate top level object. For the benefit of others I'll link to the GraphQL docs on this.
The alternative is to not use variables and to in-line your values in the query itself, like this:
mutation signin {
authenticate: authenticateUserWithPassword(
email: "me#example.com",
password: "Reindeer Flotilla"
) {
item {
id
}
}
}
But variables usually end up being neater.

Nuxt auth module axios not setting CSRF token on request

I'm using the Nuxt auth module v5 and the Laravel sanctum provider. My csrf-cookie route works fine, and my login route works fine, but when trying to call this.$axios from a function, such as when creating a user's account (since auth module doesn't offer this) I'm getting a CSRF token mismatch.
It would appear that using axios directly like this doesn't have access to setting the cookie since no user logged in, how can I get the cookie to be set?
Method for account creation
/*
** Create accounr
*/
createAccount () {
this.feedback.isShown = false
this.isCreatingAccount = true
if (this.apiAccountCreationSource) this.apiAccountCreationSource.cancel('aborted')
const CancelToken = this.$axios.CancelToken
this.apiAccountCreationSource = CancelToken.source()
this.$axios.post(`${this.$config.apiUrl}/api/account`, this.account, {
cancelToken: this.apiAccountCreationSource.token,
timeout: 30 * 1000
}).then(res => {
this.apiAccountCreationSource = null
this.setContextualResponse(res)
setTimeout(() => {
this.login()
}, 250)
}).catch(err => {
this.setContextualResponse(err.response ? err.response.data : null)
}).finally(() => {
this.isCreatingAccount = false
})
},
Nuxt config
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
credentials: true,
baseURL: process.env.API_DOMAIN
},
// Auth module configuration: https://auth.nuxtjs.org/
auth: {
redirect: {
login: '/account/login/',
logout: '/account/login/',
callback: '/account/login/',
home: '/account/dashboard/'
},
strategies: {
'laravelSanctum': {
provider: 'laravel/sanctum',
url: process.env.API_DOMAIN,
endpoints: {
login: { url: '/api/login', method: 'post' },
logout: { url: '/api/account/logout', method: 'post' },
user: { url: '/api/account', method: 'get', propertyName: 'user' }
}
}
}
},
If you need to get the CSRF token all you need to do is make a request to your token endpoint and your browser should save the XSRF token. Then axios will automatically send this token in every subsequent request.
So all that you need to do is make a axios GET request to your csrf-cookie route before you send your POST request.
this.$axios.get(`${this.$config.apiUrl}/sanctum/csrf-cookie`)
Or you can chain both requests doing something like this:
this.$axios.get(`${this.$config.apiUrl}/sanctum/csrf-cookie`).then(() => {
return this.$axios.post(`${this.$config.apiUrl}/api/account`, this.account, {
cancelToken: this.apiAccountCreationSource.token,
timeout: 30 * 1000
}).then((res) => {
this.apiAccountCreationSource = null
this.setContextualResponse(res)
setTimeout(() => {
this.login()
}, 250)
}).catch((err) => {
this.setContextualResponse(err.response ? err.response.data : null)
}).finally(() => {
this.isCreatingAccount = false
})
})
Your authentication strategy works without this hassle because it handles this csrf request internally (https://github.com/nuxt-community/auth-module/blob/dev/src/providers/laravel-sanctum.ts)
References:
https://laravel.com/docs/8.x/sanctum#csrf-protection
https://github.com/axios/axios/issues/708#issuecomment-280920224

How to test single page application with Cypress and Auth0

I am having a single page application hidden behind Auth0 lock, using #auth0/auth0-spa-js. I would like to test it using Cypress, so I have decided to follow the official Auth0 blog post, as well as Johnny Reilly blog post.
I am able to successfully retrieve valid JWT token from auth0 using suggested request. I have no idea what to do with it :(
The trouble I am facing is that both of the above approaches are relying on the app to store the JWT token locally (either in cookie or localstorage). The #auth0/auth0-spa-js is, however, using a different approach, and I assume all the relevant cookies/localstorage is stored on auth0 domains.
Do you have any idea, if there is a way to get around it?
There is a similar issue reported here raised in July 2018, not really providing any solution
I found a resolved issue on #auth0/auth0-spa-js github. The approach suggested by cwmrowe seems to be working
The solution is to mock the response of oauth/token endpoint with token generated on e2e test side.
The approach seems to be working for us
I am copying over the sample code cwmrowe has provided
Cypress.Commands.add(
'login',
(username, password, appState = { target: '/' }) => {
cy.log(`Logging in as ${username}`);
const options = {
method: 'POST',
url: Cypress.env('Auth0TokenUrl'),
body: {
grant_type: 'password',
username,
password,
audience: Cypress.env('Auth0Audience'),
scope: 'openid profile email',
client_id: Cypress.env('Auth0ClientId'),
client_secret: Cypress.env('Auth0ClientSecret')
}
};
cy.request(options).then(({ body }) => {
const { access_token, expires_in, id_token } = body;
cy.server();
// intercept Auth0 request for token and return what we have
cy.route({
url: 'oauth/token',
method: 'POST',
response: {
access_token,
expires_in,
id_token,
token_type: 'Bearer'
}
});
// Auth0 SPA SDK will check for value in cookie to get appState
// and validate nonce (which has been removed for simplicity)
const stateId = 'test';
const encodedAppState = encodeURI(JSON.stringify(appState));
cy.setCookie(
`a0.spajs.txs.${stateId}`,
`{%22appState%22:${encodedAppState}%2C%22scope%22:%22openid%20profile%20email%22%2C%22audience%22:%22default%22}`
);
const callbackUrl = `/auth/callback?code=test-code&state=${stateId}`;
return cy.visit(callbackUrl);
});
}
);
declare namespace Cypress {
interface Chainable<Subject> {
login(
username: string,
password: string,
appState?: any
): Chainable<Subject>;
}
}
Whilst it's not recommended to use the UI to login I do this myself once prior to all tests and then use the silent auth for the tests:- cy.visit("/") silent auths and allows access to the app.
integration/app.js
describe("App", () => {
before(() => {
Cypress.config("baseUrl", "http://localhost:3000");
cy.login();
});
/** Uses silent auth for successive tests */
beforeEach(() => {
cy.restoreLocalStorage();
});
afterEach(() => {
cy.saveLocalStorage();
});
/** tests */
support/commands.js
/**
* Auth0 login
* https://github.com/cypress-io/cypress/issues/461#issuecomment-392070888
*
* Allows silent auth login between tests
*/
let LOCAL_STORAGE_MEMORY = {};
Cypress.Commands.add("saveLocalStorage", () => {
Object.keys(localStorage).forEach(key => {
LOCAL_STORAGE_MEMORY[key] = localStorage[key];
});
});
Cypress.Commands.add("restoreLocalStorage", () => {
Object.keys(LOCAL_STORAGE_MEMORY).forEach(key => {
localStorage.setItem(key, LOCAL_STORAGE_MEMORY[key]);
});
});
Cypress.Commands.add("clearLocalStorage", () => {
LOCAL_STORAGE_MEMORY = {};
});
For those who has issue with Google Sign in for Cypress look at the plugin: https://github.com/lirantal/cypress-social-logins/
it('Login through Google', () => {
const username = Cypress.env('googleSocialLoginUsername')
const password = Cypress.env('googleSocialLoginPassword')
const loginUrl = Cypress.env('loginUrl')
const cookieName = Cypress.env('cookieName')
const socialLoginOptions = {
username,
password,
loginUrl,
headless: false,
isPopup: true,
logs: false,
loginSelector: 'a[href="/auth/auth0/google-oauth2"]',
postLoginSelector: '.account-panel'
}
return cy.task('GoogleSocialLogin', socialLoginOptions).then(({cookies}) => {
cy.clearCookies()
const cookie = cookies.filter(cookie => cookie.name === cookieName).pop()
if (cookie) {
cy.setCookie(cookie.name, cookie.value, {
domain: cookie.domain,
expiry: cookie.expires,
httpOnly: cookie.httpOnly,
path: cookie.path,
secure: cookie.secure
})
Cypress.Cookies.defaults({
whitelist: cookieName
})
}
})
});