fineuploader - Invalid policy document or request headers error - javascript

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..

Related

retrive a result from a website by an ajax post request

I'm tryng to perfom a simple ajax post request to retrieve some data from a website.
In detail i'm trying to contact a page that a website recall to have some informations.
So i have the main website and a page that it calls to retrive data.
I discovered that page using the google inspection section, in particular in the xhr section of network field of the inspector.
In my code i used all the headers and the payload data that are used by the website to contact the page.
This is the code that i'm using to reach my goal:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var url = 'https://www.remax.pt/Webservices/MainWebService.asmx/GetCityList';
var body = {"SiteRegionID":"12","RegionID":"12","RegionRowID":"78","ProvinceID":"0",
"LanguageCode":"ITA","MinInternetCount":"0","SearchType":"","OfficeAgent":"0",
"EncodingLanguage":"PTG","OfficeAgentId":"0"};
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var data = xhr.responseText;
if (xhr.readyState == 4 && xhr.status == "200") {
console.table("results: "+data);
} else {
console.error("error: "+data);
}
}
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
//xhr.setRequestHeader("Content-Type","text/html");
xhr.setRequestHeader("Access-Control-Allow-Origin","*");
xhr.setRequestHeader("accept", "application/json, text/javascript, */*; q=0.01");
xhr.setRequestHeader("authority", "www.remax.pt");
xhr.setRequestHeader("scheme", "https");
xhr.setRequestHeader("path", "/Webservices/MainWebService.asmx/GetCityList");
xhr.setRequestHeader("accept-language","it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7");
//xhr.setRequestHeader('accept-encoding', 'gzip, deflate, br');
//xhr.setRequestHeader("host", "https://www.remax.pt");
//xhr.setRequestHeader('referer', 'https://www.remax.pt/PublicListingList.aspx');
//xhr.setRequestHeader('content-length', '192');
//xhr.setRequestHeader('cookie','__cfduid=dc7dd48ccff40ee4f85840bfc35685b311531384150; PersonalizationMap=; PersonalizationGallery=SelectedCountryID=12; GtTransLang=ITA; SLINGSHOT=LanguageCode=it-IT; SessionId=1ac0ec84-6a03-4965-ba90-7eb686f66bf5; ASP.NET_SessionId=rgia1pblms2abf11ypsbiqgz; GtTrans=ENU; LastSearch=SiteRegionID=12&TransactionTypeUID=260&RegionID=12&RegionRowID=78&LocationText=Porto&LocationValue=YR78&PriceCurrency=EUR&ComRes=2; PersonalizationRegion=#mode=list&tt=260&cr=2&r=78&cur=EUR&la=All&sb=PriceIncreasing&page=1&sc=12&sid=a81a1d1d-ee36-4236-a72e-31343349c574; PersonalizationDate=2018-7-24 10:0:30');
xhr.setRequestHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
xhr.setRequestHeader("x-requested-with", "XMLHttpRequest");
xhr.send(JSON.stringify(body);
Actually i never receive an answer. I think that the flow of operations never enter in the onLoad section because the string that there are in if and else sections are never printed.
I wanna specify that some headers are commented because i had an answer of this type:
Refused to set unsafe header 'nameHeader'
So i decided to do not use them for the moment.
I tried to change some headers or add something new but the problem remains and honestly i don't have idea if it is a problem of syntax of some fields or if i need other things to perform an acceptable request.
for completeness i insert the 4 fields that i found in the inspector tool that specify the parameters passed by the website to call the page:
GENERAL:
1. Request URL:
https://www.remax.pt/Webservices/MainWebService.asmx/GetCityList
2. Request Method: POST
3. Status Code: 200
4. Remote Address: 104.25.40.105:443
5. Referrer Policy: no-referrer-when-downgrade
RESPONSE HEADERS:
List item
cache-control: private, max-age=0
cf-ray: 43f532b9e9886260-LIS
content-encoding: br
content-type: application/json; charset=utf-8
date: Tue, 24 Jul 2018 09:00:44 GMT
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
status: 200
x-aspnet-version: 4.0.30319
x-ua-compatible: IE=9, IE=8
REQUEST HEADERS:
authority: www.remax.pt
method: POST
path: /Webservices/MainWebService.asmx/GetCityList
scheme: https
accept: application/json, text/javascript, /; q=0.01
accept-encoding: gzip, deflate, br
accept-language: it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7
content-length: 192
content-type: application/json; charset=UTF-8
cookie: __cfduid=dc7dd48ccff40ee4f85840bfc35685b311531384150; PersonalizationMap=; PersonalizationGallery=SelectedCountryID=12; GtTransLang=ITA; SLINGSHOT=LanguageCode=it-IT; SessionId=1ac0ec84-6a03-4965-ba90-7eb686f66bf5; ASP.NET_SessionId=rgia1pblms2abf11ypsbiqgz; GtTrans=ENU; LastSearch=SiteRegionID=12&TransactionTypeUID=260&RegionID=12&RegionRowID=78&LocationText=Porto&LocationValue=YR78&PriceCurrency=EUR&ComRes=2; PersonalizationRegion=#mode=list&tt=260&cr=2&r=78&cur=EUR&la=All&sb=PriceIncreasing&page=1&sc=12&sid=a81a1d1d-ee36-4236-a72e-31343349c574; PersonalizationDate=2018-7-24 10:0:30
origin: https://www.remax.pt
referer: https://www.remax.pt/PublicListingList.aspx
user-agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
x-requested-with: XMLHttpRequest
REQUEST PAYLOAD:
{"SiteRegionID":"12","RegionID":"12","RegionRowID":"78","ProvinceID":"0","LanguageCode":"ITA","MinInternetCount":"0","SearchType":"","OfficeAgent":0,"EncodingLanguage":"PTG","OfficeAgentId":0}

get method working, but not post - ZapWorks Studio

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.

Power BI Access Token API not working in Angular

Trying to embed PowerBI dashboard into angular App. The API call to get access token is working in API is working in Postman but not working in Angular $http.post
Here is my http request:
Request URL:https://login.microsoftonline.com/common/oauth2/token
Request Method:POST
Status Code:400 Bad Request
Remote Address:104.211.216.34:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Cache-Control:no-cache, no-store
Content-Length:435
Content-Type:application/json; charset=utf-8
Date:Tue, 28 Nov 2017 12:39:04 GMT
Expires:-1
P3P:CP="DSP CUR OTPi IND OTRi ONL FIN"
Pragma:no-cache
Server:Microsoft-IIS/8.5
Set-Cookie:esctx=AQABAAAAAABHh4kmS_aKT5XrjzxRAtHzOEDuOCnOGQdXuNJYF9t_l4l8QbiGM-1SOn4WhmgW5oU1BTHew-wFbpdzDe250yG1ODXnl9crMy97-PJdBUTJD2hCZ0fjpleNFz13Xbl3nDt21xoySABfsdxlxd8ODv8ryZ_n2CwnYMpM_yEoQG5tSxlh-SdOviP8tF3-n_uBqZwgAA; domain=.login.microsoftonline.com; path=/; secure; HttpOnly
Set-Cookie:x-ms-gateway-slice=004; path=/; secure; HttpOnly
Set-Cookie:stsservicecookie=ests; path=/; secure; HttpOnly
Strict-Transport-Security:max-age=31536000; includeSubDomains
X-Content-Type-Options:nosniff
x-ms-request-id:5f039662-e0ce-425a-9e38-1593c64c7b00
X-Powered-By:ASP.NET
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-GB,en-US;q=0.9,en;q=0.8
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Length:188
Content-Type:application/x-www-form-urlencoded
Host:login.microsoftonline.com
Origin:http://evil.com/
Referer:http://localhost:9000/power-bi
roleId:57be85636318773723861b99
token:W0JANTc3YjEwMTY
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Form Data
view source
view URL encoded
{"grant_type":"password","client_id":"clientId","resource":"https://analysis.windows.net/powerbi/api","username":"username","password": "password"}
Response is :
correlation_id : "1e68335a-6b6d-441d-90d3-eb8c88929a37"
error:"invalid_request"
error_codes:[90014]
error_description:"AADSTS90014: The request body must contain the following parameter: 'grant_type'.
↵Trace ID: 5f039662-e0ce-425a-9e38-1593c64c7b00
↵Correlation ID: 1e68335a-6b6d-441d-90d3-eb8c88929a37
↵Timestamp: 2017-11-28 12:39:05Z"
timestamp:"2017-11-28 12:39:05Z"
trace_id:"5f039662-e0ce-425a-9e38-1593c64c7b00"
can anyone please help me out of this hitch??
I got the Solution. I got that error i was making API call correctly. it expects data to be sent in 'Content-Type':'application/x-www-form-urlencoded' and data is serialised.
This code worked :
$http({
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
url: 'https://login.microsoftonline.com/common/oauth2/token',
method: 'POST',
transformRequest: $httpParamSerializer,
transformResponse: function (x) {
return angular.fromJson(angular.fromJson(x));
},
data: {
grant_type:'password',
client_id: "client_id",
resource:'https://analysis.windows.net/powerbi/api',
username:"username",
password: "pwd",
client_secret: "client_secret"
}
})
I hope this answer will be useful anyone who face same problem in future.

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-ybxNuontF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RbjcoxxOez_pzcAypDgkFjnPbdtyDK-9MXyIRajT8pay9mRc-YlpjoZgwW3Ww3de1a4qeRJB7zLNr2Ec8gGVZEFRakUIfIj-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-ybxNuontF7g6hfCAi0f9oh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AypDgkFjnPbdtyDK-9MXyIRajT8pay9mRc-YlpjoZgwW3Ww3de1a4qeRJB7zLNr2Ec8gGVZEFRakUIfIj-RSn4a9vmhETk5UTE8X-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