Required param state missing from persistent data - facebook-php-sdk

I've an issue with php-graph-sdk, I've those functions
protected function getFacebook()
{
static $facebook = null;
if($facebook == null){
$facebook = new Facebook\Facebook([
'app_id' => $this->getAppId(),
'app_secret' => $this->getAppSecret(),
'default_graph_version' => 'v2.10'
]);
}
return $facebook;
}
public function getLoginUrl($url)
{
$fb = $this->getFacebook();
$helper = $fb->getRedirectLoginHelper();
$autorisations = ['email'];
return $helper->getLoginUrl($url , $autorisations);
}
public function callback(&$error = null)
{
$fb = $this->getFacebook();
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exception\ResponseException $e) {
// When Graph returns an error
$error = 'Graph returned an error: ' . $e->getMessage();
return false;
} catch(Facebook\Exception\SDKException $e) {
// When validation fails or other local issues
$error = 'Facebook SDK returned an error: ' . $e->getMessage();
return false;
}
....
}
And I do
$url = $Facebook->getLoginUrl(URL);
And in the callback file
$token = $Facebook->callback($error);
When I click on the link, the callback file is executed and $helper->getAccessToken(); causes this error:
Uncaught Facebook\Exceptions\FacebookSDKException: Cross-site request forgery validation failed. Required param "state" missing from persistent data.
I've seen posts about that and no fix works for me
EDIT:
What I've found currently is that: Facebook SDK error: Cross-site request forgery validation failed. Required param "state" missing from persistent data
Cross-site request forgery validation failed required param state missing from persistent data
and
https://github.com/facebookarchive/php-graph-sdk/issues/1123
https://github.com/facebookarchive/php-graph-sdk/issues/1134

Finally I've solved my issue by switching samesite to Lax by adding that in config.php
ini_set('session.cookie_samesite','Lax');

Related

.net core authorization using role based attributes isn't working

I have .Net core authorization set through user roles. I have the authorize attribute set at the page level restricted by roles, and I have a method restricted by only one role.
I am using ajax call through a kendo Data Source raw crud transport calls. The user does have the correct attribute or role for the method call, but it's getting to the method some how.
I have to double check in the method which is the only way I can secure my app now.
[HttpGet]
[AutoValidateAntiforgeryToken]
[Authorize(Roles="Administrators")]
public async Task<IActionResult> OnGetDeleteCustomerAsync(cbs_Customers customers)
{
if (!ModelState.IsValid)
{
return Page();
}
if (User.Identity.IsAuthenticated)
if (!(User.IsInRole(Intrafiz.Authorization.Constants.ContactAdministratorsRole)))
{
return Unauthorized();
}
if (customers is cbs_Customers)
{
Customer = customers;
}
else
{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return new JsonResult(new
{
success = false,
error = "(Deleting customer): failed to locate customer !"
});
}
try
{
_context.cbs_Customers.Remove(Customer);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
if (!cbs_CustomersExists(Customer.CustomerId))
{
return new JsonResult(new
{
success = false,
error = "(Updating customer): failed to locate customer !"
});
}
else
{
return new JsonResult(new
{
success = false,
error = "(Updating customer): failed to locate customer !" + "\r\n" + ex.Message?.ToString()
});
}
}
return new JsonResult(Customer);
}
This is in the configuration of the website
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
config.Lockout.MaxFailedAccessAttempts = 5;
config.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromDays(7);
config.Lockout.AllowedForNewUsers = true;
config.User.RequireUniqueEmail = true;
}).AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthenticationCore();
// Authorization handlers.
services.AddScoped<IAuthorizationHandler,
ContactIsOwnerAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler,
ContactAdministratorsAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler,
ContactManagerAuthorizationHandler>();
This is from the kendo dataSource
destroy: {
url: window.location.origin + "/Energy/Index?handler=DeleteCustomer",
type: "GET"
},
The user is authenticated by checking User.Identity.IsAuthorized ,
but the role isn't of Administrator or Manager but it's still the call from the dataSource is still getting to the method

Passing params to c# WebMethod from PHP/SOAP

I've seen other posts about this but nothing works for me.
Parameters are always null.
Using php soap to call a c# web service (asmx) always results in null values from the service.
Please help! Driving me insane.
[WebMethod]
public string CreateContact(string param1, string param2)
{
return param1 + "-" + param2;
}
$client = new SoapClient('https://etc....?wsdl');
$params = array('param1' => 'abc','param2' => 'xyz');
$result = $client->CreateContact($params);
echo $result->CreateContactResult;
I've tried var_dump also
I don't know what you are trying to do ...
If that is PHP ... you've got multiple errors.
Try this:
<?php
$client = new SoapClient('http://www.thomas-bayer.com/axis2/services/BLZService?wsdl');
$params = array('param1' => 'abc','param2' => 'xyz');
try{
$result = $client->CreateContact($params);
echo $result->CreateContactResult;
} catch (Exception $e) {
echo $e->getMessage();
}
?>
Should return you the error:
Function ("CreateContact") is not a valid method for this service
Valid methods for SoapClient you can find here:
http://php.net/manual/en/class.soapclient.php
Regards,
Ɓukasz Konkol

Google Calendar Server to Server

