Courtesy Redirect with NancyFx - angularjs

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 + "/");
}
}

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.

With Angularjs, $http post return response error in Microsoft Edge

Well, while I develop an admin page for test,
a weird problem occurred in Microsoft Edge.
Here's part of source code to fetch response from server of loginCtrl.js
$http({
method: 'POST',
url: Define.apiUrl + 'admin/login',
data: {
user_id: $scope.login_email,
password: $scope.login_password
}
})
.then(function (response) {
if (response.data.success) {
$cookieStore.put(Define.userInfo, response.data.info);
$cookieStore.put(Define.userToken, response.data.token);
}
}, function (data) {
console.log('errors!');
console.log(data);
});
This works well in Chrome and IE
But in Microsoft Edge, This returns error like below
data = null
status = -1
statusText = ""
and below are each status of related files.
# loginCtrl.js
## Chrome response status
Accept-Ranges:bytes
Cache-Control:public, max-age=0
Connection:keep-alive
Content-Length:1877
Content-Type:application/javascript
Date:Fri, 18 Aug 2017 04:06:49 GMT
ETag:W/"755-15df385a23e"
Last-Modified:Fri, 18 Aug 2017 04:06:47 GMT
## Chrome request status
Accept:'*/*'
Accept-Encoding:gzip, deflate, br
Accept-Language:ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Host:localhost:9000
If-Modified-Since:Fri, 18 Aug 2017 02:51:00 GMT
If-None-Match:W/"6f5-15df340413d"
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/60.0.3112.101 Safari/537.36
## Edge response status
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Connection: keep-alive
Content-Length: 1807
Content-Type: application/javascript
Date: Fri, 18 Aug 2017 02:06:14 GMT
ETag: W/"70f-15df3173adf"
Last-Modified: Fri, 18 Aug 2017 02:06:12 GMT
## Edge request status
Accept: application/javascript, '*/*'; q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: ko-KR
Connection: Keep-Alive
Host: localhost:9000
Referer: http://localhost:9000/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063
I wonder why only Edge cannot get right responses.
I tried to make headers like 'Content-Type', 'Cache-Control' or add config like cache : false.
But these couldn't fix this problem.
Did I miss something??
Plz any handsome or pretty programmer save me
I've tried to find solution of this, and finally I got one.
Some answers suggested adding tags like
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="Mon, 26 Jul 1997 05:00:00 GMT" />
or adding code into config like
$httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
// extra
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
but these couldn't solve this.
Finally I saw one answer said this may occurred by a kind of policy handling caches in Edge.
This may occur when I use local server to send requests or get responses.
And it will gonna disappear when test on other server not on local.
Actually, I'm still using local server, so I don't know whether this work or not.

How to set Cache-Control headers in Apache Camel

I am using Apache camel 2.15.1 version. In this I am using servlet component for rest dsl. My simple route looks like below
from(rest:get:CustomerDetails.json)
.to("http://localhost:8080/customer/getCustomerDetails?bridgeEndpoint=true");
I have a requirement to set Cache-Control and Pragma headers for response.
from(rest:get:CustomerDetails.json)
.to("http://localhost:8080/customer/getCustomerDetails?bridgeEndpoint=true")
.setHeader("Cache-Control",constant("private, max-age=0,no-store"));
But camel ignores this. I read few others blog which suggests to use a custom HeaderFilterStrategy. I tried with this as well. It didn't help.
https://access.redhat.com/documentation/en-US/Red_Hat_JBoss_Fuse/6.0/html/Web_Services_and_Routing_with_Camel_CXF/files/Proxying-Headers.html
https://issues.apache.org/jira/browse/CAMEL-6085
Any help to fix this issue is highly appreciated.
You can get it to work with custom HeaderFilterStrategy. The trick is to configure it in restConfiguration().endpointProperties(..) like this:
public void configure() {
JndiRegistry registry = getContext().getRegistry(JndiRegistry.class);
registry.bind("filter", new HeaderFilter());
restConfiguration()
.host("localhost")
.endpointProperty("headerFilterStrategy","#filter")
.setPort("10000");
from("rest:get:hello")
.to("http://localhost:20000?bridgeEndpoint=true")
.setHeader("Cache-Control",constant("private, max-age=0,no-store"));
from("netty-http:http://localhost:20000")
.setBody(constant("ok"));
}
where #filter is just dummy implementation like this (you can create a filter that suits better your needs)
public class HeaderFilter implements HeaderFilterStrategy {
#Override
public boolean applyFilterToCamelHeaders(String arg0, Object arg1, Exchange arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean applyFilterToExternalHeaders(String arg0, Object arg1, Exchange arg2) {
// TODO Auto-generated method stub
return false;
}
}
Now if if run my routes without .endpointProperty("headerFilterStrategy","#filter") line I get output like this
$ curl -D - http://localhost:10000/hello
HTTP/1.1 200 OK
Accept: */*
breadcrumbId: ID-myhost-40508-1441899753215-0-1
User-Agent: curl/7.35.0
Content-Length: 2
Connection: keep-alive
ok
and with .endpointProperty("headerFilterStrategy","#filter") line output like this
$ curl -D - http://localhost:10000/hello
HTTP/1.1 200 OK
Accept: */*
breadcrumbId: ID-myhost-56308-1441899833287-0-1
Cache-Control: private, max-age=0,no-store
CamelHttpMethod: GET
CamelHttpResponseCode: 200
CamelHttpUri: /hello
CamelHttpUrl: http://localhost:10000/hello
CamelNettyChannelHandlerContext: org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext#1fac34b
CamelNettyLocalAddress: /127.0.0.1:10000
CamelNettyMessageEvent: [id: 0x93dfe147, /127.0.0.1:35302 => /127.0.0.1:10000] RECEIVED: DefaultHttpRequest(chunked: false) GET /hello HTTP/1.1 User-Agent: curl/7.35.0 Host: localhost:10000 Accept: */*
CamelNettyRemoteAddress: /127.0.0.1:35302
User-Agent: curl/7.35.0
Content-Length: 2
Connection: keep-alive
ok

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

PHP ZF2 - Restful controller Backbone PUT method incorrect parsing

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.

Resources