get method working, but not post - ZapWorks Studio - javascript

I'm using zapworks studio to develop an AR experience. It uses Z.ajax to make the ajax calls. I make a GET request and a POST request. I'm also using smileupps to host couchdb(they have free hosting). Here's the CORS configuration:
credentials: false; headers:Accept, Authorization, Content-Type, Origin;
methods: GET,POST,PUT,DELETE,OPTIONS,HEAD; origins: *
Everything works fine when launching ZapWorks Studio on windows. When scanning the zapcode with an android device, however, the post ajax call fails. Only the post. I am using basic authentication. I enforce that only the admin can manage the database on couchdb. I can access the host from both the desktop and the phone from a web browser to do everything manually.
I tried everything I could of to solve the problem: remove authentication, change the CORS configuration...nothing works. I thought it was an issue with CORS but everything works fine on windows and on the mobile just the POST fails...I keep getting a status code of 0.
EDIT - New info, testing on apitester also works on the desktop and mobile.
EDIT - Here's the zpp to show the logic
EDIT - Tried with REST Api Client on my phone and it worked as well. This can only be a CORS issue or something with zapworks. Weird that it works on windows but not on the phone.
EDIT - I found out what the problem is, but not how to fix it. So I set a proxy to debug the requests made from zapworks studio following this tutorial. It seems that it does a preflight request but gets the response
"HTTP/1.1 405 Method Not Allowed"
even though the payload is
{"error":"method_not_allowed","reason":"Only DELETE,GET,HEAD,POST
allowed"}.
Here's the request:
OPTIONS /ranking HTTP/1.1
Host: somehost.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: null
User-Agent: Mozilla/5.0 (Linux; Android 8.0.0; SM-G950U1 Build/R16NW; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36
Access-Control-Request-Headers: authorization,content-type,x-requested-with
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US
X-Requested-With: com.zappar.Zappar
and the response:
HTTP/1.1 405 Method Not Allowed
Server: CouchDB/1.6.0 (Erlang OTP/R15B01)
Date: Mon, 18 Jun 2018 21:22:12 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 76
Cache-Control: must-revalidate
Allow: DELETE,GET,HEAD,POST
Access-Control-Expose-Headers: Cache-Control, Content-Type, Server
Access-Control-Allow-Origin: null
Connection: keep-alive
{"error":"method_not_allowed","reason":"Only DELETE,GET,HEAD,POST allowed"}
which clearly shows that POST is allowed...
On the windows side, there doesn't seem to be a preflight request for some reason and my guess is that's why it works. Now the question is how do I configure CORS on couchdb to work on android. These are the configurations available:
enable_cors: true
credentials: false
headers:Accept, Authorization, Content-Type, Origin
methods:GET,POST,PUT,DELETE,OPTIONS,HEAD
origins:*
This is the code:
const Open_SansRegular_ttf0 = symbol.nodes.Open_SansRegular_ttf0;
parent.on("ready", () => {
const Plane0 = symbol.nodes.Plane0;
let ajaxParameters : Z.Ajax.Parameters = {
url: "https://something.smileupps.com/test/_all_docs?include_docs=true",
headers: {"Authorization": "Basic my64encoding"},
method: "GET",
timeout: 3000
};
// Perform the AJAX request
Z.ajax(ajaxParameters, (statusCode, data, request) => {checkRequest(statusCode, data);});
ajaxParameters = {
url: "https://something.smileupps.com/test",
headers: {"Content-Type":"application/json", "Authorization": "Basic my64encoding"},
method: "POST",
body: '{"name" : "asdasd", "something": 234}',
timeout: 3000
};
Z.ajax(ajaxParameters, (statusCode, data, request) => {checkRequest(statusCode, data);});
});
function checkRequest(statusCode, data) {
if (statusCode === 0) {
Open_SansRegular_ttf0.text("Unable to connect - check network connection.");
console.log("Unable to connect - check network connection.");
return;
}
if (statusCode < 200 || statusCode >= 300) {
Open_SansRegular_ttf0.text("HTTP request failed: " + statusCode);
console.log("HTTP request failed: " + statusCode);
return;
}
// Attempt to parse the data returned from the AJAX request as JSON
let parsedData;
try {
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
parsedData = JSON.parse(data);
} catch (e) {
Open_SansRegular_ttf0.text("Unable to parse JSON: " + e);
console.log("Unable to parse JSON: " + e);
return;
}
return parsedData;
}
EDIT
Here's the request on windows
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US
Authorization:Basic mybase64encoding
Connection:keep-alive
Content-Length:37
Content-Type:application/json
Host:http://something.smileupps.com/test
Origin:file://
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ZapWorksStudio/4.0.4-stable Chrome/58.0.3029.110 Electron/1.7.9 Safari/537.36
X-DevTools-Request-Id:3680.9
X-Requested-With:XMLHttpRequest
and the response:
Access-Control-Allow-Origin:file://
Access-Control-Expose-Headers:Cache-Control, Content-Type, ETag, Server
Cache-Control:must-revalidate
Content-Length:95
Content-Type:text/plain; charset=utf-8
Date:Mon, 18 Jun 2018 21:36:22 GMT
ETag:"1-512f89feb3d0a88781119e772ec6fd7b"
Location:http://something.smileupps.com/test
Server:CouchDB/1.6.0 (Erlang OTP/R15B01)
No preflight.

Your problem is in the request: Origin: null is usually what you get when the Web page containing the xhr request is opened with the file: rather than the http or https protocol. You won't get any successful CORS request with such an origin.

Related

'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check:

I've created an API and have the following within the WebApiConfig.cs:
var cors = new EnableCorsAttribute("http://localhost:3000", "*", "*");
config.EnableCors(cors);
I'm able to access it with my React application but I've created a new method within one of the controllers and restarted the API. When I tested it in Postman by sending a POST request it worked fine. However I'm now getting the error in the title when I try to access it using my React application. All other methods within the controller work fine. It's just this new one that is causing issues:
Accessing new method in React
const requestOptions = {
method: 'post',
headers: { "Content-type":"application/json",
"Accept":"*/*",
"Accept-Encoding":"gzip, deflate, br" },
body: JSON.stringify({ Data: this.props.data})
};
fetch("http://localhost:9074/Output/EditByMultipleIDs?varA=" + this.state.varA + "&varB=" + this.state.varB + "&varC=" + this.state.varC, requestOptions)
.then(response => response.json());
varA and varC are just a string of comma separated ids and varB is just an integer.
One which works from the same controller
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ Data:this.props.data})
};
fetch("http://localhost:9074/Output/EditByID?varA=" + this.state.varA + "&varB=" + this.state.varB, requestOptions)
.then(response => response.json());
here varA and varB are just integers.
I had tried to add in extra headers but that didn't seem to have worked and had also tried to add in [EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")] into the controller but that didn't help either.
I've noticed that if I remove [System.Web.Mvc.HttpPost] from the EditByMultipleIDs method within the controller then I'm able to hit the method without any CORS issue but then my model variable is null as nothing is passed into it from the body.
Below are the declaration for both methods within the controller:
[System.Web.Mvc.HttpPost]
public ActionResult EditByMultipleIDs(string varA, [FromBody] DTO model, int varB, string varC)
{ //... Do stuff}
[System.Web.Mvc.HttpPost]
public ActionResult EditByID(int varA, [FromBody] DTO model, int varB)
{//... Do stuff}
Also when I open the link in chrome I get:
I'm not sure if that's because the body data is lost so it's not able to complete the request or what but yeah...
EDIT 1: Actual Requests being made:
General
Request URL: http://localhost:9074/Output/EditByMultipleIDs?varA=55279,55280&varB=3&varC=393,394
Request Method: OPTIONS
Status Code: 404 Not Found
Remote Address: [::1]:9074
Referrer Policy: strict-origin-when-cross-origin
Response Headers
Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Cache-Control: private
Content-Length: 4500
Content-Type: text/html; charset=utf-8
Date: Mon, 04 Jul 2022 08:59:48 GMT
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcbW5hemlyXERlc2t0b3BcQWZ0b25cUnVsZXMgRW5naW5lXFJ1bGVFbmdpbmVBUEkgLSBDb3B5XFJ1bGVFbmdpbmVBUElcT3V0cHV0XEVkaXRCeU11bHRpcGxlSURz?=
Request Headers
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:9074
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
I had found the solution here: Handling CORS Preflight requests to ASP.NET MVC actions
Just need to add in:
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OrdinalIgnoreCase) &&
Request.HttpMethod == "OPTIONS") {
Response.Flush();
}
}
into Global.asax file so that it sends an empty response whenever it gets a OPTIONS request

