How to test for access prohibited in Cypress? - automated-tests

How do I test that if I try to visit a page that I'm not authorised for I get a 403 response?
This is what I'm trying so far:
cy.visit('/sys-ops')
cy.location('pathname').should('eq', '/error/unauthorized')

You could use something like this
describe('showcase Cypress request', () => {
it('checks for 403', () => {
cy.request({
url: '/my-unauthorized-url',
followRedirect: false,
failOnStatusCode: false
}).then((resp) => {
expect(resp.status).to.eq(403)
})
})
})
Find more details here https://docs.cypress.io/api/commands/request#Request-a-page-while-disabling-auto-redirect

Related

Next-auth prevent redirecting when credentials are incorrect [duplicate]

I'm using NextAuth.js for Next.js authentication. Login works fine, but the page is still reloading on wrong credentials. It doesn't show any error. I need to handle error to show some kind of toast message.
signIn("credentials", {
...values,
redirect: false,
})
.then(async () => {
await router.push("/dashboard");
})
.catch((e) => {
toast("Credentials do not match!", { type: "error" });
});
When passing redirect: false to its options, signIn will return a Promise that always resolves to an object with the following format.
{
error: string | undefined // Error code based on the type of error
status: number // HTTP status code
ok: boolean // `true` if the signin was successful
url: string | null // `null` if there was an error, otherwise URL to redirected to
}
You have to handle any errors inside the then block, as it won't throw an error.
signIn("credentials", { ...values, redirect: false })
.then(({ ok, error }) => {
if (ok) {
router.push("/dashboard");
} else {
console.log(error)
toast("Credentials do not match!", { type: "error" });
}
})

Cypress reutrns 302 instead of 200

I was trying to test sign-in page of our app. I am using cypress to test Vuejs frontend works with AspNet Api. When I click on the signin button on chrome it makes following requests and visits the homepage "localhost:44389"
first request from Chrome
second request from Chrome
if I want to simulate it on cypress it sends same request but get 302 from second request instead of 200.
first request from Cypress
second request from Cypress
Can someone help me to find out the problem?
Cypress.Commands.add('IdentityServerAPILogin', (email, password) => {
console.log("SERVER_URL is called. Server: " + Cypress.env('SERVER_URL'));
cy.request({
method: 'GET',
url: Cypress.env('SERVER_URL'),
failOnStatusCode: false,
headers: {
'Cookie': '...coookies...'
}
})
.then(response => {
if (response.status == 401){
console.log ("Check for NOnce");
console.dir(response, { depth: null });
const requestURL = response.allRequestResponses[1]["Request URL"]
console.dir(requestURL, { depth: null })
//const signInPage = (response.redirects[0]).replace('302: ', '');
const signInPage = (response.redirects[1]).replace('302: ', '');
console.log("signInPage:" + signInPage);
const nOnceObj = response.allRequestResponses[0]["Response Headers"];
console.dir(nOnceObj, { depth: null });
const nOnce = nOnceObj["set-cookie"][0];
console.log("Nonce:" + nOnce);
cy.visit({
method: 'GET',
url: signInPage,
failOnStatusCode: false,
headers: {
//'Cookie': nOnce
}
})
// TODO: Create all needed tests later to test sign in
cy.get('#username').type(email)
cy.get('#password').type(password)
// TODO: Waiting for to click signIn button. When I call the click() method I get infinite loop!!
cy.get('.ping-button')
// .click()
// .then((response_login) => {
// console.log("Status REsponse_Login: "+ response_login);
// console.dir(response_login, { depth: null });
// if (response_login.status == 401){
// cy.visit(Cypress.env('SERVER_URL'))
// }
// })
}else
cy.visit(Cypress.env('SERVER_URL'))
})
console.log("vorbei");
});
Just figured out Cypress is not able to get Cookies from .../signin-oidc, because there is an error as in the photo below
Asking kindly for a solution. I am not allowed to make changes on authorization service. Looking for a possibility around cypress.

Fetching resources from google analytics services using HTTPS by Wix fetch function

