Failing to use eZ Platform JS REST API client with cross domain - rest

Context and troubles
I'm currently building a web application on top of ezPlatform & Symfony.
My goal is now to request this app from an external website using a JS client (using the JS REST client of ezplatform : CAPI.js)
I tested my script localy (on the app itself = same domain) and everything is fine : I can GET and POST data.
But testing this script on an external webiste (CORS requests) didn't work. I am stuck with 2 differents problems :
Server side : The response headers do not contains the Access-Control-Allowed-Methods
Client side : No session cookies are given within a request
Details
Problem 1 : No header "allow_methods"
On chrome I always have this error :
XMLHttpRequest cannot load http://api.ezplatform.lan/api/ezp/v2/user/sessions. Response for preflight has invalid HTTP status code 405
Note that, on the server side, nelmio_cors bundle is used to configures the headers. The configs :
nelmio_cors:
paths:
'^/api/ezp/v2/':
max_age: 3600
allow_credentials: true
allow_origin: ['*']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
expose_headers: []
And now, here are the details of a failing preflight request :
GENERAL
Request URL:http://api.ezplatform.lan/api/ezp/v2/user/sessions
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Remote Address:192.168.1.82:80
REPONSE HEADERS
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:authorization, accept, content-type, x-csrf-token, destination, x-siteaccess
Access-Control-Allow-Origin:http://www.externalsite.lan
Access-Control-Max-Age:3600
Cache-Control:private
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html; charset=UTF-8
Date:Tue, 13 Dec 2016 15:24:44 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.23 (Ubuntu)
Vary:X-User-Hash
REQUEST HEADERS
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:api.ezplatform.lan
Origin:http://www.externalsite.lan
Pragma:no-cache
Referer:http://www.externalsite.lan/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
In the "response headers", there is no Access-Control-Allow-Methods despite of the nelmio_cors configs.
Digging inside the nelmio_cors code I realized that the "allow_methods" config is retrieved but is then overwritten by something else, and here it becomes obscur to me.
This old ezpublish bug maybe give me a clue about the situation : the ezPublishRestBundle does not seems to find any "allowed method", and somehow overwrite the nelmio_cors config.
In the Resprovider.php file, if I force the methods getAllowedMethods to return this :
return ["POST", "PUT", "GET", "DELETE", "OPTIONS"]; then I have no more 405 error but a very different problem (explained right after this)
Problem 2 : no session cookies allowed
With my previous wonderful hack, I can now get a little bit further : my request are allowed but some of them are still failing.
I noticed that no session cookie is passed inside the requests (which is the normal behaviour testing on the same domain).
This times it seems to come from the CAPI.js file : the XmlHttpRequest object never has the property withCredentials to true.
If I add this code XHR.withCredentials = true; in CAPI.js before the request is send, then it seems to be fine.
Conclusion
I really wonder if the ez Platform rest client has been designed to be used for cross domain, but it would be very surprising if not.
So I must do something wrong, and if someone can explain me what, I would be extemely grateful :)

Related

How can I find out why ISAPI is returning a 302 status for a specific file?