I use to make appointments a calendar based on FULLCALENDAR with backup of the rdv in a database mysql on my own local server. So far, so good. I wish I could synchronize the rdvs thus taken, on the google calendar and inversely be able to import into my database mysql the rdvs taken on the account of google on line.
I tried to understand and read the API doc of google calendar here and here
I only get error messages.
I tried to do it directly in fullcalendar but the calendar must be declared in public, something I can not do.
The ideal would be to be able to make server calls in php (login and password of google clandier backup in local mysql database), for which I create my API key and a service account, but again I do not get only error messages.
Would there be a link or a really functional tutorial that I could use to learn
I tried with this link but never succeeded
thanks in advance.
EDIT : I try this.
quickstart.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/calendar-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_id.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Calendar::CALENDAR_READONLY)
));
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* #param string $path the path to expand.
* #return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
php quickstart.php
PHP Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in /Users/krislec/Desktop/vendor/google/auth/src/OAuth2.php:648
Stack trace:
#0 /Users/krislec/Desktop/vendor/google/apiclient/src/Google/Client.php(340): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /Users/krislec/Desktop/quickstart.php(36): Google_Client->createAuthUrl()
#2 /Users/krislec/Desktop/quickstart.php(75): getClient()
#3 {main}
thrown in /Users/krislec/Desktop/vendor/google/auth/src/OAuth2.php on line 648
Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in /Users/krislec/Desktop/vendor/google/auth/src/OAuth2.php:648
Stack trace:
#0 /Users/krislec/Desktop/vendor/google/apiclient/src/Google/Client.php(340): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /Users/krislec/Desktop/quickstart.php(36): Google_Client->createAuthUrl()
#2 /Users/krislec/Desktop/quickstart.php(75): getClient()
#3 {main}
thrown in /Users/krislec/Desktop/vendor/google/auth/src/OAuth2.php on line 648

Silex - my error handler isn't working

I am trying to set up a error handler on my controller to catch anything that might cause my page to malfunction. For example: in this scenario I am trying to catch any error that could possibly happen once my method calls a external API with a bad parameter but it doesn't seem to do anything except give me the typical ClientException in Middleware.php line 69:
Client error: 400 which isn't what I am exactly aiming for. Any advice will be greatly be appreciated or better ways of handling errors in Silex.
private function getSIS($url, $session, Application $app)
{
$message = "You don't have permission to access this!";
if($app['security']->isGranted('ROLE_SUPER_ADMIN'))
{
$client = new Client(['base_uri' => 'https://***********.ca/api/SIS/']);
if (!empty($session))
$response = $client->get($url, ['query' => 'session=' . $session]);
else
$response = $client->get($url);
return $response;
}
$app->error(function (\Exception $e, $code) {
switch($code) {
case 404:
$message = 'The requested page could not be found';
break;
default:
$message = 'We are sorry, but something went terribly wrong.';
}
return new Response($message);
});
return new Response($message);
}
The $app->error method might need to be placed outside the context of your controller actions. I'm not sure exactly how you have your application structured but maybe try placing the error block right before $app->run();
$app->error(function (\Exception $e, $code) use ($app) {
switch($code) {
case 404:
$message = 'The requested page could not be found';
break;
default:
$message = 'We are sorry, but something went terribly wrong.';
}
return new Response($message, $code);
});
$app->run();

Symfony2 Doctrine - Flushing in kernel.response listener flushs bad data

In order to do some logging for my Symfony2 app, I created a service that logs any connection, here is the method called on kernel.response :
public function log(FilterResponseEvent $event)
{
$log = new Log();
$request = $event->getRequest();
$response = $event->getResponse();
//fill the Log entity with stuff from request & response data
$manager = $this->container->get('doctrine.orm.entity_manager');
$manager->persist($log);
$manager->flush();
}
All of this seems fine, however when I execute a test like this one (patch with empty data to trigger a failure):
$this->client->request(
'PATCH',
'/users/testificate',
array(
'firstName' => '',
)
);
Which calls this action :
protected function processForm($item, $method = 'PATCH')
{
$form = $this->createForm(new $this->form(), $item, array('method' => $method));
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$response = new Response();
// Set the `Location` header only when creating new resources
if ($method == 'POST') {
$response->setStatusCode(201);
$response->headers->set('Location',
$this->generateUrl(
'get_' . strtolower($class), array('slug' => $item->getId()),
true // absolute
)
);
}
else {
$response->setStatusCode(204);
}
$this->em->flush();
return $response;
}
$this->em->detach($item);
return RestView::create($form, 400);
}
Although the test fails, the entity is patched, and of course it must not.
After some search what I've learnt is:
The parameters enter the form validator
The validation fails, thus returning a 400 http code without flushing the entity
However during the validation process, the entity gets hydrated with the invalid data
When the service is called on kernel.response, the $manager->flush(); flush all the data... including the bad data provided by the PATCH test.
What I've tried thus far:
1) Do a $manager->clear(); before $manager->persist(); ... doesn't change anything
2) Do a $manager->detach($item); if the form validation failed... doesn't change anything
Thanks !
I recently stumbled across problems with flushing in kernel.response when upgrading from Doctrine 2.3.4 to the latest 2.4 branch. Try flusing the log entities from kernel.terminate. Leave any modifications to the Response in kernel.response.

Resources