How should I fetch data using Wix-fetch function?
I followed this google analytics API tutorial, this tutorial using post function for getting JSON data, I used WIX fetch function to get JSON file, but the return object is undefined.
What did I miss?
fetch( "https://accounts.google.com/o/oauth2/token", {
"method": "post",
"headers": {
"Content-Type": 'application/x-www-form-urlencoded'
},
'body' : JSON.stringify({
'grant_type': 'authorization_code',
'code': URLCode,
'client_id': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
'client_secret': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'redirect_uri': 'https://www.mydomain.or/ga/oauth2callback'
})
} )
.then( (httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
} )
.then( (json) => console.log(json.someKey) )
.catch(err => console.log(err));
UPDATE
STEP 1
I used this URL to generate the CODE
wixLocation.to("https://accounts.google.or/o/oauth2/auth?scope=https://www.googleapis.com/auth/analytics%20https://www.googleapis.com/auth/userinfo.email&redirect_uri=https://www.mydomain.or/ga/oauth2callback/&access_type=offline&response_type=code&client_id=XXXXXXXXXXXXXXXXXX")
I get the CODE from the callback URL
Step 2
I used this code for the HTTP postman request
The redirect URI in step 1 and 2 is the following (the second one):
Step 1:
There needs to be an exact match between the redirect URI configured in the client id in the google developers console and the URL to get the code authorization.
The URL should be built as shown in the tutorial you linked (if you need a refresh token, you can add the access_type=offline)
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/analytics&redirect_uri=<redirect_uri>&response_type=code&client_id=<client_id>
After you enter the URL, you will be provided with an authorization window. Once you authorize, you will be redirected to the <redirect_uri> you provided earlier. You will find the code as the first parameter in the URL query. e.g. <redirect_uri>/?code=<auth_code> ...
Since the access token is for one-time use only, if you will need it again, you will have to get a new <auth_code>.
Step 2 (Postman query example):
If you got the access_token correctly and you want to check now with WIX. Get a new <auth_code> (as said, the access token is given once) and set the code as follows:
import { fetch} from 'wix-fetch';
$w.onReady(function () {
const data = `grant_type=authorization_code&code=<your_authorization_code>&client_id=<your_client_id>&client_secret=<your_client_secret>&redirect_uri=<your_redirect_uri>`;
fetch("https://accounts.google.com/o/oauth2/token", {
"method": "post",
"headers": {
"Content-Type": 'application/x-www-form-urlencoded'
},
'body': data
})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
})
.then((json) => console.log(json.access_token))
.catch(err => console.log(err));
});

basic authentication does not work for local testing with cypress

I am developing a web app that requires windows credential. To test it locally during developing, I decide to try cypress.io. However, I cannot make it work. I always got an 401-unauthorized error. Here are some codes that I have used for my testing. Thanks for your help.
method 1:
describe('My First Test', function() {
it('Visits the Kitchen Sink', function() {
cy.visit('http://localhost:8080/')
})
})
method 2:
describe('My First Test', function() {
it('test website loading', function() {
cy.visit('http://localhost:8080/',{
auth: {
username:'myusername',
password:'myassword'
}
})
})
})
method 3: overwrite command
Cypress.Commands.overwrite('visit', (orig, url, options) => {
options = options || {}
options.auth = {
username: 'username',
password: 'password',
}
return orig(url, options)
})

angular2 How to store response header data from http.get in extra variable?

I'm quite new to Angular 2 and Typescript and want to build a Card-Search App.
Basically I have a component where the response data is stored and observed...
this.searchFormGroup.valueChanges
.debounceTime(200)
.distinctUntilChanged()
.switchMap(searchFormGroup => this.mtgService.getCardsByName(searchFormGroup))
.subscribe(
searchResult => {
this.searchResult = searchResult.cards;
},
err => {
console.log(err);
});
...and a service, which sends the http.get request to the API ...
getCardsByName(searchFormGroup){
this.params.set(...) ...
return this.http.get(this.nameUrl, { search: this.params })
.map(res => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'))}
... communicating with each other.
What's the best way to store header-data from the request inside the component? Basically I need the total card-count and paging-links of the request, which are available inside the response header. I've been trying to find a solution to this for hours :o
Ok try and error got me a solution to this problem:
component activated service's http.get -> service responded with res.json() -> component only got res in JSON, what seems to delete the response header.
My workaround is:
Component:
this.searchFormGroup.valueChanges
.debounceTime(200)
.distinctUntilChanged()
.switchMap(searchFormGroup => this.mtgService.getCardsByName(searchFormGroup))
.subscribe(
res => {
console.log(res.headers); //works fine now!
this.searchResult = res.json().cards;
},
err => {
console.log(err);
});
Service:
getCardsByName(searchFormGroup){
this.params.set(...) ...
return this.http.get(this.nameUrl, { search: this.params })
.catch((error:any) => Observable.throw(error.json().error || 'Server error')) }
So the full res gets passed back to the component now.
However: any tips to make this better?

Resources