I have a website hosted served by IIS 10 on a Windows Server (2019) running Plesk. The site is mainly Classic ASP. I have a staging subdomain at staging.example.com, with the production site at www.example.com.
The two are fairly strictly separated, except that I don’t store image files, PDFs and such things on the staging server; I have a URL rewrite directive that redirects to the production site with a 302 status based on the URL not matching the following regex:
\.(php|asp|js|css|csv|json|htm|html|svg|svgz)(\?.+)?$
This generally works well: ASP pages are served from the staging site when the staging URL is called, but images on the page are pulled from the production site.
Except that there’s one ASP file which – for some reason – gives a 302 and redirects to the production site no matter what I do. The file exists in both locations. I’ve tested the URL in the pattern tester provided in the IIS URL-rewrite section, and it matches the pattern (meaning it shouldn’t redirect).
When I trace the request (that is, the initial request to the staging URL) in Firefox’s browser console, I get the following response headers (redacted):
HTTP/2 302 Found
cache-control: no-cache
content-type: text/html
location: https://www.example.com/path/to/file.asp
server: Microsoft-IIS/10.0
set-cookie: ASPSESSION****=********; secure; path=/
x-powered-by: ASP.NET
x-powered-by-plesk: PleskWin
date: Sun, 19 Dec 2021 18:52:05 GMT
content-length: 201
Accept
text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Encoding
gzip, deflate, br
Accept-Language
en-US,en;q=0.5
Authorization
Basic *************
Connection
keep-alive
Cookie
[cookies]
Host
staging.example.com
Referer
https://staging.example.com/path/to/file.asp
Sec-Fetch-Dest
document
Sec-Fetch-Mode
navigate
Sec-Fetch-Site
same-origin
Sec-Fetch-User
?1
Upgrade-Insecure-Requests
1
User-Agent
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:96.0) Gecko/20100101 Firefox/96.0
I’ve painstakingly gone through the entire file and all the file includes within it, and I can’t find any kind of Response.Redirect in any of them that might be responsible.
So it seems it’s IIS that’s redirecting with a 302… despite the fact that there doesn’t seem to be a directive that tells it to do this.
Is there a way to trace exactly what on the server is causing this 302 for one specific file? Some sort of tracing mechanism that tells me where the request gets passed on to before the 302 response is returned?
 
 
Update 26 Dec
Based on samwu’s comment, I’ve enabled Failed Request Tracing for the page, and looking through the resulting .frb file, it’s clear that none of the rewrite conditions are met – they all have succeed: false. It seems the redirect is not happening in the WWW Server at all, in fact, but in the ISAPI extension. This is the only place that the production site URL is mentioned at all in the request trace (except of course in the GENERAL_RESPONSE_HEADER section at the very end):
ISAPI_START
MODULE_SET_RESPONSE_SUCCESS_STATUS ModuleName="IsapiModule", Notification="EXECUTE_REQUEST_HANDLER", HttpStatus="302", HttpReason="Object moved"
GENERAL_SET_RESPONSE_HEADER HeaderName="Location", HeaderValue="https://www.example.com/path/to/file.asp", Replace="false"
GENERAL_SET_RESPONSE_HEADER HeaderName="Content-Length", HeaderValue="201", Replace="false"
GENERAL_SET_RESPONSE_HEADER HeaderName="Content-Type", HeaderValue="text/html", Replace="false"
GENERAL_SET_RESPONSE_HEADER HeaderName="Cache-control", HeaderValue="no-cache", Replace="false"
NOTIFY_MODULE_COMPLETION ModuleName="IsapiModule", Notification="EXECUTE_REQUEST_HANDLER", fIsPostNotificationEvent="false", CompletionBytes="0", ErrorCode="The operation completed successfully. (0x0)"
ISAPI_END
In the ISAPI Filters section in IIS Manager, there are four filters: a 32-bit and a 64-bit version for ASP.Net 2.0 and the same for ASP.Net 4.0, all called aspnet_filter.dll. I’m guessing these are standard filters – I know for certain, at least, that we haven’t mucked about with any ISAPI filters at all.
As should be obvious by now, I’m not really a server admin, and ISAPI filters are definitely above my level of knowledge.
So how do I proceed from here? How do I figure out why ISAPI is redirecting?

Using Postman get 500 Internal error sending payload

