Django - Post ajax request forbidden 403 with ExtJS - ajax

I am using ExtJs to create a button that do an ajax post to my django application, but the post is blocked by a FORBIDDEN (403) error.
I tryed to pass the CSRF token in as POST data by setting a custom X-CSRFToken header to the value of the CSRF token (https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#ajax) without success
ExtJS.js
action = new Ext.Button({
text: 'Ajax Test',
handler: function () {
Ext.Ajax.request({
url: 'test/',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
params: {'test': 'test'},
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure');
}
});
},
});
view.py
def test(request):
print "TEST WORKING"
print dict(request.POST.copy().iteritems())
return HttpResponse("")
CHROME NETWORK TAB:
Response:
CSRF verification failed. Request aborted.
Cookies:
Request Cookies:
csrftoken : S7uLgmhqeprWqL4NdH9mznIfpTgyM9RP
djdt : hide
djdttop : 30
sessionid : sx4ukmkitqp39wvuve1a9zed2kjiwfb1
Response Cookies:
(empty)
Headers:
Request URL:http://127.0.0.1:8000/basqui/layer/edit/2/test/
Request Method:POST
Status Code:403 FORBIDDEN
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:9
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:sessionid=sx4ukmkitqp39wvuve1a9zed2kjiwfb1; csrftoken=S7uLgmhqeprWqL4NdH9mznIfpTgyM9RP; djdttop=30; djdt=hide
Host:127.0.0.1:8000
Origin:http://127.0.0.1:8000
Referer:http://127.0.0.1:8000/basqui/layer/edit/2
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
test:test
Response Headersview source
Content-Type:text/html
Date:Tue, 07 Jan 2014 16:52:15 GMT
Server:WSGIServer/0.1 Python/2.7.5
X-Frame-Options:SAMEORIGIN

action = new Ext.Button({
text: 'Ajax Test',
handler: function () {
var csrf = Ext.util.Cookies.get('csrftoken');
Ext.Ajax.request({
url: 'test/',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
params: {'test': 'test', 'csrfmiddlewaretoken': csrf},
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure');
}
});
},
});

https://www.sencha.com/forum/showthread.php?134125-Django-1-3-Login-with-ExtJS-4-and-CSRF
I put this in my Application launch function:
Ext.require(["Ext.util.Cookies", "Ext.Ajax"], function(){
// Add csrf token to every ajax request
var token = Ext.util.Cookies.get('csrftoken');
if(!token){
Ext.Error.raise("Missing csrftoken cookie");
} else {
Ext.Ajax.defaultHeaders = Ext.apply(Ext.Ajax.defaultHeaders || {}, {
'X-CSRFToken': token
});
}
});

Related

502 bad gateway error for cross-origin request

