PHP ZF2 - Restful controller Backbone PUT method incorrect parsing - backbone.js

I have an issue with my ZF2 based application and Backbone at frontend. Somewhere at frontent I run
this.model.save({
city_id: parseInt( this.$el.find( '#city_id' ).val() ),
from: this.$el.find( '#from' ).val(),
to: this.$el.find( '#to' ).val(),
price: parseInt( this.$el.find( '#price' ).val() )
});
I turn on my Chrome sniffer and see the request details:
PUT /account/trip/2 HTTP/1.1
Host: jamydays.ru
Connection: keep-alive
Content-Length: 186
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://jamydays.ru
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31
Content-Type: application/json
Referer: http://jamydays.ru/account
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
Cookie: PHPSESSID=pekjbefmi1jn01q5fgm4gu6jk0; _ym_visorc=w
And request payload is:
{"from_formatted":"10 маÑ","to_formatted":"19 маÑ","url":"/account/trip","id":2,"city_id":65170,"city":"Baardheere","from":"10-05-2013","to":"19-05-2013","price":500,"is_active":1}
Conroller used to handle this request runs appropriate action:
class TripController extends AbstractRestfulController{
...
public function update( $id, $data ){ var_dump( $id, $data );exit(); }
...
}
My trouble is that I see in result this:
string(1) "2"
array(1) {
["{"from_formatted":"10_мая","to_formatted":"19_мая","url":"/account/trip","id":2,"city_id":65170,"city":"Baardheere","from":"10-05-2013","to":"19-05-2013","price":500,"is_active":1}"]=>
string(0) ""
}
Here we see that id parsed good, but all data fall into key of some strange array. Now I am retrieving data from this key, but guess this is bad way. Could anybody help me to figure out how to make controller parse data appropriate.
UPDATE
Well it seems the solution is just to update ZF2 to 2.2 stable version.

Question is solved. If you face the same trouble just update your ZF2 to 2.2 stable version or later.

Related

Missing Csrf token cookie

I'm relatively new to CakePHP (v3.7). I have an application in which I'm getting a "Missing Csrf Token Cookie" error.
In Application.php, I have:
$options = []; // I'm fine with the default options.
$csrf = new CsrfProtectionMiddleware($options);
$middlewareQueue->add($csrf);
The form page has a hidden form element with the _csrfToken in it.
I'm confused as to why it's not being found on the POST?
Digging further, I found that in CsrfProtectionMiddleware.php, the _validateToken() function below behaves as follows:
$cookies is null (there are no cookies set.)
thus, $cookie is null.
$post actually contains the content of the _csrfToken parameter from the hidden parameter on the page. However the function never looks at it. Because $cookie is null,
the if(!$cookie) statement causes an InvalidCsrfTokenException to be thrown.
protected function _validateToken(ServerRequest $request)
{
$cookies = $request->getCookieParams();
$cookie = Hash::get($cookies, $this->_config['cookieName']);
$post = Hash::get($request->getParsedBody(), $this->_config['field']);
$header = $request->getHeaderLine('X-CSRF-Token');
if (!$cookie) {
throw new InvalidCsrfTokenException(__d('cake', 'Missing CSRF token cookie'));
}
if (!Security::constantEquals($post, $cookie) && !Security::constantEquals($header, $cookie)) {
throw new InvalidCsrfTokenException(__d('cake', 'CSRF token mismatch.'));
}
}
}
Obviously, the middleware is expecting an actual cookie, in addition to a hidden parameter. Where is this cookie set (or supposed to be set?)
Update:
I checked on the browser side. The cookie is being set, but the browser isn't returning it on the POST request.
Here's CakePHP's RESPONSE to the original GET request to populate the page:
Connection: Keep-Alive
Content-Length: 3013
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2019 23:07:31 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.33 (Unix) PHP/7.1.1
Set-Cookie: csrfToken=b553dd2e06e57f6d514ee41a120e1c60084adafddfbaa6f72db1f7f590fcf50143876ac817d29d6f1cf9a786031d6235ba21e265b9d3b2a0ee4535854f048b66; path=/webroot/
X-Powered-By: PHP/7.1.1
Note the csrfToken cookie.
... and here's the POST that the browser sends back with the form data
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 184
Content-Type: application/x-www-form-urlencoded
DNT: 1
Host: *************
Origin: ****************
Pragma: no-cache
Referer: ***************
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36
Query String Parameters
redirect: /Users/login
Form Data
_method: POST
_csrfToken: b553dd2e06e57f6d514ee41a120e1c60084adafddfbaa6f72db1f7f590fcf50143876ac817d29d6f1cf9a786031d6235ba21e265b9d3b2a0ee4535854f048b66
username: xxxxxxxxxx
password: xxxxxxxxxx
Note that it's sending back the hidden form parameter _csrfToken, but NOT the cookie.
Thanks for any help...
This turned out to be a problem with the DOCUMENT_ROOT directory setting in Apache. It was set to the parent directory of webroot, instead of to webroot itself. When I changed it everything worked.

