Test automation of authorization prompt - chrome - authentication

I am trying to automate a simple login within this alert prompt authorization using cypress and javascript
I came across different solutions but I cant find the proper one.
What I actually do is I visit website with :
cy.visit('https://xxx/',{failOnStatusCode: false}) // Internal website with the fafailOnStatusCode: false
If I do not use failOnStatusCode: false I cant get to the prompt and I get an cypress message about using failOnStatusCode: false
But I am stuck after this step and neither cy.visit('https://username:password#xxx/',{failOnStatusCode: false})
is not working ...
Thanks for any comments and help. This is my first thread here :)
prompt

it('login prompt xxx', function () {
cy.setCookie("name", "value");
cy.visit("yourUrl.com", {
headers: {
authorization: 'Basic token'
},
failOnStatusCode: false
})
Test automated in cypress.
Open up the developer tools in chrome to find out these 2 things.
1.You have to know your cookie name and value from console. https://docs.cypress.io/api/commands/setcookie.html
2.Also you have to know your authorization which can be found in console.
https://docs.cypress.io/api/commands/visit.html

Related

Cypress: Login Authentication redirects to another domain: Workaround?

I understand that Cypress does not allow flipping from one domain to another domain because it will error with:
chrome-error://chromewebdata/
However, I need a workaround. I am providing a test set for multiple environments: STAGE, DEMO, PROD.
With DEMO and PROD, during the authentication phase (username/password), stay within the same domain:
VISIT: https://[demo|www].foo.com
AUTH: https://account.foo.com/auth >> username >> password
CONSENT: https://[demo|www].foo.com/action...
With STAGE, the authentication phase flips to another domain:
VISIT: https://[stage].foo.com
AUTH: https://account.bar.com/auth >> username >> password
CONSENT: https://[stage].foo.com/action...
Thereby, Cypress fails to redirect from VISIT to AUTH because of domain flip. This is blocking testing of STAGE.
What recommended workaround approaches?
Puppeteer?
Native Cypress using cy.request()?
Referenced:
Handling Cypress url redirect
Error with authentication in e2e tests using cypress: chrome-error://chromewebdata
Thank you, much appreciate the assistance.
The approach I took is similar to the Cypress Recipe Login with CSRF token
As mentioned, each deployment has its own website URL followed by account login URL.
Needed first is the CSRF token from account login page, which its URL is referred here as $baseUrl:
Cypress.Commands.add('cmdGetCSRF', ($baseUrl) => {
cy.log('COMMAND cmdGetCSRF');
expect($baseUrl)
.to.be.a('string')
.not.empty
cy.request($baseUrl)
.its('body')
.then(($body) => {
const $html = Cypress.$($body)
cy.log('html', $html)
const csrf = $html.find('input[name="__RequestVerificationToken"]').val()
expect(csrf)
.to.be.a('string')
.not.empty
return cy.wrap(csrf)
})
})
Then within body of requestOptions provided to cy.request() which will performing the login, provide one-time CSRF token:
const body: { [key: string]: string } = {
email: $envCypress.account_username,
password: $envCypress.account_password,
__RequestVerificationToken: $csrfToken
};
Cypress has recently add a new experimental feature for running test on multiple origins here. There are examples for cross origin login too. More on experimentalSessionAndOrigin feature:
https://docs.cypress.io/api/commands/origin
https://docs.cypress.io/api/commands/session

How to login with HTTP basic authentication to ACCESS the website- Test Cafe with Gherkin and cucumber

All links, project name and company name has been modified and are not original.
We have a basic HTTP authentication popup that appears when we are accessing out test/staging environments.
I am wondering, how can I enter the login information into the popup login window or send an api request in advance to save the cookie?
Because otherwise, I can't run the automation on our test environment. When the test access the page, I see a white website showing "unauthorized" in small letters.
This is what the login prompt looks like when accessing the Test/Staging env
We are using following plugin: https://www.npmjs.com/package/gherkin-testcafe
What I am asking is very similar to this question: Testing http basic authentication with Cucumber and RSpec in Rails 3.2.3
I have tried adding a role and using TestCafe http-authentication.html
Here is what I have tested so far:
TestCafe trying to use role:
const { Role } = require('testcafe');
const regularAccUser = Role('https://website/login', async t => {
await t
.typeText('#login', 'username')
.typeText('#password', 'password')
.click('#sign-in');
});
Given("I am open Dealer's login page", async t => {
await t
.useRole(regularAccUser)
.navigateTo(`${url}/login`);
});
That gives me:
ERROR CompositeParserException: Parser errors:
(7:3): expected: #EOF, #Comment, #BackgroundLine, #TagLine, #ScenarioLine, #ScenarioOutlineLine, #Empty, got 'Correct action happens when user provide either wrong or correct login information'
at Function.Errors.CompositeParserException.create (/Users/dennis/Projects/src/company/project/node_modules/gherkin/lib/gherkin/errors.js:27:13)
at Parser.parse (/Users/dennis/Projects/src/company/project/node_modules/gherkin/lib/gherkin/parser.js:72:45)
at specFiles.forEach.specFile (/Users/dennis/Projects/src/company/project/node_modules/gherkin-testcafe/src/compiler.js:43:33)
at Array.forEach (<anonymous>)
at GherkinTestcafeCompiler.getTests (/Users/dennis/Projects/src/company/project/node_modules/gherkin-testcafe/src/compiler.js:42:20)
at getTests (/Users/dennis/Projects/src/company/project/node_modules/testcafe/src/runner/bootstrapper.js:79:47)
at Generator.next (<anonymous>)
at step (/Users/dennis/Projects/src/company/project/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
at /Users/dennis/Projects/src/company/project/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13
If I try using:
import {Role} from 'testcafe'
I get:
tests/ui/stepDefinitions/login/login.js:1
(function (exports, require, module, __filename, __dirname) { import { Role } from 'testcafe';
^
SyntaxError: Unexpected token {
Using TestCafe's HTTP Authentication:
Feature: Login with correct and wrong info functionallity
.page('website/login')
.httpAuth({
username: 'username',
password: 'password',
})
Correct action happens when user provide either wrong or correct login information
#loginFunc
Scenario: Should NOT be able to login without filling in any credentials
Given I am open Dealer's login page
When I am login in with "empty" and "empty"
Then I should NOT be able to press the login button
I am getting following:
Feature: Login with correct and wrong info functionallity
✖ Scenario: Should NOT be able to login without filling in any credentials
1) Cannot obtain information about the node because the specified selector does not match any node in the DOM tree.
  | Selector('button[data-qa="qa-login-submit-button"]')
 > | Selector('button[data-qa="qa-login-submit-button"]')
Browser: Chrome 72.0.3626 / Mac OS X 10.14.3
32 | }
33 |});
34 |
35 |Then("I should NOT be able to press the login button", async t => {
36 | await t
> 37 | .expect(submitButton.hasAttribute('disabled')).ok()
38 | .expect(h1.exists).eql(true);
39 |});
```
It is basically showing me a white screen and saying: "**unauthorized**" in small letters.
You don't need any post/get requests with the Basic HTTP. Instead, you can log in using the Role mechanism:
When you switch to a role for the first time, TestCafe internally creates a branch of this role for this particular test run. All cookies set by your further actions will be appended to this branch. This branch will be used whenever you switch back to this role from the same test run.

Not able to close the browser using NightwatchJS

I am trying to open my url using Nightwatch and I wan't able to close the browser afterwards.
I tried using timeouts, as well as browser.end(), or browser.closeWindow(). None of them seem to be working for my url.
module.exports = {
'Demo test mywrkouts' : function (browser) {
browser.url('https://www.mywrkouts.com/workouts/search')
browser.timeouts('script', 10000, function(result) {
browser.end();
console.log("Test result"+result);
});
//browser.closeWindow();
}
};
It opens the page, but doesn't close the browser. I am using Chrome browser with chromedriver. I am expecting to close the window, but it doesn't work.
Any advice is appreciated.
LE: Like I extensibly described below, you don't need to explicitly close the browser at the end of the test (via browser.end()) as the Nightwatch test-runner does that for you at the end of each feature-file.
But, if you need to do some teardown operations and then explicitly close the session, do it in an after (or afterEach) hook. Try the following snippet:
module.exports = {
before(browser) {
browser.maximizeWindow();
},
'My Wrkouts Test': (browser) => {
browser.url('https://www.mywrkouts.com/');
// Check if the website logo is visible:
browser.expect.element('#barbell-homepage-top-image-desktop img.app-bar-desktop-logo').to.be.visible;
// Check the articles heading text:
browser.expect.element('h3.blog-carousel-title.primary-blue-text.center').text.to.contain('Foundational Education Series');
},
after(browser, done) {
browser.end(() => {
console.info('*--*--*--*--*--*--*--*--*--*--*--*--*');
console.info('*-- Clossing session... Good bye! --*');
console.info('*--*--*--*--*--*--*--*--*--*--*--*--*');
done();
});
}
};
Anyways, I feel you are confusing the way NightwatchJS/WebdriverIO/Protractor (or any other Webdriver-based test solution) is handling a browser session.
First off, you need not worry about closing the active session. Nightwatch does it for you at the end of each test feature-file. Thus, running a suit of let's say three test suites (login.js, register.js, forgot_password.js) will sequentially spawn & close three different browser sessions.
Also, browser.closeWindow() is only used for closing a window instance (taking into account that you have multiple windows associated with the same browser session). It won't close your main window, unless you have switched to another window instance (which was previously opened during your test run).
If you use browser.end() in the middle of your test, then you basically kill the active session, nullifying the following logic from your feature-file:
INFO Request: DELETE /wd/hub/session/4a4bb4cb1b38409ee466b0fc8af78101
- data:
- headers: {"Content-Length":0,"Authorization":"Basic Z29wcm86YmM3MDk2MGYtZGE0Yy00OGUyLTk5MGMtMzA5MmNmZGJhZTMz"}
INFO Response 200 DELETE /wd/hub/session/4a4bb4cb1b38409ee466b0fc8af78101 (56ms) { sessionId: '4a4bb4cb1b38409ee466b0fc8af78101',
status: 0,
value: null }
LOG → Completed command end (57 ms)
Everything after will look like this:
INFO Response 404 POST /wd/hub/session/null/elements (11ms) { sessionId: 'null',
value:
{ error: 'invalid session id',
message: 'No active session with ID null',
stacktrace: '' },
status: 6 }
!Note: There is no support for doing what you are trying to do, nor is it a common use-case, thus the lack of support for it across
all of these testing solutions.
They say a picture is worth 1000 words, so let's me simply put it this way... what you are trying to do is synonymous with the following:

Basic authentication with Selenium in Internet Explorer 11

I read Basic authentication with Selenium in Internet Explorer 10
And I change my register key and when I use the user and pass in the url I don't see the basic authentication popup, but actually the page is not load. I see blank page!
I see my url in the IE but nothing happened - I see white page.
Must I change somethin in IE too?
It is not possible without some workarounds.
I also needed the same feature and previous SO answer confirms, that is it either impossible or possible with high probability of failure.
One thing I learned about Protrator is not to try to make too complicated stuff with it, or I'll have a bad time.
As for the feature- I ended up making Protractor to initiate Node.js task, which use request to make the authentication and provide back the data.
Taken straight from request module:
request.get('http://some.server.com/').auth('username', 'password', false);
// or
request.get('http://some.server.com/', {
'auth': {
'user': 'username',
'pass': 'password',
'sendImmediately': false
}
});
// or
request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
// or
request.get('http://some.server.com/', {
'auth': {
'bearer': 'bearerToken'
}
});

Ajax call with basic authentication works on desktop butnot on device browser

I have a weird issue.. I am trying to call a REST URL which is secured with basic authentication over https but for some reason the call doesn't go through when I perform it from a mobile device (iPhone/iPad). When I remove the basic authentication from the service the call goes through with authentication it just times out.
When I try to debug it on my desktop it works fine .. does anybody have any idea why this wouldn't work?
My call looks like this:
var values = this.getLoginForm().getValues();
Ext.Ajax.request({
url : '/some/relative/url/',
method : 'GET',
username: values.username,
password: values.password,
success: function(response){
loggedIn = true;
Ext.Msg.alert('Success', 'Logged In');
},
failure : function(response) {
Ext.Msg.alert('Error', response.responseText);
}
});
I tried with relative URL and with absolute and there seems to be no difference.
I am using Sencha Touch 2.3.1.