I am trying to reverse engineer an api request to a server that I don't control. Initially I view the following url (which doesn't require any credentials to logon):
https://www.abc.ca.gov/datport/lqs.html?rpttype=3&rptdateoffset=0
Using Chrome dev tool I see the data is displayed via the following url:
https://www.abc.ca.gov/LQSService.svc/LicenseRequest
I use this url in Postman as a POST request:
POST https://www.abc.ca.gov/LQSService.svc/LicenseRequest
Chrome tools shows the Request Payload which I use in the Body (raw) of the Postman request:
{"data":"<ROOT><PAGENUMBER>1</PAGENUMBER><RPTTYPE>3</RPTTYPE><RPTDATEOFFSET>0</RPTDATEOFFSET><RPTDATE>11/29/2017</RPTDATE><FORMATEDDATE>Wednesday, Nov 29, 2017</FORMATEDDATE><RPTGROUP>DAILY3</RPTGROUP></ROOT>"}
When I execute the request in Postman I get the following error:
{
"ExceptionDetail": null,
"ExceptionType": null,
"Message": "The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.",
"StackTrace": null
}
The Headers from the results show:
jsonerror →true
Chrome Request Headers also shows the following which I added to the Postman request (Headers) with the same error happening:
X-Requested-With:XMLHttpRequest
Cookie:ASPSESSIONIDCWQRCBDR=IBNIPHCCIGMJLKOPDMDJKCPJ
I also added the following Cookie in Postman as well:
ASPSESSIONIDCWQRCBDR=IBNIPHCCIGMJLKOPDMDJKCPJ; path=/; domain=.www.abc.ca.gov; Expires=Tue, 19 Jan 2038 03:14:07 GMT;
What else may I be missing or not specifying correctly in the Postman request?
The complete Request Headers as shown in Chrome are:
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Content-Length:210
Content-Type:application/json; charset=UTF-8
Cookie:ASPSESSIONIDCWQRCBDR=IBNIPHCCIGMJLKOPDMDJKCPJ; __utmt=1;
__utma=158387685.1745889465.1508735899.1512200444.1512230785.12;
__utmb=158387685.6.10.1512230783; __utmc=158387684;
__utmz=158387685.1512185091.8.2.utmcsr=google|utmccn=
(organic)|utmcmd=organic|utmctr=(not%20provided)
Host:www.abc.ca.gov
Origin:https://www.abc.ca.gov
Referer:https://www.abc.ca.gov/datport/lqs.html?
rpttype=3&rptdateoffset=0
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
X-Requested-With:XMLHttpRequest
Turns out I only needed to specify Content-Type in header.

Uber API issue with CORS