Cross Origin call is not allowing in browser

I am trying to call one application to another where I am getting and error as "Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response." and in my back-end I have used the following code as mentioned below
List<String> originList = Arrays.asList(origins.trim().split("( )*,( )*"));
String origin = request.getHeader("Origin");
if (originList.contains(origin)) {
originAllow = origin;
} else {
originAllow = originList.get(0);
}
response.setHeader("Access-Control-Allow-Origin", originAllow);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, accept, authorization");
response.setHeader("Access-Control-Expose-Headers", "Location");
In originAllow I am passing the url which I am trying to access but I am getting the below error,
XMLHttpRequest cannot load http://<<url>>. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Please find the browser request and response header,
Response Header
Access-Control-Allow-Headers:x-requested-with, content-type
Access-Control-Allow-Methods:GET OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Connection:close
Content-Length:0
Content-Type:text/plain; charset=UTF-8
Server:Apache-Coyote/1.1
X-Application-Context::8080
Request Header
Accept:/
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ms;q=0.6
Access-Control-Request-Headers:authorization, x-requested-with
Access-Control-Request-Method:GET
Connection:keep-alive
Host:myrestapi-dev
Origin:http://localhost:9000
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
OPTIONS <>?page=0&search_param=test&size=10,desc HTTP/1.1
Host: myrestapi-dev
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:9000
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Access-Control-Request-Headers: authorization, x-requested-with
Accept: /
Referer: http://localhost:9000/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,ms;q=0.6
I am running application in localhost:port and the other application is using deployed url where the protocol,host are different.
Please let me know Is there anything I need to add to access the url from ui(angular) for authorization moreover it is working in other browser but not in chrome
this is because your server isn't allowing the authorization header.
To address it:
response.setHeader("Access-Control-Allow-Headers", "Content-Type, authorization");
should help you. as I am not sure about your backend I need to explain a bit more.
This is because it is up to the server to specify that it accepts cross-origin requests (and that it permits the Content-Type request header).Moreover, You need to make AJAX call from the same domain or make server-side changes, allowing requests from external domains.To address this you need to make changes in headers at http://yourdomain.com by allowing your external domain in headers:
Access-Control-Allow-Origin: *
1- ref1
2- ref2
Possible solution in AngularJs. : Using JSONP with Angular
The AngularJS $http service has a built-in method called "jsonp".
var url = "some REST API Url" + "?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
// whatever
});
Also, the url had to be appended with ?callback=JSON_CALLBACK.
I am going to expand this solution using JSONP
exampleurl = 'http://wikidata.org/w/api.php?whatever....&format=json'
//Number 1 :
$.ajax({
dataType: "jsonp",
url: exampleurl ,
}).done(function ( data ) {
// do whatever
});
//Number 2 :
$.ajax({
dataType: "json",
url: exampleurl + '&callback=?',
}).done(function ( data ) {
// do whatever
});
//Number 3 :
$.getJSON( exampleurl + '&callback=?', function(data) {
// do whatever
});
more information
1- getJson
2-$.Ajax

$http.post() method is actally sending a GET

