"A Token was not found in the SecurityContext" on Silex / Symfony - php

I built a Silex project with an login mechanism.
Not being a Symfony expert, I strictly followed the guidelines here for the authentication process : http://silex.sensiolabs.org/doc/providers/security.html
... and it works fine on my development environment
However, when I pushed my project on my production server, I get the following error each time I try to log into my web app
[2012-12-18 16:35:33] CRITICAL: Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException:
A Token was not found in the SecurityContext. (uncaught exception) at
/my/app/path/vendor/symfony/security/Symfony/Component/Security/Http/Firewall/AccessListener.php line 53 [] []
which means that the following code in AccessListener.php
$this->context->getToken());
throws an expection
Given the fact that the same code works perfectly fine on my development environment, I assume it has something to do with my production server configuration.
I found this thread http://groups.google.com/forum/#!msg/symfony-devs/jKphNy_0Q2Y/vYfkAuyjSHEJ that suggests to add the following line to my project's .htaccess
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
with no result. I still get the "A Token was not found in the SecurityContext" exception.
Does anybody have an idea ?
Edit
The content of $app['security.firewalls'] is the following
$app->register(new Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'login' => array(
'pattern' => '^/login$'
),
'admin' => array(
'pattern' => '^/',
'form' => array('login_path' => '/login', 'check_path' => '/admin/login_check'),
'logout' => array('logout_path' => '/admin/logout'), // url to call for logging out
'users' => array(
'admin' => array('ROLE_ADMIN', 'SOMEPASSWORD'),
),
)
)
));

It seems it has nothing to do with HTTP Basic Auth, because you don't use it in any of your firewalls. What you use is a firewall with a form entry point, which then uses session to store the security token.
I would suggest you to look at how sessions (and cookies) are managed on prod server compared to your dev environment.

Most likely the reason why this works on your local machine but not in your productive environment is that .htaccess is supported by Apache, while nginx does not bother wasting I/O and CPU time parsing this files
If you post your .htaccess I will show you how to translate this to performant nginx-readable configuration.
EDIT
Silex even has a configuration example for nginx
http://silex.sensiolabs.org/doc/web_servers.html

Related

Laravel not publishing to Redis