Error x-amzn-errortype: InvalidSignatureException on DELETE request to API gateway

I am attempting to build a javascript application.
I am unable to get a DELETE request authenticated via IAM. 
The API gateway delete route has been configured to use AWS_IAM authentication. Cognito user group has a role attached which grants access to invoke the delete route.
I've signed the request using AWS.Signers.V4
var httpRequest = new AWS.HttpRequest("https://bo5o2odxxx.execute-api.ap-south-1.amazonaws.com/wrhprod/"+uri, "ap-south-1");
httpRequest.headers.host = "https://bo5o2odxxx.execute-api.ap-south-1.amazonaws.com";
httpRequest.headers['Content-Type'] = "application/json";
httpRequest.method = method; 
var v4signer = new AWS.Signers.V4(httpRequest, "execute-api", true);
v4signer.addAuthorization(awsCredentials, AWS.util.date.getDate());
delete httpRequest.headers['host']
delete httpRequest.headers['X-Amz-User-Agent']
I am using axios to send the delete request:
axios.delete('/events/2017/1523502329582',
{ headers: httpRequest.headers})
.then(response => {
//success
})
.catch(error => {
//fail
});
This is my request Header:
:authority: bo5o2odxxx.execute-api.ap-south-1.amazonaws.com
:method: DELETE
:path: /wrhprod/events/2017/1523502329582
:scheme: https
accept: application/json, text/plain, /
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
authorization: AWS4-HMAC-SHA256 Credential=ASIAIGIXC2II7KWVVUVA/20180413/ap-south-1/execute-api/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token;x-amz-user-agent, Signature=f1b12cf3c1a3693f259e2f0079231974d6de0e4225bca0af3754a32eecf95277
origin: http://localhost:3000
referer: http://localhost:3000/events
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
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ZFC7mX7xtaSQKcmv2sG1uJus9d7yyd3phQ4FluiI77UE5CVx3bkdRlEObRXB/DyCv+gfk3VfouIchF8xNpMU1jmaHN5+rB0/lbTMxVmEX8qYc6UdZXIIWRm2spB2YwnacBhC0Q36CnCwU1hcRo7YhcminiCPQy6+7OrOTLLXKAenRjNIuPYGAaZQl1MgPMBwFpPGAdbrJG/iWleNf5fN+dettOD18VT8jrmdQ0jRM5N9OjEMJqvwdYF
This is the AWS response header:
content-length: 192
content-type: application/json
date: Fri, 13 Apr 2018 07:17:41 GMT
status: 403
x-amz-apigw-id: FRLvXEDeBcwFuLQ=
x-amzn-errortype: InvalidSignatureException
x-amzn-requestid: c0f040c3-3eea-11e8-bd7a-dd445896cd03
I've spent hours on this & have not found a solution, please let me know if I can supply any other information to help troubleshoot.
This same API was working using cognito as an API gateway authorizer, I switches to IAM so that I may have more fine grained control on the cognito users.
I was not able to get AWS.Signers.V4 to work. From what I read, this API is not public yet.
I was able to get my APP working using a custom client to sign the request. It is available for download Here