NOTE:
I've found a possibly related issue that warrants a new question here
This is a weird problem. I've been using angular over the course of 2 years and have never run into this problem.
I'm using angular v1.5.0. I'm making a post request like this:
$http({
method: "POST",
url: "/myurl",
data: {
file: myFile // This is just an object
}
});
Run-of-the-mill POST request right? Get this. I look in the console and the Network tab logs the request as a GET. Bizarre. So I've jiggered the code to work like this:
$http.post("/myurl", {file: myFile});
Same thing. After stepping through the $http service code I'm confident that the headers are being set properly. Has anyone else run into this problem?
Update
Taking germanio's advice, i've tried using the $resource service instead:
promise = $resource("/upload").save()
(this returns an error for another reason, it still executes the POST properly). I'm having the same problem: the request is logged as a GET in the console.
Here are the headers of the request when it gets to my server:
GET /myurl/ HTTP/1.1
Host: localhost:8001
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cache-Control: no-cache
Connection: keep-alive
Pragma: no-cache
Referer: http://localhost:8001/myurl/
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
Update 2
As per georgeawg's suggestion I've used an interceptor to log the request at its various stages. Here is the interceptor code:
$httpProvider.interceptors.push(function() {
return {
request: function(config) {
console.log(config);
return config;
}
}
}
Having run this code I get this logged:
data:Object // contains file object
headers: Object // has Content-Type set to multipart
method:"POST" // ???
url :"/myurl
So this means the request is being sent as a POST from within Angular, but it is still logged as a GET both in the browser and on my server. I think there is something low level at work here about the HTTP protocol that I dont understand.
Is the request sent to the server before it is actually logged in the browser? If so, that might atleast point to my server as the culprit.
In the hopes of finding out whats going on, here is my server code:
type FormStruct struct {
Test string
}
func PHandler(w http.ResponseWriter, r *http.Request) {
var t FormStruct
req, _ := httputil.DumpRequest(r, true)
log.Println(string(req))
log.Println(r.Method) // GET
log.Println(r.Body)
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&t)
log.Println("Decoding complete")
if err != nil {
log.Println("Error")
panic(err.Error()+"\n\n")
}
log.Println(t.Test)
w.Write([]byte("Upload complete, no errors"))
}
func main() {
http.HandleFunc("/myurl/", PHandler)
fmt.Println("Go Server listening on port 8001")
http.ListenAndServe(":8001", nil)
}
My server throws an EOF error when it receives the request:
2016/03/30 10:51:37 http: panic serving [::1]:52039: EOF
Not sure what an EOF would even mean in this context.
Update 3
By the suggestion of another use, I tried using POSTMAN to hit my server with a fake POST request. The server receives the request properly. This means to me that there is something up with how angular is making the POST request. Please help.
Any ideas?
Full server logs:
Go Server listening on port 8001
2016/03/30 11:13:08 GET /myurl/ HTTP/1.1
Host: localhost:8001
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json
Postman-Token: 33d3de90-907e-4350-c703-6c57a4ce4ac0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
X-Xsrf-Token: null
2016/03/30 11:13:08 GET
2016/03/30 11:13:08 {}
2016/03/30 11:13:08 Decoding complete
2016/03/30 11:13:08 Error
2016/03/30 11:13:08 http: panic serving [::1]:52228: EOF
goroutine 5 [running]:
net/http.(*conn).serve.func1(0xc820016180)
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:1389 +0xc1
panic(0x3168c0, 0xc82000b1a0)
/usr/local/Cellar/go/1.6/libexec/src/runtime/panic.go:426 +0x4e9
routes.FUPHandler(0x1055870, 0xc820061ee0, 0xc820104000)
/Users/projectpath/routes.go:42 +0x695
net/http.HandlerFunc.ServeHTTP(0x4e7e20, 0x1055870, 0xc820061ee0, 0xc820104000)
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:1618 +0x3a
net/http.(*ServeMux).ServeHTTP(0xc820014b40, 0x1055870, 0xc820061ee0, 0xc820104000)
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:1910 +0x17d
net/http.serverHandler.ServeHTTP(0xc820016100, 0x1055870, 0xc820061ee0, 0xc820104000)
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:2081 +0x19e
net/http.(*conn).serve(0xc820016180)
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:1472 +0xf2e
created by net/http.(*Server).Serve
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:2137 +0x44e
Update 4
I stumbled onto something interesting:
Charles logs a POST request when I post to myurl, but the response status is 301. After the POST a GET is logged. This is the GET that is hitting my server.
My server, as you can see above, does not do any sort of redirection. How is the 301 happening?
This is due to a security consideration.
In your situation when a redirect is sent back from the server to the browser, the browser will not repeat the POST request (but rather just a "simple" GET request).
Generally speaking a browser will not send POST data to a redirect URL because the browser is not qualified to decide if you're willing to send the same data to the new URL what you intended to send to the original URL (think about passwords, credit card numbers and other sensitive data). But don't try to circumvent it, simply use registered path of your handler to POST to, or any of the other tips mentioned in the linked answer.
For context see question:
Go web server is automatically redirecting POST requests
You can read more on the subject here:
Why doesn't HTTP have POST redirect?
This code actually send GET to server
$http({
method: 'POST',
params: {
LoginForm_Login: userData.username,
LoginForm_Password: userData.password
},
url: YOURURL
}).then(
You need to use transformRequest, sample below actually send POST
$http({
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
LoginForm_Login: userData.username,
LoginForm_Password: userData.password
},
url: YOURURL
}).then(

CORS - CakePHP does not accept AngularJS JSON-Request

I'm using CakePHP as backend and AngularJS as frontend, whereas front- & backend are in different domains so this is basically a CORS-situation.
Basically I'm trying to send the contents of a form to a Cake-API (later this is meant to do authentication part - but I'm failing earlier) via $http.post. So here is the code:
aeapBackend.login = function(username, password) {
return $http.post(
API_URL + 'api_mobile_user/login', {
test: username,
test2: password
}
);
};
Whereas the corresponding API in CakePHP looks like this:
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('login'));
}
public function login() {
$this->response->header(array(
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Headers' => 'Content-Type'
)
);
$this->autoRender = false;
}
What happens next is that the preflight OPTIONS request ist done - which looks quite good to me:
Request Headers:
OPTIONS /api_mobile_user/login HTTP/1.1
Host: aeap.localhost
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://asf.localhost
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53
Access-Control-Request-Headers: accept, content-type
Accept: */*
Referer: http://asf.localhost/?username_input=hjk&password_input=hjgk&login_button=
Accept-Encoding: gzip,deflate,sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Response headers:
HTTP/1.1 200 OK
Date: Wed, 05 Nov 2014 15:29:00 GMT
Server: Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.5.15
X-Powered-By: PHP/5.5.15
Set-Cookie: CAKEPHP=j6st0hnq8ear2cc6psg56d6eu3; expires=Wed, 05-Nov-2014 19:29:00 GMT; Max-Age=14400; path=/; HttpOnly
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
But when the actual POST-request is done I get an status code 403:
XMLHttpRequest cannot load http://aeap.localhost/api_mobile_user/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://asf.localhost' is therefore not allowed access. The response had HTTP status code 403.
How can I avoid this? In my opinion I already enabled CORS support for Cake ['Access-Control-Allow-Origin']. It seems to me that AngularJS posts some additional informations whioch are not checked during the preflight and then rejected by the backend.
Used versions: CakePHP 2.5.3, AngularJS: 1.3.0
Thanks to Marvin Smit I was able to determine the reason for the behavior which was not connected to CORS are the headers. I set 'Access-Control-Allow-Origin' => '*'on web-server level so I was able to get a response which pointed to the security component of CakePHP.
I basically tried to send a POST-Reuqest to an API which did not expect that data should be posted to it. Therefore the access was denied. So I had to add $this->Security->csrfCheck = false to the beforeFilter:
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('login'));
$this->Security->csrfCheck = false;
}
For what it's worth, the proper way to do this for Cakephp 3 is as follows
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('login'));
$this->eventManager()->off($this->Csrf);
}
Although, this is not recommended for AJAX requests. The following doc can help you more. CSRF And AJAX

AngularJS $resource DELETE item in collection

I have an ASP.NET Web Api (1) controller with GET, POST and DELETE actions. I am calling this from an Angular 1.2.0 RC3 app with $resource. Let's call the controller Foos.
I do a GET that returns a list of foos:
GET http://localhost:55386/api/foos/123456/1 HTTP/1.1
Host: localhost:55386
Connection: keep-alive
Accept: application/json, text/plain, */*
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,es;q=0.6
where the resource is
/api/foos/clientId/recordId
Here I am saying get me a list of foos for client x and record y
Now, I want to remove a single foo from the list of foos that I received, so I call $delete:
$scope.delete = function(foo){
foo.$delete();
}
however this results in the following request:
DELETE http://localhost:55386/api/foos/123456/1 HTTP/1.1
Host: localhost:55386
Connection: keep-alive
Accept: application/json, text/plain, */*
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,es;q=0.6
This delete is obviously trying to delete the entire list of foos, which makes sence.
My question is, how do I delete a single foo using Angular's $resource without getting each foo in its own GET request?
UPDATE:
I could do a GET /api/foo/1 where the resource is foo/fooId, and its equivalent DELETE /api/foo/1 to delete it but I want to get a list of foos instead of each foo individually.
I know that is not the question but you should restangular https://github.com/mgonto/restangular. It is easier to interact with rest services
I was misunderstanding how $resource works. I assumed thatfoo knew how to delete itself as it is a Resource 'instance' in the following function:
$scope.delete = function(foo){
foo.$delete();
}
The correct approach is:
$scope.delete = function(foo){
Api.delete({
id: foo.Id,
clientId : $scope.clientId,
recordId : $scope.recordId
});
}
You have to manually tell the $resource instance to use the id of foo so that the url includes the foo id and does the following DELETE
DELETE http://localhost:55386/api/foos/123456/1/123 HTTP/1.1
where 123 is fooId

Resources