I am trying to implement Redis publishing in my local RESTful API which is built in Laravel for the purposes of implementing a chat system later on with Web Sockets. I intend to read them from a Node.JS server later on.
I am using Redis::publish to publish a simple message to my test-channel.
However, for some reason Laravel doesn't seem to publish to it.
I have also noticed that when I call Redis::set, whatever I set doesn't get persisted in Redis, but using Redis::get I can read the values that I'm setting.
public function redis(Request $request) {
$data = $request->validate([
'message' => 'string|required'
]);
Redis::publish('test-channel', 'a test message');
return 'Done';
}
I am using the code above in the api/redis route:
Route::post('/redis', 'API\MessageController#redis');
I have subscribed to the test-channel using the redis-cli command.
If I manually publish a message to the test-channel using the redis-cli in a terminal instance, I properly receive the messages that I am publishing. However, they don't seem to get published with Laravel for some reason.
What I can notice while running php artisan serve and visiting the aforementioned route is Laravel logging the following:
[*timestamp*] 127.0.0.1:39448 Accepted
[*timestamp*] 127.0.0.1:39448 Closing
The port after 127.0.0.1 appears to be random.
I tried both php-redis php extension and the predis package, just to be sure that it isn't any one of them, but I get the same result with both of them. I am currently using php-redis with both igbinary and redis extensions enabled in /etc/php/config.d and have removed the Redis alias from config/app.php.
I am using PHP 7.4, Laravel 6.0 and Redis 5.0.7 on Manjaro.
Been there, discovered that with:
$ redis-client
psubscribe *
will show you what's going on.
Chances are that your default config/database.php contains something like:
'redis' => [
'client' => env('REDIS_CLIENT', 'predis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
In that case, the channel name will be prefixed with this prefix option.
So you can just comment this option, or, if you keep it, be sure to subscribe to the right channel
Redis::publish('test-channel', 'a test message');
$prefix = config('database.redis.options.prefix');
$channel = $prefix . 'test-channel';
return "Done. (published on $channel)";

Getting my PHP Slime Framework Application to run in a Hosted Environment?

Introduction
Hi all. I've currently completed the development for my first PHP web application - a very simple one built using the popular PHP micro-framework - Slim Framework 3.
The Application's Code
My app is a very simple one that just routes different get requested to different templated pages. I'm using slimphp/Twig-View for view rendering / templating.
Main index.php file looks like this:
// Require composer autoloader
require __DIR__ . '/vendor/autoload.php';
// Application settings
$settings = require __DIR__ . '/app/settings.php';
// New Slim app instance
$app = new Slim\App( $settings );
// Add our dependencies to the container
require __DIR__ . '/app/dependencies.php';
// Require our route
require __DIR__ . '/app/routes.php';
// Run Slim
$app->run();
The routes.php file is like so:
// Creating routes
// Psr-7 Request and Response interfaces
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
$app->group('/', function () {
$this->get('', function (Request $request, Response $response, $args) {
$vars = [
'page' => [
'title' => 'East End Ink',
'description' => 'Best apparel company in Austin'
],
];
return $this->view->render($response, 'home.twig', $vars);
});
$this->get('products', function (Request $request, Response $response, $args) {
$vars = [
'page' => [
'title' => 'East End Ink',
'description' => 'Best apparel company in Austin'
],
];
return $this->view->render($response, 'products.twig', $vars);
});
[...... cut out some repetition ....]
$this->get('services', function (Request $request, Response $response, $args) {
$vars = [
'page' => [
'title' => 'East End Ink',
'description' => 'Best apparel company in Austin'
],
];
return $this->view->render($response, 'services.twig', $vars);
});
});
The source code for the whole app is HERE.
How I run the App Locally / Trying to Run in Production
This is what it looks like for me to run the web application locally:
20 Second Video - http://tinypic.com/r/n6c5g7/9
I just run php -S localhost:8080 and once at localhost:8080 the app works great. The problem is, I do not know how to translate this to running the application online. I've deployed my source code to CloudWays and FortRabbit, both have somehow been successful at displaying the homepage.
CloudWays - http://phpstack-115365-328618.cloudwaysapps.com/:
FortRabbit - https://custom-5yx3.frb.io/:
The error I get when I try to navigate to the routing of any other page on this staging environment is this:
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at [no address given] to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
Apache/2.4.10 (Debian) Server at phpstack-115365-328618.cloudwaysapps.com Port 80
What I think it's doing is just serving up the php file there like php does locally if I go to the application's route at port 80 without running php -S localhost:8080.
17 Second Video of me reproducing same issue locally: http://tinypic.com/r/28s6n87/9
Now the question is:
How can I get this web application hosted at a place like CloudWays or FortRabbit. What in general am I trying to do to get it running there? And if you're kind enough, how specifically might I go about doing that?
P.S.
The site's source code is still public, so feel free to checkout it's GitHub Repo to peruse files.
P.P.S.
I'm very grateful to any help you're able to provide. I'm a n00b and this arena, and will pay it back when I'm a more able/experienced PHP developer like I do in other areas.
I downloaded your files from the repo.
First, I get the following error when checking out your website locally:
Parse error: syntax error, unexpected '}' in /var/www/htdocs/slim/app/routes.php on line 98
That's because a missing semicolon on line 97. I fixed that.
Then I can see the home page, but trying to go to the other pages gives a 500 error.
The problem for me is in your .htaccess file. You have this line:
RewriteBase /var/www/html/brand-builders-php-site/
and if I change it to this:
RewriteBase /
then everything works (I can load the pages)
Usually 500 errors are relating to the htaccess when using Slim 3, at least from when I was using it.
The other answer regarding the htaccess properly addresses this, I'd comment but not enough repair so I can only answer.

Configure Cakephp 2.6.0 with Redis Engine

I am trying to configure cakephp ver 2.6.0 to use redis engine by default. but somehow i am not able to make it work. any help will be highly appreciated.
Things Which i have tried so far..
Configured app/config folder 2 files , core.php and bootstrap.php. , according to the guidelines provided here in this blog configure cake with redis and this blog too Another cake-redis config setup
but i keep on getting errors like.
Fatal error: Uncaught exception 'CacheException' with message 'Cache engine session is not properly configured.' in C:\wamp\www\project\cakephp\cakephp_2.6.0\lib\Cake\Cache\Cache.php on line 181
CacheException: Cache engine session is not properly configured. in C:\wamp\www\project\cakephp\cakephp_2.6.0\lib\Cake\Cache\Cache.php on line 181
Any help will be highly appreciated.
I was having the same exact issue today while trying to setup CakePHP to use Redis as the cache engine.
Coincidentally, I also read the same setup instructions from the two blogs you linked to.
The reason was that I had copied pasted the Configure::write(...) code block from the Another cake-redis config setup blog post as it is and pasted it into the file without first commenting out the Configure::write(...) code block that was already in the core.php file.
I'm assuming that you have already successfully setup Redis on Windows and have installed the PHPRedis extension without any issues.
I am using the instructions from Another cake-redis config setup here.
In your app/Config/core.php file, comment out the following block: (this was starting at line 218 in my core.php)
Configure::write('Session', array(
'defaults' => 'php'
));
Instead, you can put this in: (You can change the values to suit your particular needs)
Configure::write('Session', array(
'defaults' => 'cache',
'timeout' => 100,
'start' => true,
'checkAgent' => false,
'handler' => array(
'config' => 'session'
)
));
After this, change the value of $engine to 'Redis', so it becomes:
$engine = 'Redis';
And then, put this code in, I put this in at the very end of the file: (Again, your values can be different depending on what your setup is)
Cache::config ('session', array (
'Engine' => $engine,
'Prefix' => $prefix . 'cake_session_',
'Duration' => $duration
));
And that's it. You're done! No need to change anything else.
To make sure that Redis is working properly with CakePHP, I ran the RedisEngine Test Suite that comes with CakePHP. You need to have PHPUnit installed for this to work.
It can be accessed via http://your-cakephp-project/test.php
Click on 'Tests' under Core and then click on 'Cache/Engine/RedisEngine'
If everything is working successfully, you should see all the tests pass.
Alternatively, you can use redis-cli at the command prompt to confirm that Redis is storing keys properly.
Once you have logged in by typing redis-cli, type KEYS *
This should give you a list of keys related to your CakePHP setup.
An example would be the "myapp_cake_core_object_map" key.
Hope this helps.

Laravel Omnipay with Omnipay/Paypal - Class not found

I'm trying to integrate the Omnipay Paypal package with my Laravel 4.1 application. I've installed the laravel-omnipay package, as suggested by Omnipay, and followed the instructions on how to set it up.
I've added the laravel-omnipay package to both the providers array and the aliases array in the app.php file of Laravel. The config file has also been created.
My composer.json has the following requirements:
"ignited/laravel-omnipay": "1.*",
"omnipay/paypal": "~2.0"
and the config file of ignited/laravel-omnipay looks like this:
<?php
return array(
// The default gateway to use
'default' => 'paypal',
// Add in each gateway here
'gateways' => array(
'paypal' => array(
'driver' => 'Paypal_Express',
'options' => array(
'solutionType' => '',
'landingPage' => '',
'headerImageUrl' => ''
)
)
)
);
But when I call $gateway = Omnipay::gateway('paypal'); I'm getting the error
Class '\Omnipay\Paypal\ExpressGateway' not found"
Is there something I'm forgetting? :I
I'm not familiar with ignited/laravel-omnipay specifically, so this may or may not be the problem, but you might try fixing the capitalisation on this line:
'driver' => 'PayPal_Express',
(note that PayPal has two capital P's).
Generally class names are not case sensitive in PHP, but if you are using a case-sensitive filesystem, then the composer autoloader will not be able to find the right class.
Try composer dumpautoload to load new classes.
UPDATE:
Think in a term of service that is provided to your application by that new package. Find where is that service linked to application. It is usually done through ServiceProviders class. If there is no bug, it should be easy, following simple business rule to see how is provider related to main app.
So, you have one entity (provider) that should communicate with another.
That communication is done through simple rules. This is the best way to learn Laravel. It helps to think in a term of business rules, rather then to stare at code which is often very abstract.

AuthComponent works great in development mode, but not in production?

I'm getting a bizarre error when using CakePHP's AuthComponent. As far as I can tell, there's nothing wrong with the code itself. It's working great on my development machine and the production server. However, if I change the 'debug' level in app/Core/config.php from 2 (development) to 0 (production) on the production server, the app fails with nothing but this in the error logs:
PHP Fatal error: Class 'AuthComponent' not found in /path/to/my/app/View/Elements/auth_status.ctp on line 3
I've checked that the file is present in lib/Cake/Controller/Component/AuthComponent.php. I've also experimentally added/removed App::uses('AuthComponent', 'Controller/Component') to AppController and my individual controllers to no avail. This one has me stumped, and I can't reproduce the error on my development machine. This seems to indicate a server issue, but I'm at a loss to find an explanation, and the docs aren't clear on the prerequisites required to run the AuthComponent. Any ideas how I can fix it? Thanks!
For reference, here's my AppController:
class AppController extends Controller {
public $helpers = array('Recaptcha.Recaptcha');
public $components = array(
'Session',
'Auth' => array(
'loginAction' => array(
'controller' => 'users',
'action' => 'login'
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
);
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow();
}
}
The code for auth_status.ctp:
<div class="pull-right">
<?php if (AuthComponent::user('id')): ?>
<?php echo $this->Html->link("Welcome!", '/users/view/'.AuthComponent::user('id'));?>
|
<?php echo $this->Html->link('Logout', '/users/logout');?>
<?php else: ?>
<?php echo $this->Html->link('Login', '/users/login');?>
|
<?php echo $this->Html->link('Register', '/users/register');?>
<?php endif; ?>
</div>
I finally got to the bottom of this one. In core.php, there's a variable named $prefix that's used by the cache engine. If that engine is Memcache or APC, it must be changed to avoid naming collisions with any other Cake apps running on the server. My development laptop was using File cache engine, while the production server was using APC (and later Memcached). An older version of the same Cake app was running on that server and was not using AuthComponent. As soon as someone would make a request on that app, the other app would use the wrong cache and throw HTTP500 errors until I cleared the cache.
Change the $prefix variable to something unique to your app, and the problem disappears.
You probably have different php.ini settings regarding include_path.
Check on development and on production server:
echo ini_get('include_path');
I think this may be related to this issue. The error in my code was totally unrelated to AuthComponent (or Cake at all).
Unfortunately I can't know what the error is in your case - I had to to some real debugging before I pin-pointed my error.
If anyone wonders; my error was that I accessed functions as arrays and my production server was running a PHP version < 5.4.
I also ran into this problem and as it turned out my problem was, that I tried to load a plugin in bootstrap.php, but didn't have it installed

Categories