How to POST a request with the urlencode mode? - cypress

I'm a beginner with cypress, and I'm trying to send a POST request with mode urlencode to get the access token. This is script in postman:
const postRequest = {
url: 'https://login.microsoftonline.com/967731f1/oauth2/v2.0/token',
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'urlencoded',
urlencoded:
[
{key: "client_id",value: "459e40d6-e96a-4c4e-833f-f43bd5d71885"},
{key: "scope",value: "api://icy-beach-05c371d10.1.azurestaticapps.net/459e40d6-e96a-4c4e-833f-f43bd5d71885/access-as-user"},
{key: "grant_type",value: "password"},
{key: "username",value: "abc#gmail.com"},
{key: "password",value: "xxxxxx"},
]
}
};
pm.sendRequest(postRequest, (error, response) => {
if (error) {
console.log(error);
}
pm.test('response should be okay to process', () => {
pm.environment.set("accesstoken_admin", response.json().access_token);
});
});
So, I do not know how to work on cypress. Does anyone help me? Many thanks!

/// <reference types="cypress"/>
describe('login and create a new client',()=>{
it('login by admin account',() => {
cy.request({
method: 'POST',
url:'https://login.microsoftonline.com/967731f1/oauth2/v2.0/token',
form: true,
body: {
client_id: "459e40d6-e96a-4c4e-833f-f43bd5d71885",
scope: "api://icy-beach-05c371d10.1.azurestaticapps.net/459e40d6-e96a-4c4e-833f-f43bd5d71885/access-as-user",
grant_type: "password",
username: "abc#gmail.com",
password: "xxxxxx",
}
}).then((res) => {
cy.log(JSON.stringify(res))
})
})
})

Related

How/Where does nuxtjs set the authorization header