fineuploader - Invalid policy document or request headers error

I'm trying to setup Fine-uploader s3 with cross domain signing. I've been struggling with it for two weeks now, going through every article on the internet and still can't get this to work. I'm, with exaggerating, very frustrated. I've started questioning every line of code and I get nowhere..
I keep receiving the following errors in the browser console:
XHR finished loading: OPTIONS "https://myserver.com/vendor/fineuploader/php-s3-server/endpoint-cors.php?v4=true".
util.js:241 [Fine Uploader 5.15.6] Invalid policy document or request headers!
XHR finished loading: POST "https://myserver.com/vendor/fineuploader/php-s3-server/endpoint-cors.php?v4=true".
util.js:241 [Fine Uploader 5.15.6] Policy signing failed. Invalid policy document or request headers!
I'm using the php server provided by fineuploader on github to sign documents. Here I've set my constants and modified
'access-control-allow-origin: https://myserver.com' and 'access-control-allow-credentials: true'.
My javascript uploader script client-side looks like this.
var uploader = new qq.s3.FineUploader({
element: document.getElementById("uploader"),
debug: true,
request: {
endpoint: 'BUCKET_NAME.s3-accelerate.amazonaws.com',
accessKey: 'ACCESS_KEY'
},
cors: {
//all requests are expected to be cross-domain requests
expected: true,
//if you want cookies to be sent along with the request
sendCredentials: true
},
objectProperties: {
bucket: 'BUCKET_NAME',
host: 's3-accelerate.amazonaws.com' // only needed for version 4 signatures
},
signature: {
endpoint: 'https://myserver.com/vendor/fineuploader/php-s3-server/endpoint-cors.php',
version: 4
},
uploadSuccess: {
endpoint: 'https://myserver.com/vendor/fineuploader/php-s3-server/endpoint-cors.php?success'
},
iframeSupport: {
localBlankPagePath: '/success.html'
},
validation: {
allowedExtensions: ["jpeg", "jpg", "png"],
acceptFiles: "image/jpeg, image/png",
sizeLimit: 10000000,
itemLimit: 1
},
retry: {
enableAuto: true // defaults to false
},
paste: {
targetElement: document,
promptForName: true
}
});
This is my header information
Request URL:https://MYSERVER.com/vendor/fineuploader/php-s3-server/endpoint-cors.php?v4=true
Request Method:OPTIONS
Status Code:200 OK
Remote Address:MY_IP
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:OPTIONS
Access-Control-Allow-Origin:https://MY_WEBSITE.com
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Wed, 31 Jan 2018 17:45:06 GMT
Host:127.0.0.1:8000
Server:nginx/1.10.3 (Ubuntu)
Transfer-Encoding:chunked
X-Powered-By:PHP/7.0.22-0ubuntu0.16.04.1
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:da-DK,da;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:aeoeaa.club
Origin:https://MY_WEBSITE.com
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
Query String Parameters
view source
view URL encoded
v4:true
And
Request URL:https://MYSERVER/vendor/fineuploader/php-s3-server/endpoint-cors.php?v4=true
Request Method:POST
Status Code:200 OK
Remote Address:MY_IP
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:https://MYWEBSITE.com
Connection:keep-alive
Content-Type:application/json
Date:Wed, 31 Jan 2018 17:45:07 GMT
Host:127.0.0.1:8000
Server:nginx/1.10.3 (Ubuntu)
Transfer-Encoding:chunked
X-Powered-By:PHP/7.0.22-0ubuntu0.16.04.1
Request Headers
view source
Accept:application/json
Accept-Encoding:gzip, deflate, br
Accept-Language:da-DK,da;q=0.9,en-US;q=0.8,en;q=0.7
Connection:keep-alive
Content-Length:461
Content-Type:application/json; charset=UTF-8
Host:MYSERVER.com
Origin:https://MYWEBSITE.com
Referer:https://MYWEBSITE.com/pages/testpage
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
Query String Parameters
view source
view URL encoded
v4:true
Request Payload
view source
{expiration: "2018-01-31T17:50:06.323Z",…}
conditions
:
[{acl: "private"}, {bucket: "MY_BUCKET_NAME"}, {Content-Type: "image/jpeg"},…]
expiration
:
"2018-01-31T17:50:06.323Z"
Everything should be working but I still get the same error. I don't want any of the complicating features. I just want a simple upload to s3. But this seems impossible. I'll gladly supply more info. Anything to get this done. I'll even send a bottle of wine to the one solving it. Nothing I do helps..