I am using the serverless framework to deploy my lambda to AWS and have been able to successfully run POST requests via Postman to the API Gateway associated with my lambda function, but when I try run a POST request from a form submission (AJAX request) on a local server I am receiving the 502 error message,
Access to XMLHttpRequest at 'https://*id*.execute-api.us-east-1.amazonaws.com/prod/message' from origin 'http://localhost:2368' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
which I didn't expect since I have the cors property in my serverless.yml set to true, which sets CORS configurations for the HTTP endpoint. Here is the function yaml setup:
functions:
email:
handler: handler.sendEmail
events:
- http:
path: message
method: post
cors: true
Here is the jQuery AJAX request:
$.ajax({
type: 'POST',
url: 'https://*id*.execute-api.us-east-1.amazonaws.com/prod/message',
crossDomain: true,
data: JSON.stringify(formData),
contentType: 'application/json',
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
console.log(ajaxOptions);
console.log(thrownError);
}
});
Is there something that I need to adjust with the API Gateway configuration or within my Lambda application?
Here is my response function:
const generateResponse = (body, statusCode) => {
console.log("generateResponse")
console.log(body)
return Promise.resolve({
headers: {
"access-control-allow-methods": "POST",
"access-control-allow-origin": "*",
"content-type": "application/json",
},
statusCode: statusCode,
body: `{\"result\": ${body.message}}`
});
};
Also provided is the ajax request:
$.ajax({
type: 'POST',
url: 'https://*my-lambda-id*.execute-api.us-east-1.amazonaws.com/prod/message',
crossDomain: true,
data: JSON.stringify(formData),
contentType: 'application/json',
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
console.log(ajaxOptions);
console.log(thrownError);
}
})
And the resulting OPTION and POST Request and Response Headers triggered by the AJAX:
OPTIONS:
Request URL: https://*my-lambda-id*.execute-api.us-east-1.amazonaws.com/prod/message
Request Method: OPTIONS
Status Code: 200
Response Headers
access-control-allow-credentials: false
access-control-allow-headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent
access-control-allow-methods: OPTIONS,POST
access-control-allow-origin: http://localhost:2368
content-length: 1
content-type: application/json
date: Tue, 08 Oct 2019 11:11:36 GMT
status: 200
via: 1.1 *id*.cloudfront.net (CloudFront)
x-amz-apigw-id: *id*
x-amz-cf-id: *id*
x-amz-cf-pop: *id*
x-amzn-requestid: *id*
x-cache: Miss from cloudfront
Request Headers
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://localhost:2368
Referer: http://localhost:2368/
Sec-Fetch-Mode: no-cors
POST
Request URL: https://*my-lambda-id*.execute-api.us-east-1.amazonaws.com/prod/message
Request Method: POST
Status Code: 502
Request Headers
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json
Origin: http://localhost:2368
Referer: http://localhost:2368/
Sec-Fetch-Mode: cors
Wherever you return a response from your Lambda function you need to include the specific header CORS requests. The cors: true option you add to serverless.yml only helps make sure that the OPTIONS pre-flight requests work. Don't forget that this includes non-success responses as well.
For example:
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Headers': 'Authorization'
}
}

How to send push notifications in Chrome(Progressive Web Apps)

