How to create CSRF token for Cakephp 3 PHPunit testing? - unit-testing

I am trying to get my unit tests working again after enabling CSRF tokens and SSL in my CakePHP 3 app.
How do I create or generate a token for a test like the following? Or do I just disable it for testing purposes?
public function testLogin() {
$this->get('/login');
$this->assertResponseOk();
$data = [
'email' => 'info#example.com',
'password' => 'secret'
];
$this->post('/login', $data);
$this->assertResponseSuccess();
$this->assertRedirect(['controller' => 'Users', 'action' => 'dashboard']);
}

The official documentation has good approach since version 3.1.2.
You only have to call $this->enableCsrfToken(); and/or $this->enableSecurityToken(); before your post to be able to perform the request successfully with token.
As the official example shows:
public function testAdd()
{
$this->enableCsrfToken();
$this->enableSecurityToken();
$this->post('/posts/add', ['title' => 'Exciting news!']);
}

Related

AWS PHP SDK Cognito User Auth

How can I verify if a user is logged in on my services with AWS PHP SDK?
I am logging them with :
$result = $this->awsCognitoClient->adminInitiateAuth([
'AuthFlow' => 'ADMIN_NO_SRP_AUTH',
'ClientId' => $this->appClientID,
'UserPoolId' => $this->userPoolID,
'AuthParameters' => [
'USERNAME' => $userName,
'PASSWORD' => $password,
],
]);
That provides a session token. I want to send that token to another of my services and in that other service I want to check if the token is valid or not. How should I proceed?
Is this the best way or is there a better method to authenticate my user?
To solve this issue i created a singleton instance of an AWSAutWrapper and i share the accesstoken with other services.

Creating Oauth callback function in python. I there is a webserver should sends me Token and I want to react to the token if it's correct by call back