First time asking a question here. I'm a beginner at this, but i'm truly stumped at the problem i'm facing.
Browsers in use:
Safari and Firefox (both on Mac OS Sierra)
Firefox (Linux - Ubuntu 16.04.2)
I am registered as an Uber Developer and have registered an App in the Dashboard. I'm only using the Server Token for authentication at the moment. In the Dashboard, I have set the following entries in the "Authorizations" tab of the App for CORS (Optional URI for CORS Support):
http://localhost:8000 <-- web server in my PC
https://subdomain.mydomain.com <--- remote web server
A few months ago i created a web app using HTML, CSS and JS (with Jquery v2.2.4) to play around with the Ride Estimates API and was able to get it to report data for many locations in my area successfully. Somehow it no longer works. I'm trying to fix that and improve the functionality. However, i just can't get past the initial query to the API because of CORS issues that were not existent before.
My API URL is:
https://api.uber.com/v1/estimates/price?start_latitude=8.969145&start_longitude=-79.5177675&end_latitude=8.984104&end_longitude=-79.517467&server_token={*********SERVER*TOKEN**********}
When i paste that in the address bar of the browser i get valid JSON:
{"prices":[{"localized_display_name":"uberX","distance":1.58,"display_name":"uberX","product_id":"811c3224-5554-4d29-98ae-c4366882011f","high_estimate":3,"surge_multiplier":1.0,"minimum":2,"low_estimate":2,"duration":420,"estimate":"2-3\u00a0$","currency_code":"USD"},{"localized_display_name":"X English","distance":1.58,"display_name":"X English","product_id":"8fe2c122-a4f0-43cc-97e0-ca5ef8b57fbc","high_estimate":4,"surge_multiplier":1.0,"minimum":3,"low_estimate":3,"duration":420,"estimate":"3-4\u00a0$","currency_code":"USD"},{"localized_display_name":"uberXL","distance":1.58,"display_name":"uberXL","product_id":"eb454d82-dcef-4d56-97ca-04cb11844ff2","high_estimate":4,"surge_multiplier":1.0,"minimum":3,"low_estimate":3,"duration":420,"estimate":"3-4\u00a0$","currency_code":"USD"},{"localized_display_name":"Uber Black","distance":1.58,"display_name":"Uber Black","product_id":"ba49000c-3b04-4f54-8d50-f7ae0e20e867","high_estimate":6,"surge_multiplier":1.0,"minimum":4,"low_estimate":4,"duration":420,"estimate":"4-6\u00a0$","currency_code":"USD"},{"localized_display_name":"Uber SUV","distance":1.58,"display_name":"Uber SUV","product_id":"65aaf0c2-655a-437d-bf72-5d935cf95ec9","high_estimate":7,"surge_multiplier":1.0,"minimum":5,"low_estimate":5,"duration":420,"estimate":"5-7\u00a0$","currency_code":"USD"}]}
I then proceed to set up JS (w/ JQuery) code in webpage...
var url = "https://api.uber.com/v1/estimates/price?start_latitude=8.969145&start_longitude=-79.5177675&end_latitude=8.984104&end_longitude=-79.517467&server_token={*********SERVER*TOKEN**********}";
$.getJSON(url, function(result){
console.log(result);
});
Uploading the HTML and JS to my remote web server and then loading the webpage in any of my browsers yields a 200 status from Uber API. However, the console log shows CORS blocking my request (PROBLEM #1):
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.uber.com/v1/estimates/price?start_latitude=8.969145&start_longitude=-79.5177675&end_latitude=8.984104&end_longitude=-79.517467&server_token={*********SERVER*TOKEN**********}. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Then, in the Inspector view of both Mac Browsers, under the Network / Resources areas, i see the 200 Status message from the GET request. However, along with the Response message (PROBLEM #2):
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
The Request Headers are:
GET /v1/estimates/price?start_latitude=8.969145&start_longitude=-79.5177675&end_latitude=8.984104&end_longitude=-79.517467&server_token={*********SERVER*TOKEN**********} HTTP/1.1
Host: api.uber.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://subdomain.domain.com/Uber/index.html
Origin: https://subdomain.domain.com
Connection: keep-alive
The Response Headers are:
HTTP/1.1 200 OK
Server: nginx
Date: Sun, 19 Mar 2017 22:26:31 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Content-Geo-System: wgs-84
Content-Language: en
X-Rate-Limit-Limit: 2000
X-Rate-Limit-Remaining: 1998
X-Rate-Limit-Reset: 1489964400
X-Uber-App: uberex-nonsandbox, optimus, migrator-uberex-optimus
Strict-Transport-Security: max-age=604800
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Content-Encoding: gzip
In Firefox for Linux i sometimes don't get the Syntax Error; i always seem to get it on the Mac Browsers. In Linux, when i do get that error, then clicking on the "Edit and Resend" Headers button (resending the Headers but without really editing the Headers), the Syntax Error disappears and the Response text actually shows the Uber API Object that is supposed to be there... but i still get the CORS Blocked message on the Console Log. I really don't understand why this is, but it seems contradictory. In the end, i am unable to get to use the API data that, using the same method months ago, i could get for several dozens of locations.
I have looked for answers in similar questions but so far have found none that apply to my case. Any help will be greatly appreciated. Getting really frustrated... really stuck here.
This issue was caused by the API not including the header correctly. This issue is resolved and the api is now working as expected. Also, the allow origin header will only be returned in a response if an origin is specified in the request.

Office Outlook Add-In OAuth Error

i'm currently developing an Office Outlook App.
I'm trying to get the messages (specially the Attachments of messages)
from the Exchange Server.
I'm using the Outlook Desktop Application.
I already got the bearer authentication token and i'm trying using the Office REST-API to get the messages, but there is a strange error if i send the GET request to the server.
Error:
"The api you are trying to access does not support item scoped OAuth."
Here is my JavaScript-Code:
Office.context.mailbox.getCallbackTokenAsync(function (asyncResult) {
if (asyncResult.status === "succeeded") {
var authToken = asyncResult.value;
var attUrl = 'https://outlook.office.com/api/v2.0/me/mailfolders/inbox/messages/';
$.ajax({
method: "GET",
url: attUrl,
beforeSend: function (request) {
request.setRequestHeader("Accept", "text/*, application/xml, application/json; odata.metadata=none");
request.setRequestHeader("Authorization", "Bearer " + authToken);
request.setRequestHeader("X-AnchorMailbox", "test#test.de");
},
success: function (responseData) {
console.log("success", responseData);
},
error: function (errData) {
console.log("err", errData);
}
});
}
});
I'm scanning the outgoing traffic and there seems everything ok:
GET outlook.office.com/api/v2.0/me/mailfolders/inbox/messages/ HTTP/1.1
Authorization: Bearer TokenIsCorrect
Accept: text/*, application/xml, application/json; odata.metadata=none
X-AnchorMailbox: test#test.de
Referer: localhost:44300/AddInRead/App/Index/Index.html
Accept-Language: de-DE
Origin: localhost:44300
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Host: outlook.office.com
DNT: 1
Connection: Keep-Alive
Cache-Control: no-cache
.................
I refered to:
Outlook Mail REST-API Reference
and the samples on
Outlook Dev Center OAuth Sandbox
I think i searched the hole internet, but couldn't find anything
to fix this problem.
Hopefully someone can give me the right hint.
BTW: had to remove some links cause of no reputation of my account :/
Thanks !
I found the problem and i was able to fix it.
There is a difference between the Access-Token and the Token you get, if you call the Office.context.mailbox.getCallbackTokenAsync function of the REST-API.
I could see that with logging-in in Outlook Dev Center OAuth Sandbox with my own account, get the token and compare this token with the token i get in VS with getCallbackTokenAsync.
They are different.
The Token from the function is only for getting attachments or items.
In this case i thought "items" are messages and i could start a request for all messages with that token, but wrong.
You have to take the token from the function and address the attachment directly with
https://outlook.office.com/api/v2.0/me/mailfolders/inbox/messages/' + idMail + '/attachments/' + mail.attachments[i].id;
Best regards

The domain is inserted right but FB login still gives a "the given url is not allowed by the application configuration"

I'm making a facebook login for a client. But i keep getting the error:
the given url is not allowed by the application configuration
This is not new to me and I know what the error means and how to correct it. But this time i'm really puzzled, as I have tried every possible solution and still no result.
I'm using the newest Facebook PHP SDK (v.3.2.2) and integrated it into a codeigniter (v.2.0) project i received from my client. I have tried every possible website url. With and without http, with and without www and with and without slashes.
Please write if you need more information.
DOCUMENTATION :
The facebook settings right now :
App name: myDomain.com
App Namespace : myDomain.com
Sandbox Mode : off
Allowed domains : myDomain.com (Also tried www.myDomain.com just to test)
Website with Facebook Login : http:// www.myDomain.com/
THE HTTP REQUEST (I highlighted the most important) :
GET /dialog/oauth?client_id=416398375038503&redirect_uri=http%3A%2F%2Fwww.myDomain.com%2F&state=c7fcaa638bb00e28177b2551ab285199&scope=email HTTP/1.1
Host: www.facebook.com
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
Referer: **http://www.myDomain.com/**
Accept-Encoding: gzip,deflate,sdch
Accept-Language: da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: locale=da_DK; datr=c352UWXk3ZNnDRb9vF_flCKf; lu=ThIiiPnfHJO6URgttq6n991g; p=30; presence=EM371808349EuserFA21015531322A2EstateFDsb2F1371646911100Et2F_5b_5dElm2FnullEuct2F1371756338BEtrFnullEtwF2809378943EatF1371808247422EwmlFDfolderFA2inboxA2Ethread_5fidFA2user_3a1275290355A2CG371808349901CEchFDp_5f1015531322F9CC; sub=8192; act=1371810189642%2F3; c_user=1015531322; csm=2; fr=0Q2dUDn4VqDw2NwPO.AWUeSLjGpJH-4uKuONHiGbL-jYE.BRdn55.S8.AWVTnqQG; s=Aa7pqsZ0XxblFusE.BRwH3a; xs=1%3A7IUHTcAXzyAQdg%3A2%3A1371569626; wd=1363x712
Query String Parametersview sourceview URL encoded
client_id:416398375038503
redirect_uri: **http://www.myDomain.com/**
state:c7fcaa638bb00e28177b2551ab285199
scope:email
Want to improve this post? Add citations from reputable sources by editing the post. Posts with unsourced content may be edited or deleted.
Try once by removing the Allowed domains setting