Please explain how to do push notifications with XHR and Javascript. or is there any other way to send push notifications in progressive web apps. I have created curl command and when i execute it in my terminal push notification sent but how to do it on button click?
Here is my cURL command:-
curl --header "Authorization: key=AIzaSxUdg" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"cxA-dUj8BTs:APAvGlCYW\"]}"
This is what i have tried :-
function send()
{
navigator.serviceWorker.ready
.then(function(registration) {
registration.pushManager.getSubscription()
.then(function (subscription) {
curlCommand(subscription);
$.ajax({
url: "https://android.googleapis.com/gcm/send",
headers: {
Authorization: "key=AIzaSxUdg",
},
contentType: "application/json",
data: JSON.stringify({
"registration_ids": [endpoint]
}),
xhrFields: {
withCredentials: true
},
crossDomain: true,
type:"push",
dataType: 'json'
})
.done(function() {
alert('done');
})
.fail(function() {
alert('err');// Error
});
})
})
}
But it shows error -----
XMLHttpRequest cannot load https://android.googleapis.com/gcm/send. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8880' is therefore not allowed access..
Google API is intended to be used from a server so it is not including CORS headers.
As you are performing a cross origin XHR (from your domain to Google's domain), the User Agent makes a preflight request in search of the CORS headers that tell your client is authorized to perform operations.
To do this you need to make a request to your server (i.e. a POST on /notifications/send) and your server should then execute the cURL request to GCM.
This will work:
function send()
{
navigator.serviceWorker.ready
.then(function(registration) {
registration.pushManager.getSubscription()
.then(function (subscription) {
curlCommand(subscription);
$.ajax({
url: "https://cors-anywhere.herokuapp.com/https://android.googleapis.com/gcm/send",
headers: {
Authorization: "key=AIzaSxUdg",
},
contentType: "application/json",
data: JSON.stringify({
"registration_ids": [endpoint]
}),
xhrFields: {
withCredentials: true
},
crossDomain: true,
type:"push",
dataType: 'json'
})
.done(function() {
alert('done');
})
.fail(function() {
alert('err');// Error
});
})
})
}

angular js http request from aspx method

I have a page locations.aspx that has a method behind it in locations.aspx/getData. when I use the code
$http.jsonp($scope.url)
.success(function (data, status, headers, config) {
alert(data);
}).error(function (data, status, headers, config) {
$scope.status = status;
});
with the $scope.url being locations.aspx/getData it loads the html page of the aspx page but doesn't access the method. I can access the method using
$.ajax({
type: "POST",
url: $scope.url,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (p) {
var temp = $.parseJSON(p.d);
$scope.allItems.push(temp);
},
error: function () {
alert('error');
}
});
but the data never updates or binds on the view side. An example on the html is
<select ng-model="selectLocation" id="selectLocation" ng-change="onLocationChange()">
<option></option>
<option ng-repeat="l in allItems">{{l.location}}</option>
</select>
After the ajax call allItems array does have an item in it but the view never updates.
My ajax call headers are
Request URL:localhost:41796/locations.aspx/getData
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, /; q=0.01
Content-Type:application/json; charset=utf-8
Response Headersview source
Cache-Control:private, max-age=0
Connection:Close
Content-Length:270
Content-Type:application/json; charset=utf-8
and my $http headers are
Request URL:localhost:41796/locations.aspx/getData
Request Method:GET
Status Code:200 OK
Request Headersview parsed
GET /locations.aspx/getData HTTP/1.1
Host: localhost:41796
Connection: keep-alive
Response Headersview parsed
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 7177
Connection: Close
Based on the discussion above, it seems you're using ASP.NET and running into specific issues with it.
ASP.NET can be pretty picky sometimes about what it will parse and what it won't -- especially when it comes to MVC (which it doesn't appear that you're using here, but perhaps [WebMethod] (what I assume you're using) has the same kinds of issues).
Instead of messing with jQuery's $.ajax, you can use Angular's $http in the same way:
$http({
method: 'POST',
url: $scope.url,
contentType: 'application/json; charset=utf-8'
})
.success(function (data, status, headers, config) {
alert(data);
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
Check this: http://docs.angularjs.org/api/ng.$http#Parameters for more information.

400 bad request error using ajax

I am using ajax to call a webservice. But when i check the ouput in firebug i get 400 bad request error. Can you please tell me why do i get the error. Why do i get the error. Is anything wrong in following code.Following is the code i have written:
<script>
function HelloWorld() {
var sDate = '<cart currency="USD" total="5.38"><cart-shipment total="5.38" shipment-reference="33261668"><shipment-tax total="0.39" /><shipment-cost total="0" /><shipment-address><address>33 W 59TH STREET APT 203 </address><zip>60559</zip><city>WESTMONT</city><state>IL</state><country>US</country><phone></phone><name>John Baker</name><attention-of>KID</attention-of></shipment-address><items><item total="4.99"><item-name>Hello Kitty - cupcake</item-name><item-description>Hello Kitty - cupcake</item-description><item-price>4.99</item-price><item-quantity>1</item-quantity></item></items></cart-shipment></cart>';
var webMethod = "https://abc.com/Services/TransactionService.svc";
var sr = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:ns2="vp">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<tem:ProcessTransaction>' +
'<tem:checkOutData>' + sDate + '</tem:checkOutData>' +
'<tem:token>5OMc0y1miZN5EFqiZ8IiLn+mzdboyTuTob43Kp4+VcVtrYGQvl7QWJB5OeoPWQpBUej6LSejwE8f16tDhg1EUqDtGGAdn/MM3Gk8MOr0FvFko84ogfhIs9HCUjum2MUN1a/sALjhen+DareUP5wWbIpnu8Eaqg2Tv0RjEsq1bqYblHcXfKIq7anTDzYoHN8Y7LAXgdEhSrVcEIB3+sCCDQ==</tem:token>' +
'<tem:transactionDescription>Volusion Order Description</tem:transactionDescription>' +
'</tem:ProcessTransaction>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
$.ajax({
type: "POST",
url: webMethod,
data: sr,
contentType: "text/xml",
dataType: "xml",
cache: false,
success: OnSuccess,
error: OnError
});
return false;
}
function OnSuccess(data, status) {
alert(data);
}
function OnError(request, status, error) {
alert(error);
}
</script>
<div>
<input type="button" value="Soap" onclick="HelloWorld();" />
</div>
Following is the output that i receive in firebug:
Request Headers:
OPTIONS /Services/TransactionService.svc?wsdl HTTP/1.1
Host: development.virtualpiggy.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://test.com
User-Agent: Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
Access-Control-Request-Headers: origin, content-type, accept
Accept: /
Referer: http://test.com/Desktop/test_webservice.htm
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Response Header:
Access-Control-Allow-Origin:http://yann-asus:81 http://www.kkdmarketing.com
Cache-Control:private
Content-Length:0
Date:Tue, 04 Dec 2012 06:42:23 GMT
Server:Microsoft-IIS/7.0
Set-Cookie:SessionId=ovpsrxt33jyoi3pzidvxkh0o; path=/; secure; HttpOnly
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
I would try setting a utf-8 charset in the contentType
$.ajax({
type: "POST",
url: webMethod,
data: sr,
contentType: "text/xml; charset=utf-8",
dataType: "xml",
cache: false,
success: OnSuccess,
error: OnError
});

Problems with sending ajax post to controller

I have an action
[HttpPost]
public JsonResult AddLocationsForOrder(List<BuyerOrderLocation> locations, string[] orders)
{
// something here
}
and js code, which sends the request:
data = { locations: serializedLocations, orders: selector.val() };
$.ajax({
url: addLocationUrl,
success: function (responseText) { Core.responceReceived(responseText, null, null); },
error: function () { Core.showErrorNotification("Sorry, some error occured. Please contact administrator"); },
async: false,
type: 'POST',
dataType: 'json',
data: JSON.stringify(data)
});
post details from firebug are here:
locations
"[{"id":225,"country":"United States","countryShort":"US","state":"Iowa","stateShort":"IA","city":null,"zipCode":null,"address":"Douglas, IA, USA","latitude":41.9053851,"longtitude":-93.8349976,"bounds":null,"isDeleted":false,"county":"Boone","radius":0},{"id":226,"country":"United States","countryShort":"US","state":"Iowa","stateShort":"IA","city":null,"zipCode":null,"address":"Iowa, USA","latitude":41.8780025,"longtitude":-93.097702,"bounds":null,"isDeleted":false,"county":null,"radius":0}]"
orders
[ "10440" , "10441" , "10442" ]
0 "10440"
1 "10441"
2 "10442"
And request headers:
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Connection keep-alive
Content-Length 830
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Cookie ASP.NET_SessionId=ewtvgwleg5or1lqctinpjv2d; .ASPXAUTH=8414A94FE30B8F8D6FE862259398F39D6F6D2EE995C9EE16549987E2E1291851788CAB75425579F61F70EBE4C7B785B07CB36773894A5B2A513966247AA5B670A25D4AE565796B449912D745EBE5E5E4AB8280902C132FC3D97C0C33BA2C2357372CD9C9EA49983DC4A8E875C6E4D653FA049EC7B0F3824666F35D3838226AA19ACEEC1B8C5716E995966787268313FEF90E2ABBAE989CA682D406EBCE361BB7
Host local.attorneyboost
Referer http://local.attorneyboost/Order/OrderInfo/10439
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1
X-Requested-With XMLHttpRequest
As you can see, request type is "POST", and I'm "Jsoning" data before sending to the server. But in action I got a null values for parameters. What am I doing wrong? I'm already stuck on searching for mistake
In this article they explain how to send complex JSON object to ASP.NET.
Hope this helps
You need to specify the datatype in the request send it to the server. The datatype attribute of your called sets the format of the response of the server, to set the datatype in the format that need to send to the server you need to use the contentType attribute
Modify the ajax called with this
$.ajax({
url: addLocationUrl,
success: function (responseText) { Core.responceReceived(responseText, null, null); },
error: function () { Core.showErrorNotification("Sorry, some error occured. Please contact administrator"); },
async: false,
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType = 'application/json; charset=utf-8'
});
You need to specify the datatype in the request send it to the server. The datatype attribute of your called sets the format of the response of the server, to set the datatype in the format that need to send to the server you need to use the contentType attribute

Resources