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.
Related
I try to send POST multipart/form-data but without attached file. It's like the client sends sign up form with email + password and without avatar file(this field isn't required).
HTTP request:
POST https://.../profile/user/own
headers=
Authorization: bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiIwN2NjMDUzYS0wMTczLTExZWItOWI1OC0wMTg4NjFhYmViYjAiLCJzY29wZSI6WyJjbGllbnQiXSwiZXhwIjoxNjAxMzc0MzEzLCJ1dWlkIjoiMDdjYzA1M2EtMDE3My0xMWViLTliNTgtMDE4ODYxYWJlYmIwIiwiYXV0aG9yaXRpZXMiOlsiUGF5bWVudE1hcmtldENsaWVudCIsImxvYmJ5X2NoYXQiLCJVc2VyQmFsYW5jZSIsInVzZXItc2xvdC1yZWFkIiwibGVhdmVfY2FsbCIsInJlYWRfc2NoZWR1bGVfdXNlciIsInVzZXItY2FuY2VsLXNsb3QiLCJyZWFkX3VzZXJfcXVlc3Rpb25uYWlyZSIsIndyaXRlX3RpbWV6b25lIiwicmVhZF90aGVyYXBpc3RzX2luZm8iLCJlbmRfc2Vzc2lvbiIsImpvaW5fY2FsbCIsImVkaXRfdXNlciIsImFuc3dlcl9hY3Rpb24iLCJyZWFkX3Nlc3Npb24iLCJQYXltZW50VmVyaWZpQ2xpZW50IiwiYmVnaW5fc2Vzc2lvbiIsIm9jY3VweS1zbG90Iiwid3JpdGVfbWVzc2FnZSIsInJlYWRfdXNlciIsInJlYWRfY29udmVyc2F0aW9uIiwicmVhZF9jaGF0IiwicmVhZF9jdXJyZW50X2NoYXQiLCJzb2NrZXQiLCJtYWtlX2NhbGwiLCJyZWFkX2NhbGwiLCJyZWFkX21lc3NhZ2UiLCJjYWxsX3Rva2VuIl0sImp0aSI6Ijg1NjQ5MmJhLTI0ODUtNDAyZC1hZTJhLWZiY2E2YjhkNGY2MSIsImNsaWVudF9pZCI6ImNsaWVudCJ9.APWse9P8SIJtDMMay8UTT9CN_JEvSIRaznn8JALcYfxz107IaL5ezwEJfIEDBb9_WEDeVKvpjI1eUmiYBQiOcF5LkIPhpww_8vaSbWvWP3Tkg21QQceNEZwnjucMc6Doj1YNlx3iOs03Mv8zmOJZ2S1acz5sVj5cK_ufrItG7Ic_-bbpW67Byl1vNgbTgaJoGMRAgqfCxKpAVpxMFqNw3F8FMKe0dm-uYmJwpKlWVg4sEUOW7LSZ6wr3c5XgBHXVvTzVFb0sJyhFkw9W1nrMSJTxJqsaVGEzIe01qhQZasbRkMxC32XXlFzpGSmBDJpdWpTD3pUXrIhD4v15PWt3wg
accept: */*
host: api.dev.psychicbook.net
content-type: multipart/form-data
content-length: 108
formBody=
userData: {"email":"automation.tku1fin9av3#test.com","nickname":"5SkHTB0EVs"}
=========================
HTTP response:
status=
500
headers=
Server: nginx/1.17.10
Date: Mon, 28 Sep 2020 10:11:53 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE,OPTIONS
Access-Control-Max-Age: 3600
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
X-Application-Context: gateway-service:develop:8765
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Strict-Transport-Security: max-age=15724800; includeSubDomains
body=
{"timestamp":1601287913987,"status":500,"error":"Internal Server Error","exception":"org.springframework.web.multipart.MultipartException","message":"Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found","path":"/profile/user/own"}
There is a special method for file uploading -> .formUpload("file", "image.jpg"), but I don't want to send any file.
If I make the same with Insomnia or anoter REST client, everything is OK, and it looks like:
HttpResponse<String> response = Unirest.post("https://.../profile/user/own")
.header("authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJjMGRlNWI3ZS0wMTYzLTExZWItOWI1OC0wMTg4NjFhYmViYjAiLCJzY29wZSI6WyJjbGllbnQiXSwiZXhwIjoxNjAxMzY3NzUyLCJ1dWlkIjoiYzBkZTViN2UtMDE2My0xMWViLTliNTgtMDE4ODYxYWJlYmIwIiwiYXV0aG9yaXRpZXMiOlsiUGF5bWVudE1hcmtldENsaWVudCIsImxvYmJ5X2NoYXQiLCJVc2VyQmFsYW5jZSIsInVzZXItc2xvdC1yZWFkIiwibGVhdmVfY2FsbCIsInJlYWRfc2NoZWR1bGVfdXNlciIsInVzZXItY2FuY2VsLXNsb3QiLCJyZWFkX3VzZXJfcXVlc3Rpb25uYWlyZSIsIndyaXRlX3RpbWV6b25lIiwicmVhZF90aGVyYXBpc3RzX2luZm8iLCJlbmRfc2Vzc2lvbiIsImpvaW5fY2FsbCIsImVkaXRfdXNlciIsImFuc3dlcl9hY3Rpb24iLCJyZWFkX3Nlc3Npb24iLCJQYXltZW50VmVyaWZpQ2xpZW50IiwiYmVnaW5fc2Vzc2lvbiIsIm9jY3VweS1zbG90Iiwid3JpdGVfbWVzc2FnZSIsInJlYWRfdXNlciIsInJlYWRfY29udmVyc2F0aW9uIiwicmVhZF9jaGF0IiwicmVhZF9jdXJyZW50X2NoYXQiLCJzb2NrZXQiLCJtYWtlX2NhbGwiLCJyZWFkX2NhbGwiLCJyZWFkX21lc3NhZ2UiLCJjYWxsX3Rva2VuIl0sImp0aSI6Ijg5ZDg4OTViLTU1NzQtNDk2OC1hNmJhLWRmZjcyYmIxYWI1MyIsImNsaWVudF9pZCI6ImNsaWVudCJ9.bW7F65elarJNQ9RkfIJcH0uq9Og0ue8TXNZ7Gh_FFCdj_c8SVHlPXwu-nEoZZSTVk3gBB2I_hw8MqPfCZVZrlAlzyIfAcyuQ1WRgRH5-xVzYej3XqBEADuCjBabcO87LoPwz_vYCT3JZVhNZHcDMOkQ429dg0HdKeSBd6qJaPYCgWgq529b9-wnufNBx9LHyaTYLWZC5nMfmDbyep3sc2_q6YzqKMMH5a-s1SmOgQpKbCNyCx7gui3tiYqQh21zMN-PhtkRNAD78awzpIpZhuZTF-AbrQkI6J1Yvsg59AYkZZVBd5gyCSopydquezf7xaAc3Ot2L-DubGzWwr2u9gA")
.header("content-type", "multipart/form-data; boundary=---011000010111000001101001")
.body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"userData\"\r\n\r\n{\"email\":\"automation.tku1fin9av3#test.com\",\"nickname\":\"qatest5\"}\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n\r\n-----011000010111000001101001--\r\n")
.asString();
How can I make the same but with Gatling?
I had the same issue. I have some entries with, and some without files. Both need to be uploaded using body parts.
When i set one fields using StringBodyPart it worked for me:
val uploadDocument = doIfEqualsOrElse(session => session("file").as[String], "") {
// executed if the session value stored in "myKey" starts with "admin"
exec(
http("upload: ${title}")
.post(
clientPortalUrl + "/customerportal/api/documents"
)
.headers(multipartUploadHeaders)
//if we do not call formUpload() we need set one field using StringBodyPart, the rest will follow.
.bodyPart(StringBodyPart("title", "${title}")).asMultipartForm
.formParam("documentType", "${documentType}")
.formParam("accountId", "${accountId}")
.formParam("period", "${period}")
.formParam("endDate", "${endDate}")
.formParam("signer", "${signer}")
.formParam("nexusRecipient", "${nexusRecipient}")
.formParam("vatFiscalEntityDivision", "${vatFiscalEntityDivision}")
.formParam("editor", "${editor}")
.formParam("repeatable", "${repeatable}")
.requestTimeout(5.minutes)
.check(status.is(201))
.check(jsonPath("$.title").exists)
)
} {
exec(
http("upload: ${title}")
.post(
clientPortalUrl + "/customerportal/api/documents"
)
.headers(multipartUploadHeaders)
.formParam("title", "${title}")
.formParam("documentType", "${documentType}")
.formParam("accountId", "${accountId}")
.formParam("period", "${period}")
.formParam("endDate", "${endDate}")
.formParam("signer", "${signer}")
.formParam("nexusRecipient", "${nexusRecipient}")
.formParam("vatFiscalEntityDivision", "${vatFiscalEntityDivision}")
.formParam("editor", "${editor}")
.formParam("repeatable", "${repeatable}")
.formUpload("files[]", "${file}")
.requestTimeout(5.minutes)
.check(status.is(201))
.check(jsonPath("$.title").exists)
)
}
I'm using angular to POST to an authentication endpoint; on the server side, I can see the request succeed, and proper CORS headers are set. Angular's origin is http://localhost:9000
On the server side, preflight OPTIONS requests always get a 200 back, so that seems OK.
On the client side, the $http.post always fails with an error code of 0, which from other research suggests something is still wrong with CORS. I've read the spec and tried a number of other answers, yet something is still missing.
Angular POSTs like this:
$http({
method: 'POST',
url: 'http://localhost:3000/auth/login',
data: {
username: $scope.username,
password: $scope.password
}
})
.then(function (response) {
/* etc. etc. */
}, function (response) {
/* This always triggers, with response.status = 0 */
console.log("ERROR: " + response.data);
console.log("Status: " + response.status);
console.log("Status text: " + response.statusText);
console.log("Headers: " + response.headers);
$scope.error = 'Something went wrong...';
});
Using curl to debug what the server is sending back, this is it:
< HTTP/1.1 302 Found
< X-Powered-By: Express
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS
< Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, Content-Length, X-Requested-With
< Access-Control-Allow-Credentials: true
< Set-Cookie: ua_session_token=(blahblah); Path=/
< Location: /
< Vary: Accept
< Content-Type: text/plain; charset=utf-8
< Content-Length: 23
< Date: Mon, 28 Dec 2015 15:08:17 GMT
< Connection: keep-alive
This is why I'm at a loss, as per the specification, the server seems to be doing the right thing?
Here's what the server gets from the client in terms of request headers:
HEADER host localhost:3000
HEADER content-type application/json;charset=UTF-8
HEADER origin http://localhost:9000
HEADER content-length 38
HEADER connection keep-alive
HEADER accept application/json, text/plain, */*
HEADER user-agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9
HEADER referer http://localhost:9000/
HEADER accept-language en-us
HEADER accept-encoding gzip, deflate
UPDATE tried something else with no luck, based on this post. It would seem Access-Control-Allow-Headers is case-sensitive, and angular is sending on the request accept, origin, content-type. I tweaked the server to parrot back the same, with no luck.
Alright, after applying my head to my keyboard for several hours, I've fixed it.
The answer seems to be that angular really doesn't like getting redirects in response to POST. When I changed the server endpoint to return just a plain auth token as text (the same token it was setting as a cookie anyway) rather than returning a redirect, the angular POST started working like a charm and falling through to the success handler.
Not sure I got deep enough into this to know why angular was behaving in that way; by playing around with it I found that if the redirect the server sent was to a nonexistent (404) URL that this could be replicated, EVEN IF the original POST returned that valid redirect.
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
We are battling trying to get html5mode working with AngularJs, the last hurdle is to recreate the courtesy redirect that IIS does as such:
Request
GET http://localhost/foo HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-US
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Host: ws7-agentry2
IIS Response
HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=UTF-8
Location: http://localhost/foo/
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Fri, 18 Jul 2014 17:09:20 GMT
Content-Length: 147
<head><title>Document Moved</title></head>
<body><h1>Object Moved</h1>This document may be found here</body>
The issue is that regardless of the request containing a trailing slash or not, the request object in the Nancy pipeline is identical. Since we can not differentiate between the two, we can not return a redirect without causing an infinite loop of redirects. We have tried to use url rewrites to accomplish this but to no avail, ideally I would like to get the raw url.
thanks in advance
In case anyone else needs to achieve the same results, which is to get html5mode working with IE9 & NancyFx, had to build a httpmodule as this article shows though I believe the title is wrong:
public class CourtesyRedirectModule : IHttpModule {
public void Dispose() {}
public void Init(HttpApplication context) {
context.BeginRequest += context_BeginRequest;
}
private void context_BeginRequest(object sender, EventArgs e) {
if (HttpContext.Current.Request.Url.PathAndQuery.Equals(HttpContext.Current.Request.ApplicationPath))
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ApplicationPath + "/");
}
}
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.