ASP.NET ajax post request getting redirected

I am using Visual Studio 2013 ASP.NET Identity template.
After user successfully logs in, the user is taken to a page with table.
Page has search options and search function is javascript driven
The javascript sends user selected parameters in form of an ajax request
I am having problems because AJAX request is well constructed from client side and sent to correct URL but it immediately gets redirected and parameters are lost.
I am not sure if this is happening because the request should be authenticated/authorized. I tried the following
$.ajax({
type: 'POST',
url: '<%=Config.VirtualDir %>listings.aspx' + '?filterattribute=y&call=ajax',
data: { 'zipcode': ZipCode, 'bedrooms': BedRooms, 'bathrooms': Bathroom, 'SquareFeetMin': SquareFeetMin, 'SquareFeetMax': SquareFeetMax, 'PriceMin': MinPrice, 'PriceMax': MaxPrice, 'Radius': Radius, 'Years': Years, 'IntRate': IntRate, 'DownPayment': DownPayment, 'sort': ddlsort, 'crfrom': capfrom, 'crto': capto, 'cffrom': cflowfrom, 'cfto': cflowto, 'roifrom': roifrom, 'roito': roito, 'vefrom': vefrom, 'veto': veto, 'chksupp': supp, 'undadd': undadd },
beforeSend: function(xhr){
xhr.withCredentials = true;
},
success: function (response) {
$('#DivRender').html(response);
DisplayPaging();
UpdateDropDowns();
$.hideprogress();
}
});
I checked how the request is handled in Fiddler and Here is what happens
Request1
POST /listings.aspx?filterattribute=y&call=ajax HTTP/1.1
Host: localhost:1794
Connection: keep-alive
Content-Length: 277
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,sv;q=0.6
Cookie: 83VLqQgggt8=CfDJ8EqbzpbyFkFAtEyP1X9rGYWcW8ryXAnh-VbYXDpLXBhNXU5Brq_PAiggJHvIwAXK2yZZPz5_NBCSTjV9FYC1O6PEvmGVe9r8feB74Rjc0hANEjsG_Pf6k6iwYdnRRxxHDD5qSRAAYJHGa3LpH4MOlww; .AspNet.Microsoft.AspNet.Identity.Application=CfDJ8EqbzpbyFkFAtEyP1X9rGYUDNW-ipW7_DjFWLk0XMejiHWRdCnQmZMipzvTZJcnYL3ncfpETFYsVA3s2UHEnvkUJEbxPIBfuNNoRLQrhaoJaegw78lGv1XWRXgJ9g5GikhXprPsC9Nt8n7Wt6UVT24Wao-CHiVHVZVOX3weXu8Eu48W8gEhnXzvG1Vx57tGWPiSbu9mJiIOXoJyO-ybxNuontF7g6hfCAi0f9ohonq2Mal9xWhVtHWUQnIYTdlrbnueX6guTMyCPmS8augNyZSAmGqRfCr9KfoTYy4bAjIaOpxKANS6qe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akUIfIj-RSn4a9vmhETk5UTE8X-Yc99AMDnauKhmg5y09GwhGdO1Iv62kauaD_Kpxq14ATfCu; .ASPXAUTH=1647B3E8FA3AB2D87B584B214BF8BFEB3390BBBE6BBB9F35B6C01A8E2DDB4D3A31A2F1906E93298C87D5FE9A6E1D869D055A1CC2BE6B1A25316B1BEA229E144D2D1FAB1B038013DD96DE9BA072C6511A10526A34DC959868C808FCD458ADDF40DAB7856C3639D74AC00AFD21166D6ED5DF82726E
zipcode=92801%2C92802%2C92804%2C92805%2C92806%2C92807
Response 1: HTTP/1.1 301 Moved Permanently
**Second Immediate Request**
GET /listings?filterattribute=y&call=ajax HTTP/1.1
Host: localhost:1794
Connection: keep-alive
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,sv;q=0.6
Cookie: 83VLqQgggt8=CfDJ8EqbzpbyFkFAtEyP1X9rGYWcW8ryXAnh-VbYXDpLXBhNXU5Brq_PAiggJHvIwAXK2yZZPz5_NBCSTjV9FYC1O6PEvmGVe9r8feB74Rjc0hANEjsG_Pf6k6iwYdnRRxxHDD5qSRAAYJHGa3LpH4MOlww; .AspNet.Microsoft.AspNet.Identity.Application=CfDJ8EqbzpbyFkFAtEyP1X9rGYUDNW-ipW7_DjFWLk0XMejiHWRdCnQmZMipzvTZJcnYL3ncfpETFYsVA3s2UHEnvkUJEbxPIBfuNNoRLQrhaoJaegw78lGv1XWRXgJ9g5GikhXprPsC9Nt8n7Wt6UVT24Wao-CHiVHVZVOX3weXu8Eu48W8gEhnXzvG1Vx57tGWPiSbu9mJiIOXoJyO-ybxNuontF7g6hfCAi0f9ohonq2Mal9xWhVtHWUQnIYTdlrbnueX6guTMyCPmS8augNyZSAmGqRfCr9KfoTYy4bAjIaOpxKANS6qeTQdCP07oB_axsNJ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vmhETk5UTE8X-Yc99AMDnauKhmg5y09GwhGdO1Iv62kauaD_Kpxq14ATfCu; .ASPXAUTH=1647B3E8FA3AB2D87B584B214BF8BFEB3390BBBE6BBB9F35B6C01A8E2DDB4D3A31A2F1906E93298C87D5FE9A6E1D869D055A1CC2BE6B1A25316B1BEA229E144D2D1FAB1B038013DD96DE9BA072C6511A10526A34DC959868C808FCD458ADDF40DAB7856C3639D74AC00AFD21166D6ED5DF82726E
How do i make sure that the ajax post request sends session cookies along with the request so that redirect doesnt happen.
If you want to make sure you're not being affected by authentication redirects:
Check out your OWIN Startup class, you should have a line like this (taken from default MVC, will be similar for Web API):
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
});
The LoginPath property here will redirect all unauthenticated requests (if the request requires authorization) to the specified path.
Try your AJAX request again without that LoginPath, you will probably get a 401 Unauthorized.
If you want to keep the LoginPath redirect but don't want it to affect your AJAX calls, check out this post from Brock Allen about handling 401s differently depending on the requesting application.
In your case it is better to use [WebMethod] instead of sending a request to the page. In WebMethod also you can access Session.

