CakePHP 403 on AJAX request - cakephp

I'm trying to use AJAX to autocomplete a search box on my website. I was using firebug to test my application. When I try to search something, Firebug tells me that the AJAX request returned a 403 forbidden error. However, when I copy the EXACT URL that was in the AJAX request, it returns the correct data.
Edit:
I think this has to be something on the JavaScript side. Are there any headers that might be omitted with an AJAX request compared to a normal request?
Here is the $_SERVER variable (I removed the parameters that were the same on both requests) on an AJAX request that failed (1) vs typing the URL in and it works (2):
(1)
2011-04-02 13:43:07 Debug: Array
(
[HTTP_ACCEPT] => */*
[HTTP_COOKIE] => CAKEPHP=0f9d8dc4cd49e5ca0f1a25dbd6635bac;
[HTTP_X_REQUESTED_WITH] => XMLHttpRequest
[REDIRECT_REDIRECT_UNIQUE_ID] => TZdgK654EmIAAEjknsMAAAFG
[REDIRECT_UNIQUE_ID] => TZdgK654EmIAAEjknsMAAAFG
[REMOTE_PORT] => 60252
[UNIQUE_ID] => TZdgK654EmIAAEjknsMAAAFG
[REQUEST_TIME] => 1301766187
)
(2)
2011-04-02 13:44:02 Debug: Array
(
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
[HTTP_COOKIE] => CAKEPHP=d8b392a5c3ee8dd948cee656240fd5ea;
[REDIRECT_REDIRECT_UNIQUE_ID] => TZdgYq54EmIAAF7zt6wAAAJJ
[REDIRECT_UNIQUE_ID] => TZdgYq54EmIAAF7zt6wAAAJJ
[REMOTE_PORT] => 60281
[UNIQUE_ID] => TZdgYq54EmIAAF7zt6wAAAJJ
[REQUEST_TIME] => 1301766242
)

I think I found the solution. I set the security level to medium to solve the issue. I found this line in the config folder. Does a medium security level pose any problems in production?
/**
* The level of CakePHP security. The session timeout time defined
* in 'Session.timeout' is multiplied according to the settings here.
* Valid values:
*
* 'high' Session timeout in 'Session.timeout' x 10
* 'medium' Session timeout in 'Session.timeout' x 100
* 'low' Session timeout in 'Session.timeout' x 300
*
* CakePHP session IDs are also regenerated between requests if
* 'Security.level' is set to 'high'.
*/
Configure::write('Security.level', 'medium');
Edit: This is definitely the solution. Here's what was happening:
When the security level is set to high, a new session ID is generated upon every request.
That means that when I was making ajax requests, a new session ID would be generated.
If you stay on the same page, JavaScript makes a request, which generates a new session_id, and doesn't record the new session_id.
All subsequent ajax requests use an old session_id, which is declared invalid, and returns an empty session.

If you are using Auth, you need to make sure that you are logged in if the controller/action is not on your $this->Auth->allow() list.
Make sure you set debug to 0 as well, might cause you some problems.

Maybe it's the Cross site request forgery component. It's responsible for all authentication requests, except GET requests. Look at this: http://book.cakephp.org/3.0/en/controllers/components/csrf.html

Related

Gatling overrides `Cookie` header with the `Set-Cookie` header of previous response

I have an http request in Gatling that gets executed 10 times:
val scnProxy = scenario("Access proxy")
.exec(session => session.set("connect.sid", sessionId))
.repeat(10) {
exec(
http("Access endpoint")
.get("/my-api")
.header(
"Cookie",
session => "connect.sid=" + session("connect.sid").as[String]
)
.check(status is 200)
)
}
For some reason, I get the intended response only on the first iteration. On every other iteration, I keep getting 401. So, I changed log level to TRACE to see what the problem is and found a weird behavior. For the first iteration, I get the header Cookie: connect.sid=... but for some reason, on second and other iterations, the cookie parameter gets overridden by the set-cookie of the previous request. Since Cookie header value is a string, it does not merge these cookies.
Is there a way that I can add a cookie instead of my cookie getting overriden?
Use the proper Gatling components for manipulating cookies.

CakePHP Authentication Middleware not called

I used AuthComponent a lot but am new to AuthenticationMiddleware. I follow almost exactly https://book.cakephp.org/authentication/2/en/index.html except the username field is username instead of email. But when I try to get a page requiring authentication, Cake throws UnauthenticatedException in AuthenticationComponent::doIdentityCheck(). This can be understood because Cake should have redirected me to /users/login, which it did not. I tried
$service->loadAuthenticator('Authentication.Form', [
'loginUrl' => '/users/login' // case 1
// or case 2 'loginUrl' => \Cake\Routing\Router::url('/users/login'),
// or case 3 omit this to use the default
In all the above cases Cakes throws UnauthenticatedException with the message:
No identity found. You can skip this check by configuring requireIdentity to be false.
Also http://localhost:8765/users/login leads me to the correct page, also I can see the list of users by http://localhost:8765/users/ if I allow unauthenticated as this:
// UsersController.php
public function initialize() : void {
parent::initialize();
$this->Authentication->allowUnauthenticated(['index', 'login']);
}
My environment: CakePHP 4.0, authentication plugin 2.0. Is there a way to verify that AuthenticationMiddleware has indeed been set up and added to the middleware queue?
You'd get a different error if the middleware didn't ran, one that would complain about the authentication attribute missing on the request object.
You need to configure the unauthenticatedRedirect option on the service object in order for redirects being issued for unauthenticated requests, without that option being configured you'll receive exceptions instead. Additionally you may need to set the queryParam option (that's the query string parameter that will hold the initially accessed URL) if you want to be able to redirect users after successfully logging in.
$service->setConfig([
'unauthenticatedRedirect' => '/users/login',
'queryParam' => 'redirect',
]);
That seems to be missing from the docs, it's only mentioned in the migration notes. You may want to open an issue for that over at GitHub. The quickstart guide example has been updated to include the redirect configuration.

How can an HTTP 403 be returned from an apache web server input filter?

I have written an apache 2.x module that attempts to scan request bodies, and conditionally return 403 Forbidden if certain patterns match.
My first attempt used ap_hook_handler to intercept the request, scan it and then returned DECLINED to the real handler could take over (or 403 if conditions were met).
Problem with that approach is when I read the POST body of the request (using ap_get_client_block and friends), it apparently consumed body so that if the request was subsequently handled by mod_proxy, the body was gone.
I think the right way to scan the body would be to use an input filter, except an input filter can only return APR_SUCCESS or fail. Any return codes other than APR_SUCCESS get translated into HTTP 400 Bad Request.
I think maybe I can store a flag in the request notes if the input filter wants to fail the request, but I'm not sure which later hook to get that.
turned out to be pretty easy - just drop an error bucket into the brigade:
apr_bucket_brigade *brigade = apr_brigade_create(f->r->pool, f->r->connection->bucket_alloc);
apr_bucket *bucket = ap_bucket_error_create(403, NULL, f->r->pool,
f->r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
bucket = apr_bucket_eos_create(f->r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
ap_pass_brigade(f->next, brigade);

Set up configuration to Access amazon order from seller account

I want to set .config.inc.php of MarketplaceWebServiceOrders library that I used to access order of amazon seller account.
Here is my config.inc.php file setting
/************************************************************************
* REQUIRED
*
* All MWS requests must contain a User-Agent header. The application
* name and version defined below are used in creating this value.
***********************************************************************/
define('APPLICATION_NAME', 'MarketplaceWebServiceOrders');
define('APPLICATION_VERSION', '2013-09-01');
After figure out these setting I got error
Caught Exception: Resource / is not found on this server. API Section is missing or you have provided an invalid operation name. Response Status Code: 404 Error Code: InvalidAddress Error Type: Sender Request ID: 47e5f613-5913-48bb-ac9e-cb00871b36af XML: Sender InvalidAddress Resource / is not found on this server. API Section is missing or you have provided an invalid operation name. 47e5f613-5913-48bb-ac9e-cb00871b36af ResponseHeaderMetadata: RequestId: 47e5f613-5913-48bb-ac9e-cb00871b36af, ResponseContext: 6qut/Q5rGI/7Wa0eutUnNK1+b/1rvHSojYBvlGThEd1wAGdfEtnpP2vbs28T0GNpF9uG82O0/9kq 93XeUIb9Tw==, Timestamp: 2015-09-15T12:47:19.924Z, Quota Max: , Quota Remaining: , Quota Resets At:
Here GetOrderSample.php file code for service url. Which I have done already.
// More endpoints are listed in the MWS Developer Guide
// North America:
$serviceUrl = "https://mws.amazonservices.com/Orders/2013-09-01";
// Europe
//$serviceUrl = "https://mws-eu.amazonservices.com/Orders/2013-09-01";
// Japan
//$serviceUrl = "https://mws.amazonservices.jp/Orders/2013-09-01";
// China
//$serviceUrl = "https://mws.amazonservices.com.cn/Orders/2013-09-01";
$config = array (
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'ProxyUsername' => null,
'ProxyPassword' => null,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebServiceOrders_Client(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
APPLICATION_NAME,
APPLICATION_VERSION,
$config);
Caught Exception: Resource / is not found on this server.
This is telling you that the problem is with the path. It's not being able to find that.
Are you sure that the class you're trying to use is in the right path? Most classes that you need to run the samples are in the "Model" folder.
I mean to say, if you take the sample out of the sample folder and put it elsewhere, it won't be able to find classes in the "Model" folder.
An easy fix to test it is to put everything you downloaded from the MWS site into your web directory and just edit the config file. It should work that way.
I'm not a php guy, but I don't see where you're setting up the access keys, merchant id, marketplace id, and most importantly the serviceURL. The 404 error is the first clue meaning it can't find the service. Download the PHP client library which has everything you need to get started.

What are scope values for an OAuth2 server?

I'm facing a difficulty to understand how scopes work.
I found here a small text that describes the scopes of stackexchange api but i need more information on how they work (not specifically this one...). Can someone provide me a concept?
Thanks in advance
To authorize an app you need to call a URL for the OAuth2 authorization process. This URL is "living" in the API's provider documentation. For example Google has this url:
https://accounts.google.com/o/auth2/auth
Also you will need to specify a few query parameters with this link:
cliend_id
redirect_uri
scope: The data your application is requesting access to. This is typically specified as a list of space-delimited string, though Facebook uses comma-delimited strings. Valid values for the scope should be included in the API provider documentation. For Gougle Tasks, the scope is https://www.googleapis.com/auth/tasks. If an application also needed access to Google Docs, it would specify a scope value of https://www.googleapis.com/auth/tasks https://docs.google.com/feeds
response_type: code for the server-side web application flow, indivating that an authorization code will be returned to the application after the user approves the authorization request.
state: A unique value used by your application in order to prevent cross-site request forgery (CSRF) attacks on your implementation. The value should be a random unique string for this particular request, unguessable and kept secret in the client (perhaps in a server-side session)
// Generate random value for use as the 'state'. Mitigates
// risk of CSRF attacks when this value is verified against the
// value returned from the OAuth provider with the authorization
// code.
$_SESSION['state'] = rand(0,999999999);
$authorizationUrlBase = 'https://accounts.google.com/o/oauth2/auth';
$redirectUriPath = '/oauth2callback.php';
// For example only. A valid value for client_id needs to be obtained
// for your environment from the Google APIs Console at
// http://code.google.com/apis/console.
$queryParams = array(
'client_id' => '240195362.apps.googleusercontent.com',
'redirect_uri' => (isset($_SERVER['HTTPS'])?'https://':'http://') .
$_SERVER['HTTP_HOST'] . $redirectUriPath,
'scope' => 'https://www.googleapis.com/auth/tasks',
'response_type' => 'code',
'state' => $_SESSION['state'],
'approval_prompt' => 'force', // always request user consent
'access_type' => 'offline' // obtain a refresh token
);
$goToUrl = $authorizationUrlBase . '?' . http_build_query($queryParams);
// Output a webpage directing users to the $goToUrl after
// they click a "Let's Go" button
include 'access_request_template.php';
The set of query string parameters supported by the Google Authorization Server for web server applications are here:
https://developers.google.com/accounts/docs/OAuth2WebServer?hl=el#formingtheurl

Resources