Cypress - test redirect - cypress

I have a local endpoint that checks if I'm logged in and if yes, it generates token and redirects me to another API endpoint. I want to test the redirection however, I'm ending with the following error:
cy.visit() failed trying to load:
http://getmantaportal.test/authorize/
The response we received from your web server was:
> 403: Forbidden
This was considered a failure because the status code was not 2xx.
This http request was redirected '1' time to:
- 302: https://example.com/api/?token=eyJ0eXAiOiJKV1QiL
Here is my code:
it('Redirect to Manta Edge if already logged in.', function () {
// Login first.
// [...]
// Go to the endpoint and get redirected immediately.
cy.visit('/authorize/')
cy.url().should('contain', '/api/?token=')
})
Thanks a lot in the advance.

Use nested cy.request calls, you'll need to know all redirects you will get to be authenticated.
See the hypothetical example below.
cy.request({
method: "POST",
url: `YOUR FIRST URL`,
headers: {},
body: {
username: YOUR_USERNAME,
password: YOUR_PASSWORD
},
}).then(function (response) {
var body = response.body;
cy.request({
method: "GET",
url: `YOUR SECOND URL`,
auth: {
bearer: body.access_token,
},
}).then(function (response) {
cy.request({
method: "POST",
url: `YOUR THIRD URL IF EXISTS`,
auth: {
bearer: body.access_token,
},
}).then(function (response) {
response.headers
// If necessary, get the cookies to finish the authentication
});
});

Related

Can I log to file all the responses made during running cypress test?

When I'm running cypress e2e tests, application makes XHR requests. How can I log all this requests and responses? I don't want to stub these requests. I with to get an artifact with all requests and responses made during test. Gitlab is used as CI.
Main test code looks like this. All these are user defined commands, interacting with the application. Interacting with the application causes different requests to be made (e.g. I click a button, this causes the request).
it('Log response to a file',function(){
cy.request({
method: 'GET',
url: 'https://<site>/home/payments/currency/confirm/*',
headers: {
'Content-Type': 'application/json',
},
body: {},
}).then((response)=>{
const someResponse = response.body;
console.log("hhhh"+someResponse);
cy.writeFile('cypress/fixtures/testResponse.json', someResponse);
cy.login(login_name, pass)
cy.typeOTPpinpad(secret)
cy.makePayment('Currency', 'amount')
cy.typeToken(secret)
cy.logout()
})
})
Here is how I tried to use regular expression to catch request (id is unique and I need to use regular expressions).
https://<mysite>/home/payments/<currency>/confirm/* - asterisk is payment id.
You could grab the request and response and write to a location as below. I have write the request and response to fixture folder as below: Try the below and let me know
it('Log request to a file',function(){
cy.request({
method: 'GET',
url: 'url_here',
headers: {
'Content-Type': 'application/json',
},
body: {},
}).then((request)=>{
const someRequest = JSON.stringify(request);
console.log("hhhh"+someRequest);
cy.writeFile('cypress/fixtures/testRequest.json', someRequest);
})
})
// The below is for response:
it('Log response to a file',function(){
cy.request({
method: 'GET',
url: 'url_here',
headers: {
'Content-Type': 'application/json',
},
body: {},
}).then((response)=>{
const someResponse = response.body;
console.log("hhhh"+someResponse);
cy.writeFile('cypress/fixtures/testResponse.json', someResponse);
})
})
The testrunner has such information on board:
[

get the information from Naver LINE API through http request

I have a question on the chat app, Naver LINE. There is an API that provides login authentication called LINE login.
I've follow the instructions on the documents and run the querystring and I got a callback URL that gives me the code look like this,
https://sample.com/callback?code=b5fd32eacc791df&state=123abc
Now, the document says I need to use the code in a http request using post method. I got the following,
XMLHttpRequest cannot load https://api.line.me/v1/oauth/accessToken/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://xxxxxxxxxxxxxxxxxxxxxxxxxxx' is therefore not allowed access. The response had HTTP status code 404.
Below is the request I wrote,
$.ajax({
url: "https://api.line.me/v1/oauth/accessToken/",
type: "POST",
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: JSON.stringify(data),
dataType: "json",
success: function (response) {
var resp = JSON.parse(response)
alert(resp.status);
},
error: function (xhr, status, state, error) {
alert("error", xhr, status);
console.log(xhr);
console.log(status);
console.log(state);
console.log(error);
}
});
data is the credentials I put in so LINE would pass me the user's information.
Is there anything I did wrong? If so, how can I fix this?
Thanks ahead.

Google OAuth 2 authorization: got Error redirect_uri_mismatch using ajax p

I already set the Authorized redirect URI on Google API Concole as below show.
Google console API Setting
I used localhost:64420/index to get the code, and send the code to localhost:64420/Auth to used ajax post parameter try to get the access token.
Sadly, I got the error message:
{error: "redirect_uri_mismatch", error_description: "Bad Request"}
Here is the script:
<script>
var code = code;
var clientID = client_ID;
var clientSecret = client_Secret;
var redirect_uri = "http://localhost:64420/Report.aspx";
var searchurl = "https://www.googleapis.com/oauth2/v4/token";
$.ajax({
dataType: "json",
url: searchurl,
data: { code: code, client_id: clientID, client_secret: clientSecret, redirect_uri: redirect_uri, grant_type: 'authorization_code' },
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
crossDomain: true,
cache: true,
success: function (data) {
alert(data);
},
error: function (jqXHR, exception, errorstr) {
console.log(jqXHR);
alert(errorstr);
}
});
</script>
The redirect URL in your app and the redirect URL you configure in the API console must be an exact character-for-character match. Remember you can configure multiple redirect URLs in the APi Console, so don't be shy and add all possible variants, eg with both http and https. You should really be using https for a redirect URL and I wouldn't be surprised if a future change disallowed plaintext URLs.

Getting blocked response even if status code 200 is returned

I have MVC web app and I am consuming some WEB API with AJAX calls. I try to login, so I send username and password, to get the needed info (token etc.).
var loginData = {
grant_type: 'password',
username: 'SomeName',
password: 'SomePass'
};
$.ajax({
type: 'POST',
url: '/Token',
contentType: "application/x-www-form-urlencoded; charset='utf-8'",
data: loginData,
success: function (response) { // 200 Status Header
localStorage.setItem('token', response.access_token);
alert('Success!');
},
error: function (response) { // 500 Status Header
alert('Error!');
}
});
The problem is - After the request is send, the server returns the response with all the informations, but it is somehow blocked.
It returns status code - 200 with all the information but the response is blocked/aborted
Session properties (provided by Fiddler)

Request headers not passed when proxying with Apache HTTPD server

I have set up a proxy on Apache HTTP server for making the cross domain Ajax call. The call is happening but is returning a response indicating that the API key passed as a request header is invalid.
Can you make cross domain Ajax calls using Apache web server proxy? If so what am I doing wrong. ?
The proxy setting is as follows:
ProxyPass /api-temp/* http://api.temp.com/
The code to make the Ajax call is as follows:
var imageNamespace = {
imageUrls: [ ],
url: '/api-temp/v1/data/cat/42736286',
test: function() {
alert(234);
},
getImages: function() {
$.ajax({
type: 'GET',
dataType: 'json',
cache: true,
headers: {'API_KEY': 'xxxxxxxxxxxxxxxxxxxxxxxxx'},
url: imageNamespace.url,
success: function () {
alert('success:', success);
},
error: function (error) {
alert('ERROR:', error);
},
complete: function () {
alert('complete');
}
});
},
}
Here is the response in the browser:
The URL it is invoking is as follows: http://api.temp.com/v1/data/cat/42736286
Please enter valid API Key
I am passing the key in the request header but it is not being picked up. Any insight on how to resolve this will be helpful.

Resources