AJAX function w/ Mailgun, getting "ERROR Request header field Authorization is not allowed by Access-Control-Allow-Headers"

I'm working on making an AJAX call that hit the Mailgun API to send email. Documentation on Mailgun says that post requests should be made to "https://api.mailgun.net/v3/domain.com/messages". I've included my api key as specified by mailgun (they instruct to use a username of 'api'). Since this involves CORS, I can't get past the error: Request header field Authorization is not allowed by Access-Control-Allow-Headers.
However, I've inspected the requests/responses in the Network tab and "Access-Control-Allow-Origin" in the response from Mailgun is set to "*"...which should indicate that it should allow it? (See request/response below): I've edited the actual domain and my API key.
Remote Address:104.130.177.23:443
Request URL:https://api.mailgun.net/v3/domain.com/messages
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.mailgun.net
Origin:null
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
Response Headersview source
Access-Control-Allow-Headers:Content-Type, x-requested-with
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:600
Allow:POST, OPTIONS
Connection:keep-alive
Content-Length:0
Content-Type:text/html; charset=utf-8
Date:Fri, 20 Mar 2015 19:47:29 GMT
Server:nginx/1.7.9
My code for the ajax call is below, in which I include my credentials in the headers and the domain to where the post is supposed to go. Not sure what's causing this not to work. Is it because I'm testing on local host? I didn't think that would make a difference since the "Access Control Allow Origin:*" in the response header. Any help would be greatly appreciated! Thank you.
function initiateConfirmationEmail(formObj){
var mailgunURL;
mailgunURL = "https://api.mailgun.net/v3/domain.com/messages"
var auth = btoa('api:MYAPIKEYHERE');
$.ajax({
type : 'POST',
cache : false,
headers: {"Authorization": "Basic " + auth},
url : mailgunURL,
data : {"from": "emailhere", "to": "recipient", etc},
success : function(data) {
somefunctionhere();
},
error : function(data) {
console.log('Silent failure.');
}
});
return false;
}
Drazisil is correct above. The response needs to include Access-Control-Allow-Headers: Authorization as you are including that header in your request and Authorization is not a simple header.

Categories

Resources