I want to make the same function but in Python Django how can I do that
because I
want to make authentication for login using Oauth 2.0
public function callback(Request $request){
$response = Http::post('https://oauth.zid.sa' . '/oauth/token', [
'grant_type' =>'authorization_code',
'client_id' => 48,
'client_secret' => 'LsswUNyWTjyKT9AsXnpsv3FnG4glSNZQ5SM3YRnD',
'redirect_uri' => 'http://client.test/oauth/callback',
'code' => $request->code // grant code]);}

How to send XML POST request with Guzzle to web service API using Laravel?

I am trying to post a request to my Web API, using Laravel Guzzle Http client. However, I am getting errors trying to post the request. The data I want to send is XML as the API controller is built in XML return format.
I have tried all sorts of methods to post the request with Guzzle but it is yet to work.
public function createProperty(Request $request)
{
$client = new Client();
$post = $request->all();
$create = $client->request('POST', 'http://127.0.0.1:5111/admin/hotel', [
'headers' => [
'Content-Type' => 'text/xml; charset=UTF8',
],
'form-data' => [
'Name' => $post['hotel_name'],
'Address' => $post['address'],
'Phone' => $post['phone'],
'Email' => $post['email'],
'Website' => $post['website'],
'Latitude' => $post['latitude'],
'Longitude' => $post['longitude'],
'Tags' => $post['tags'],
'Priority' => $post['priority'],
'Visible' => $post['visible'],
'Stars' => $post['stars'],
'Description' => $post['description'],
'Facilities' => $post['facilities'],
'Policies' => $post['policies'],
'ImportantInfo' => $post['important_info'],
'MinimumAge' => $post['minimum_age']
]
]);
//dd($create->getBody());
echo $create->getStatusCode();
echo $create->getHeader('content-type');
echo $create->getBody();
$response = $client->send($create);
$xml_string = preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $create->getBody());
$xml_string = $create->getBody();
//dd($xml_string);
$hotels = simplexml_load_string($xml_string);
return redirect()->back();
}
I expected the result to POST to the web service and save data to database, but however I got the error "Client error: POST 'http://127.0.0.1:5111/admin/hotel' resulted in a '400 bad request' response. Please provide a valid XML object in the body
Rather than using post-data in the guzzle request, you need to use body:
$create = $client->request('POST', 'http://127.0.0.1:5111/admin/hotel', [
'headers' => [
'Content-Type' => 'text/xml; charset=UTF8',
],
'body' => $xml
]);
$xml will be the XML data you want to send to the API. Guzzle will not create the XML data for you, you'll need to do this yourself.
The XML data can be created using the DomDocument class in PHP.
If you are using Laravel 7+ this simple line should work very well
$xml = "<?xml version='1.0' encoding='utf-8'?><body></body>";
Http::withHeaders(["Content-Type" => "text/xml;charset=utf-8"])
->post('https://destination.url/api/action', ['body' => $xml]);

Facebook PHP SDK 5.0 in Yii 2.0 framework (config file)

I was following this tutorial for setting up Facebook PHP SDK 5.0 extension in my Yii 2.0 project. And it works as expected, but every time (in any of the controllers) I need to use some of the features from here this, I need to make an instance like this:
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.5',
// . . .
]);
and later use it:
// Send a GET request
$response = $fb->get('/me');
// Send a POST request
$response = $fb->post('/me/feed', ['message' => 'Foo message']);
// Send a DELETE request
$response = $fb->delete('/{node-id}');
but I'm not sure how practical is this, to make an instance of an object in every action/controller where I need to use it. I want to add this data as a general data in the config file. So I tried something like this:
'components' => [
.
.
'facebook' => [
'class' => 'Facebook\Facebook',
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.5'
],
.
.
and later in the actions I want to take this value like:
$fb = Yii::$app->facebook;
and after that do all the operations mentioned above. So I want to generalize the values in the config file like all other extensions, but I keep getting the error:
Facebook\Exceptions\FacebookSDKException
Required "app_id" key not supplied in config and could not find fallback environment variable "FACEBOOK_APP_ID"
Is it possible this to be entered in web config file, and with that, to avoid creating the object with same credentials before each Facebook call?
EDIT 1:
Reply to #machour response:
I followed your suggestion and It was still throwing the same error. Then I found it working as follows:
<?php
namespace your\namespace;
use Facebook\Facebook;
class MyFacebook extends Facebook {
public $app_id = '{app-id}';
public $app_secret = '{app-secret}';
public $default_graph_version = 'v2.5';
public function __construct()
{
parent::__construct([
'app_id' => $this->app_id,
'app_secret' => $this->app_secret,
'default_graph_version' => $this->default_graph_version
]);
}
}
And then:
'components' => [
.
.
'facebook' => [
'class' => 'your\namespace\MyFacebook'
]
At some point this is acceptable solution, since the redundancy is eliminated. The keys are not only at one place.
But do you have any idea how to transfer all the keys to the config file instead of the MyFacebook class?
The problem is that Facebook\Facebook doesn't implement $app_id, $app_secret and $default_graph_version as public properties, so your parameters are not taken in account when Yii builds the object declared in your component.
One way to fix that is to create your own class that extends Facebook, with those public properties, and to correctly call Facebook\Facebook constructor from it's own constructor. And then point your configuration to that new class instead :
<?php
namespace your\namespace;
use Facebook\Facebook;
class MyFacebook extends Facebook {
public $app_id;
public $app_secret;
public $default_graph_version;
public function __construct()
{
parent::__construct([
'app_id' => $this->app_id,
'app_secret' => $this->app_secret,
'default_graph_version' => $this->default_graph_version
]);
}
}
And then:
'components' => [
.
.
'facebook' => [
'class' => 'your\namespace\MyFacebook',
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.5'
],
That should do the trick.

OTRS generic interface rest authentication

I'm trying to consume the OTRS generic interface. The rest service is created by the import functionallity. I found the files needed for import here Consuming OTRS TicketConnector from .NET apps
My problem is when I try to consume the interface for example with a curl command
curl http://<user>:<password>#<server-ip>:<port>/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnectorREST/Ticket/<Ticket-id> -X GET
The result of the command is
{"Error":{"ErrorCode":"TicketGet.AuthFail","ErrorMessage":"TicketGet: Authorization failing!"}}
I tried every user/password combination that makes sense to me. I tried the otrs admin account, agent account, customer account, root account of the server, EVERYTHING! I can't find a information in the docs that states wich account type is needed.
Here are some information that are printed out by the webservice debugger
Communication sequence started
$VAR1 = {
'DOCUMENT_ROOT' => '/srv/www/htdocs',
'GATEWAY_INTERFACE' => 'CGI/1.1',
'HTTP_ACCEPT' => '*/*',
'HTTP_HOST' => '<server-name>',
'HTTP_USER_AGENT' => 'curl/7.39.0',
'MOD_PERL' => 'mod_perl/2.0.4',
'MOD_PERL_API_VERSION' => '2',
'PATH' => '/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/usr/lib/mit/bin:/usr/lib/mit/sbin',
'PATH_INFO' => '/Webservice/GenericTicketConnectorREST/Ticket/<ticket-id>',
'PATH_TRANSLATED' => '/srv/www/htdocs/Webservice/GenericTicketConnectorREST/Ticket/<ticket-id>',
'QUERY_STRING' => '',
'REMOTE_ADDR' => '<server-ip>',
'REMOTE_PORT' => '56065',
'REQUEST_METHOD' => 'GET',
'REQUEST_URI' => '/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnectorREST/Ticket/<ticket-id>',
'SCRIPT_FILENAME' => '/opt/otrs/bin/cgi-bin/nph-genericinterface.pl',
'SCRIPT_NAME' => '/otrs/nph-genericinterface.pl',
'SERVER_ADDR' => '<server-ip>',
'SERVER_ADMIN' => '<admin-account>',
'SERVER_NAME' => '<server-name>',
'SERVER_PORT' => '80',
'SERVER_PROTOCOL' => 'HTTP/1.1',
'SERVER_SIGNATURE' => '<address>Apache/2.2.12 (Linux/SUSE) Server at <server-name> Port 80</address>
',
'SERVER_SOFTWARE' => 'Apache/2.2.12 (Linux/SUSE)'
};
Deteced operation TicketGet
No data provided
Incoming data before mapping
$VAR1 = {
'RequestMethod' => 'GET',
'TicketID' => '<ticket-id>'
};
TicketGet.AuthFail
TicketGet: Authorization failing!
Outgoing data before mapping
$VAR1 = {
'Error' => {
'ErrorCode' => 'TicketGet.AuthFail',
'ErrorMessage' => 'TicketGet: Authorization failing!'
}
};
Long story short: what type of authentication or user type otrs expects to access the generic interface?
In found my mistake. The way I passed the login credentials to the service was wrong.
In my case the user is a agent user.
Here is a working curl command for my service:
curl http://<server-ip>:<port>/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnectorREST/Ticket/<ticket-id>?UserLogin=<username>\&Password=<password> -X GET