I'm trying to test my application with mocha, chai and chai-http. When I test the login, I can't seem to log in no matter what I try. I've tried in Postman and gotten the same result.
I've seen many answers along the lines of this one but I've had no success with them.
Is Passport doing something that's preventing successful login? I can log in from the browser with no problem.
I found an answer in this post and from tinkering with the settings in Postman. Adding the content type x-www-form-urlencoded seemed to be the key.
it('should redirect to dashboard on successful login', function(done) {
chai.request('http://localhost:3000')
.post('/login')
.set('Token', 'text/plain')
.set('content-type', 'application/x-www-form-urlencoded')
.type('form')
.send('grant_type=password')
.send('username=bobby')
.send('password=abc123')
.end(function(err, res) {
res.should.have.status(200);
expect(res).to.redirectTo('http://localhost:3000/user/dashboard');
done();
});
});
Related
I'm trying to implemented login via API following Playwright's guidelines but somehow nothing seems to be working.
As a comparison I've built the same in Cypress and it works out of the box:
Context:
Playwright Version: 1.30
Operating System: Mac
Node.js version: v16.19.0
Browser: Chromium
I am unable to make a simple API login that works perfectly using Cypress instead. Let me share the 2 code snippets for comparison:
Simple test case:
API request to the login end-point - Auth token is retrieved
set the auth token as a cookie
navigate to a page that is accessible only if authenticated
Code Snippet
Cypress (working fine)
const body = {
username: 'username...',
password: 'password',
rememberMe: true,
};
describe('Login via API to management console', () => {
it('Login via API to management console', () => {
cy.request({
method: 'POST',
url: loginEndPoint,
headers: {
'Content-Type': 'application/json',
},
body,
}).then((response) => {
cy.setCookie('Authorization', `Token ${response.body.data.token}`);
});
cy.visit(`/management`);
});
});
Playwright (not working)
test('Login via API', async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
const loginResponse = await context.request.post(`https://${process.env.MANAGEMENT_URL}/web/api/v2.1/users/login`, {
data: {
username: process.env.MANAGEMENT_USER,
password: process.env.MANAGEMENT_PASSWORD,
rememberMe: true,
}
});
const {
data: { token },
} = await loginResponse.body().then((b) => {
return JSON.parse(b.toString());
});
expect(token).toMatch(/^[a-z0-9]{80}$/)
await context.addCookies([{ name: 'Authorization', value: `Token ${token}`, path: '/', domain: `https://${process.env.MANAGEMENT_URL}` }]);
await page.goto(`https://${process.env.MANAGEMENT_URL}/management/`);
await expect(page).toHaveURL(/management/);
});
Describe the bug
Both scripts are successful at retrieving the authentication token but somehow either I'm doing something wrong with setting the cookie in Playwright or there is an issue. I'd assume the 2 scripts should be comparable.
Furthermore: I've tried to execute login via UI using global-setup, saving the storage-state, loading it before running the test and it fails also in this case... so there is something that is not setting properly the state in this case or the cookie in the previous one.
Not entirely sure why the cookie approach wasn’t working, perhaps the https:// part should be removed from the domain?
That being said, in Playwright you shouldn’t even need to do that especially within a single test, looking at the Playwright docs on signing in via the API and related page about the request context particularly under cookie management. The associated request and browser contexts share cookies, so once you complete the login request, the browser should already have the cookie state too and be logged in, so you should be able to just remove getting the token and adding the cookie. Or you can login with the API in the global setup even, as that doc showed. Just make sure in that case to save the storage state, and specify the same file in your config.
I see you tried the global setup approach (through the UI, but you can use the API since you have it), not sure what happened there. I would say to ensure that you specified the storageState in the config; I would be curious how you loaded it as mentioned, and if you’re still having problems maybe share the code you’re using for that piece?
Hope that helps or we can troubleshoot further!
Im trying to add a logout functionality to my mern app where I only have google authentication using passportJS. I want to clear the cache and cookies on logout because if I don't it automatically logs me back in without asking for what account to choose.
The cookie im trying to delete is a https only cookie
I have tried what seems like every solution on the internet but none of them work
logout
document.cookie = "connect.sid=; Max-Age=0;secure;path=/"; // This worked only for the first time
// clears cache which works fine
caches.keys().then((names) => {
names.forEach((name) => {
caches.delete(name);
});
});
window.open(`${apiURL}/auth/logout`, "_self");
I have tried other solutions like: react-cookie, universal-cookie, js-cookie etc... But none of them seem to work either.
Does anyone know how to do this I have been stuck on this for a long time?
Ok so after a while I figured out that I cannot delete http only cookies so what I did was I simply used the req.logout() function on the backend to delete it
when you log the user out you simply redirect the user to this route which then deletes the cookie and redirects back!
router.get("/logout", (req: Request, res: Response) => {
req.logout({}, (err: any) => {
if (err) return res.status(500).json({ message: "Something went wrong." });
res.redirect(clientURL);
});
});
I'm working on e2e test with cypress on my application.
In my case the login are manage by a external service.
When I want to enter in my application's home page (https://myApplication/home), the system redirects me in different superdomains to login.
At first cypress seems to be able to change the superdomain, but once arrived in external service page for the authentication, the system go in login error (as if we have already logged in, but incorrect).
This type of behavior does not happen outside the cypress .
Are there alternative solutions to manage external access in a cypress test or is it possible to manage it directly from cypress?
I added in my cypress.json the chromeWebSecurity:false and when I call the link for login, I added the failOnStatusCode: false,
but it still doesn't work.
Assuming this is caused by SameSite cookie blocking , then I've just been fighting the same issue. I resolved it by intercepting all requests, checking if they had a set-cookie header(s) and rewriting the SameSite attribute. There's probably a neater way to do it, as this does clutter up the cypress dashboard a little.
Sadly Zachary Costa's answer no longer works as Chrome 94 removed the SameSiteByDefaultCookies flag.
You can add this as a command for easy reuse:
In your commands file:
declare namespace Cypress {
interface Chainable<Subject> {
disableSameSiteCookieRestrictions(): void;
}
}
Cypress.Commands.add('disableSameSiteCookieRestrictions', () => {
cy.intercept('*', (req) => {
req.on('response', (res) => {
if (!res.headers['set-cookie']) {
return;
}
const disableSameSite = (headerContent: string): string => {
return headerContent.replace(/samesite=(lax|strict)/ig, 'samesite=none');
}
if (Array.isArray(res.headers['set-cookie'])) {
res.headers['set-cookie'] = res.headers['set-cookie'].map(disableSameSite);
} else {
res.headers['set-cookie'] = disableSameSite(res.headers['set-cookie']);
}
})
});
});
Usage:
it('should login using third party idp', () => {
cy.disableSameSiteCookieRestrictions();
//add test body here
});
or alteratively, run it before each test:
beforeEach(() => cy.disableSameSiteCookieRestrictions());
We were encountering a similar issue, where Cypress was redirecting us to the default "You are not logged in" page after getting through the login process. I'm not certain if that's EXACTLY the issue you were experiencing, but just in case, here's our solution. In our case, the issue was caused by Chrome's "Same Site Cookies" feature interacting poorly with Cypress, so we needed to disable it. In your plugins/index.js file, you would add the following code:
module.exports = (on, config) => {
on('before:browser:launch', (browser, launchOptions) => {
if (browser.name === 'chrome') {
launchOptions.args.push('--disable-features=SameSiteByDefaultCookies');
}
return launchOptions;
});
};
Note that if you already have launchOptions being set, you can just add this code onto it so it doesn't clash at all.
Hopefully, this works for you as well!
In the current version of cypress you can't go to another domain in the same test. This is due to the fact that cypress injects its test into the browser (they are working on this issue).
So one solution today is that you need to utilize cy.request to perform the login programmatically and inject the auth secret (jwt, cookie, localstorage, token or what you have) into the browser context yourself (for cookie this would be cy.setcookie).
Always make sure to checkout the plugins if there is already an abstraction for your login. Often this is openId or ntlm.
Beeing new to vue testing, I'm trying to make an integration test for our Vue SPA with axios & mocha.
I want some of the tests to make real api calls to our server without mocking, to figure out if it really works from the beginning to the end. The server API is a Laravel 7 app with laravel/sanctum and cookie based session authentication.
I can make real axios calls directly in the test file like this:
import authApi from '../../src/components/connections/auth';
describe('AxiosCallTest', () => {
it('makes an axios call', function(done) {
this.timeout(5000);
authApi.get('/sanctum/csrf-cookie').then((response) => {
console.log('response: ', JSON.stringify(response));
done();
}).catch(() => {
done();
});
});
});
// -> response: {"data":"","status":204,"statusText":"No Content","headers":{"cache-control":"no-cache, private"},"config":{"url":"/sanctum/csrf-cookie","method":"get","headers":{"Accept":"application/json","X-Requested-With":"XMLHttpRequest"},"baseURL":"http://testing.backend.vipany.test/api/auth","transformRequest":[null],"transformResponse":[null],"timeout":30000,"withCredentials":true,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"axios-retry":{"retryCount":0,"lastRequestTime":1591774391768}},"request":{"upload":{"_ownerDocument":{"location":{"href":"http://localhost/","origin":"http://localhost","protocol":"http:","host":"localhost","hostname":"localhost","port":"","pathname":"/","search":"","hash":""}}},"_registeredHandlers":{},"_eventHandlers":{}}}
I've read and tried a lot and now have 2 problems:
handling cookies for CSRF Token Cookies and Session Cookies (used for authentication), as on conventional requests the browser handles this out of the box.
waiting on axios calls in vue components, as I can't use mocha's done() function in the components itself, as I did in this example. I can only find examples with mocking requests with moxios or similiar. But I don't want to mock the axios calls.
Does anyone know a good article about these issues or has already solved it?
Thanks a lot
update:
I've found an article to get the cookie out of the axios request and tried it myself to get the X-XSRF-TOKEN out of the response (I've checked it in the browser: HttpOnly: false, secure: false), but it does not work:
console.log('response X-XSRF-TOKEN: ', response.config.headers['X-XSRF-TOKEN']);
// -> undefined
Found out that cypress and nightwatch are the right tools for end-to-end testing (e2).
Didn't know the right terms (e2e or end-to-end testing) and the right tools.
Switched to cypress.io - absolutly great.
vue-cli even has first hand plugins to integrate cypress or nightwatch: https://cli.vuejs.org/core-plugins/e2e-cypress.html
I've inherited a Node.js web app that uses relies on OAuth. Whenever you visit a page the app ensures you've authenticated. Please note, there no Angular, React, Vue, etc here. Each page is straight up HTML.
I want to test this site using Cypress. My problem is, I'm stuck on the initial redirect from the auth provider. Cypress acknowledge OAuth is a challenge.
commands.js
Cypress.Commands.add('login', (credentials) => {
var settings = {
'clientId':'<id>',
'scope':'<scope-list>',
...
};
var body = `client_id=${settings.clientId}&scope=${settings.scope}...`;
var requestOptions = {
method: 'POST',
url: 'https://login.microsoftonline.com/...',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: body
}
cy.request(requestOptions);
});
Then, in my test, I have:
context('Home', () => {
it('Visits Successfully', () => {
cy.login();
cy.title().should('include', 'welcome');
});
});
In the test runner, I see the login POST request is occurring. I confirmed that an access token is being received using a console.log, however, my title is empty. It's like the redirect after OAuth isn't happening in Cypress. However, when I visit the site in the browser, the redirect is happening as expected.
What am I missing?
What you might be missing is confusing between the actual UI flow and the programmatic flow of doing OAuth with a 3rd party website.
What you would want to do is to complete the programmatic login and then send the required parameters to your OAuth callback URL for your app manually in the test code.
an example is given here (though it uses a different grant type it gives you an idea) https://auth0.com/blog/end-to-end-testing-with-cypress-and-auth0/#Writing-tests-using-Cypress-Login-Command
another issue on the cypress github that deals with a similar problem
https://github.com/cypress-io/cypress/issues/2085
this also might help:
https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/logging-in__single-sign-on/cypress/integration/logging-in-single-sign-on-spec.js