I inherited a web project from another developer who's left the company. It is built with nuxtjs and laravel, neither of which I am strong with.
In the web project, after a user goes to a login screen, types in email and password, and presses save, I can see in my developer tools that the nuxtjs framework sends a {email: "user#email.com", password: "password"} to the laravel api at https://example.project.com/api/login. The laravel api then returns a 200 response with this payload { data: { message: "Login successful.", token: "50|Fs88RPU7HON1LnBskm35O9txG0OnXDiG3x4XWILJ" }}. Everything is great so far!
Immediately after the 200 response above, NuxtJS sends another request to https://example.project.com/api/auth/user in an attempt to get information about this user. Nginx gives a 401 response. My first suspicion for why this happens is because NuxtJS sent an Authorization: Bearer undefined as shown in this screenshot of my browser dev tools
I've seen other situations with Authorization: Bearer [object object].
I want to know how does NuxtJS decide what value to provide to the Authorization http header? This is my current nuxt.config.js
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'Blah',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.png' }],
},
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'#nuxtjs/auth'
],
auth: {
redirect: {
login: '/login',
logout: '/',
callback: '/api/login',
home: '/'
},
strategies: {
local: {
endpoints: {
login: { url: '/api/login'},
user: { url: '/api/auth/user'}
},
}
},
localStorage: true
},
proxy: {
'/api': {
target: 'https://example.project.com/',
pathRewrite: { '^/api': '' },
},
},
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
baseURL: 'https://example.project.com/',
credentials: true,
headers : {
common: {
'Accept' : 'application/json'
}
}
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
}
}
And also, this is the line of code in pages/login.vue that starts the login process:
await this.$auth.loginWith('local', { data: {email:"user#email.com",password:"password"} });
Simply add Authorization header as default header right after authorization request. Assuming that server sends access token in response the code might look like this:
const response = await this.$auth.loginWith('local', {
data: {
email: "user#email.com",
password:"password"
}
})
const { token } = response;
axios.defaults.headers.common = { Authorization: `Bearer ${token}` };
change your strategy as below to set property name of the token being returned in response.
strategies: {
local: {
token: {
property: 'token'
},
endpoints: {
login: { url: '/api/login'},
user: { url: '/api/auth/user'}
},
}
},
It will include the authorization header in all your requests using $axios.
also you might need to set propery of the user which you are returning from backend also.
This is done by a library in the background. #nuxtjs/auth or #nuxtjs/auth-next will set the token depending on your config in nuxt.config.ts.
You can find the token in the local storage in auth._token.<strategy>. To use a Bearer token in the subsequent userinfo request you might need to set:
nuxt.config.ts
auth: {
strategies: {
local: {
token: {
type: 'Bearer',
}
}
}

Need to return the response from .then() in cypress

I am trying to return the value of .then() and trying to use in another method but I am getting an error and couldn't do that. Please help me with this.
Is there any other way for returning this
test () {
var a = cy.request({
method: 'POST',
form: true,
url: 'https://......../token',
headers: { "Accept": "application/json, text/plain, /", "referer-domain": referer_domain, "Content-Type": "application/json;charset=UTF-8" },
body: {
"client_id": "..",
"client_secret": "....",
"username": username,
"password": password,
"grant_type": "password",
"scope": ""
}
})
.then(response => { return response })
return a;
}
If you want to return it as a chainable value of the function use cy.wrap()
cy.get('someElement')
.then(element => {
//some code
return cy.wrap('the value or action I need to retun)
}
.then(returnedValue => {
some code that can use it
}
If you want to access it as a variable in the code later you can use as()
cy.get('someElement')
.then(element => {
//some code
cy.wrap(result).as('resultAllias')
}
cy.get('#resultAllias')
.then(result => {
//some code to use the result
}
I know this question is old, but in case anyone comes across this question like I did, the issue is you're writing synchronous code against Cypress functions that are async.
The .then() callback attached to your cy.request() is going to be executed long after your function already returned, thus it will always result in var a being undefined.
The proper way to return the response it to simply return the cy.request() function and to use the .then() callback in the test to interact with the response.
test () {
// var a = cy.request({
return cy.request({
method: 'POST',
form: true,
url: 'https://......../token',
headers: { "Accept": "application/json, text/plain, /", "referer-domain": referer_domain, "Content-Type": "application/json;charset=UTF-8" },
body: {
"client_id": "..",
"client_secret": "....",
"username": username,
"password": password,
"grant_type": "password",
"scope": ""
}
})
// .then(response => { return response })
// return a;
}
// Test code
it('works', () => {
test().then(response => /* utilize the response here */);
});

axios request on google cloud functions using express

I'm calling a payment gateway rest API to retrieve a QR code.
It works well in my local with ajax but impossible to make it work with axios on a firebase cloud functions (express on nodejs).
My ajax code in my local:
var dataReq = {
amount: '1',
referenceNo: 'chelou',
token:'myToken',
payType: 'F',
backgroundUrl: 'myBackgroundurl',
customerEmail: 'dgdfgdgdgd'
};
$.ajax({
type: "POST",
url: "https://api.gbprimepay.com/gbp/gateway/qrcode/text",
data: dataReq,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
success: function(dataResp){
console.log(dataResp)
},
failure: function(errMsg) {
console.log(errMsg);
}
});
});
My axios code in firebase cloud function:
axios({
method: 'post',
url: 'https://api.gbprimepay.com/gbp/gateway/qrcode/text',
headers: {"Content-Type": "application/x-www-form-urlencoded"},
data: {
amount: '1',
referenceNo: 'chelou',
token:'hW7RBDVpELvpxIJAxYf6AXl7ESXIWWOekGO/28aDCYkV7m07Fs26ko4QyROTFLNCZbRandtw5mxCgnQBtGdw5vYt5bkvmiZXi460Cc3yYWvNaE8LyEZJ1TdNJsX0poTwT9gb3hmy9JNdrxMB5HEwkjC9P18=',
payType: 'F',
backgroundUrl: 'https://us-central1-wyzauto.cloudfunctions.net/widgets/changeOrderStatus',
customerEmail: 'dgdfgdgdgd'
}
})
.then((response) => response.data)
.then((responseFinal) => {
return res.json(responseFinal);
})
.catch(error => {
return res.json({result: error});
})
});
The ajax code is returning
{referenceNo: "chelou", qrcode: "00020101021230830016A00000067701011201150105560068…chelou530376454041.005802TH5910GBPrimePay6304192E", resultCode: "00", gbpReferenceNo: "gbp352913431029"}
The axios code is returning {"resultCode":"90"} it's not an error but for some reason the qr code is not being computed
Do you see anything wrong with my header or something like that?!?

Get a 401 error with POST and PUT Laravel passport/Vue/Axios

I am working on a Vue application with a seperate Laravel back-end API. The back-end has Laravel passport that requires an access token when doing database calls.
Normally everything goes right, I can get data back from the database but for some reason, 2 of my calls gets errors, the POST en PUT. I don't know why I get unauthenticated (401) from laravel passport back, while my get request is going well. Also, both POST and PUT are going fine in the postman application.
The get request
getSuppliers() {
axios.get(`${this.$API_URL}/api/v1/relations`, {
headers: this.headers,
})
.then((response) => {
this.loaded = true;
this.relations = response.data.data;
})
.catch(error => console.log(error));
},
The post request
axios.post(`${this.$API_URL}/api/v1/relations`, {
headers: this.headers,
data: {
company_name: this.supplier.company_name,
language_id: this.supplier.language_id,
supplier_type_id: this.supplier.supplier_type_id,
email: this.supplier.email,
website: this.supplier.website,
recognition_number: this.supplier.recognition_number,
street: this.supplier.street,
house_number: this.supplier.house_number,
zipcode: this.supplier.zipcode,
city: this.supplier.city,
country: this.supplier.country,
},
})
.then((response) => {
console.log(response);
// retrieve the id
// push the user to the show of the retrieved id
})
.catch(error => console.log(error));
Helper functions for access token
function getHeaders(token) {
return {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
};
}
function getToken() {
const oauth = JSON.parse(localStorage.getItem('oauth') || '{}');
if (oauth.access_token) {
return oauth.access_token;
}
return false;
}
Somebody out there that had the same problem or similair?
After some digging, going through my other code and requests I find a solution that fixed it for me.
Instead of
axios.post(`${this.$API_URL}/api/v1/relations`, {
headers: this.headers,
data: {
company_name: this.supplier.company_name,
language_id: this.supplier.language_id,
supplier_type_id: this.supplier.supplier_type_id,
email: this.supplier.email,
website: this.supplier.website,
recognition_number: this.supplier.recognition_number,
street: this.supplier.street,
house_number: this.supplier.house_number,
zipcode: this.supplier.zipcode,
city: this.supplier.city,
country: this.supplier.country,
},
})
.then((response) => {
console.log(response);
// retrieve the id
// push the user to the show of the retrieved id
})
.catch(error => console.log(error));
I had to do
axios({
method: 'post',
url: `${this.$API_URL}/api/v1/relations`
headers: this.headers,
data: {
company_name: this.supplier.company_name,
language_id: this.supplier.language_id,
supplier_type_id: this.supplier.supplier_type_id,
email: this.supplier.email,
website: this.supplier.website,
recognition_number: this.supplier.recognition_number,
street: this.supplier.street,
house_number: this.supplier.house_number,
zipcode: this.supplier.zipcode,
city: this.supplier.city,
country: this.supplier.country,
},
})
.then((response) => {
console.log(response);
// retrieve the id
// push the user to the show of the retrieved id
})
.catch(error => console.log(error));
I don't see any difference except the style, so I don't know exactly why the second style is working and the first one is not, especially for the put and post type of requests.

Extjs 5 ajax PUT and DELETE methods throw 403 errors (csrf token included)

I am building a web application with django-rest-framework and extjs5.
Obviously i faced problems with django's csrf token, which i had to inlude in Extjs's Ajax requests.
But while i implemented POST method successfully, it seems that my implementation doesn't work for PUT and DELETE method.
My POST method code:
onSaveRecordBtnClick: function(){
Job_Name = this.lookupReference('Job_Name').getValue();
var csrf = Ext.util.Cookies.get('csrftoken');
Ext.Ajax.request({
url: '/jobs_api/job/',
method: "POST",
params: {
Job_Name: Job_Name,
'csrfmiddlewaretoken': csrf
},
success: function(conn, response, options, eOpts) {
var result = MyApp.util.Util.decodeJSON(conn.responseText);
if (result.success) {
alert('Job Submission Successfull');
}
else {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
});
}
This works perfectly, but when i try PUT or DELETE method i keep getting:
Request Method:DELETE
Status Code:403 FORBIDDEN
{"detail":"CSRF Failed: CSRF token missing or incorrect."}
My DELETE method:
onJobDblClick : function(grid, record, index, eOpts) {
var job_id = record.id;
var csrf = Ext.util.Cookies.get('csrftoken');
Ext.Ajax.request({
url: '/jobs_api/job/' + job_id + '/',
method: "DELETE",
params: {
'id': job_id,
'csrfmiddlewaretoken': csrf
},
success: function(conn, response, options, eOpts) {
var result = MyApp.util.Util.decodeJSON(conn.responseText);
if (result.success) {
alert('Job Deleted Successfully');
}
else {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
});
}
My job model is:
Ext.define('MyApp.model.Job', {
extend: 'MyApp.model.Base',
fields: [
{ name: 'id', type: 'int' },
{ name: 'Job_Name', type: 'string' },
],
proxy: {
type: 'rest',
url: '/jobs_api/job/',
reader: {
type: 'json',
rootProperty: 'data'
}
}
});
I don't know why this is happening. Please help!!

Resources