Symfony2 - Access is denied (user is not fully authenticated) - php
I'm developing a website using Symfony2, and until today - had no problem logging in. But now when logging in I'm not correctly authenticated - Symfony profiler lists me as logged in as: anon instead of the user I logged in as. I'm also redirected back to the login page instead of the target path.
The login process consists of a traditional login form (i.e. username + password) with a submit button. All user credentials are stored in MySQL and I've setup a User entity as a provider.
There are no errors in my php errors log, or listed in the Symfony profiler under Exception or Logs.
One observation I've made is nothing is listed under the Session Attributes heading (within Symfony profiler > Request) - normally there would be some security context information listed after successfully logging in, but now it's always empty. I tried setting a basic session variable on the homepage which was partially successful as it gets set and is shown under Session Attributes, but get's cleared whenever attempting to login!
This is my security.yml file:
# app/config/security.yml
security:
encoders:
Woodcut\UserBundle\Entity\User: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
main:
entity: { class: Woodcut\UserBundle\Entity\User, property: username }
firewalls:
secured_area:
pattern: ^/
anonymous: ~
form_login:
login_path: login
check_path: login_check
username_parameter: _username
success_handler: custom_authentication_handler
failure_handler: custom_authentication_handler
#always_use_default_target_path: true
#default_target_path: /login_router
logout:
path: /logout
target: /
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
- { path: ^/ratings/update, roles: ROLE_USER }
- { path: ^/ratings/new, roles: ROLE_USER }
- { path: ^/favourite, roles: ROLE_USER }
I'm using a typical LAMP stack to run my site with Symfony 2.3.13 and PHP 5.4.28 on a Ubuntu 12.04 Virtual machine. PHP is running as mod_php.
Output from Symfony Profiler > Debug:
INFO - Populated SecurityContext with an anonymous Token
DEBUG - Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall \ExceptionListener::onKernelException".
DEBUG - Access is denied (user is not fully authenticated) by "/vagrant_www/vprojects/woodcut/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/AccessListener.php" at line 70; redirecting to authentication entry point
DEBUG - Calling Authentication entry point
If someone can please help me determine why users are authenticated as anonymous instead of as themselves that would be great. Been pulling my hear out the last two days trying to find the cause.
Thanks in advance for any help provided!
Additional info: I have a VPS running a copy of the site (for client previewing). I dev on my local VM and git push my changes, I then SSH into my VPS and do a git pull to keep my two version in sync.
What's strange is the VPS version does not exhibit this issue (i.e. login works fine) yet both versions use an identical codebase except for some minor differences in their respective parameters.yml and parameters_dev.yml files.
Update: Problem started happening after making a large number of edits to the code base and performing a apt-get update and apt-get upgrade on my VM. So in an effort to isolate the possible cause I rolled back to an earlier commit - to see if the problem was code related. But despite rolling back to before my major coding changes, the problem is still there.
This has me thinking the cause may not be code related and instead could be server related, something in the new version of PHP (5.4.28) that was installed via apt-get upgrade perhaps OR a new php.ini directive maybe?
I've run the Symfony configuration checker tool and everything seems fine!
Weird.
I was struggling with the same problem. I checked almost everything and after that suspecion fell on session handler...
I have
session: ~
changed to:
session:
handler_id: ~
More about session handling:
http://symfony.com/doc/2.2/components/http_foundation/session_configuration.html#native-php-save-handlers
This problem happens when the PHPSESSID cookie is changing with each request.
If that is your case then you should check the PHPSESSID response cookies between these request, I bet you that they are changed. Why is that happening, that is the real question!
Let's assume for a moment that the above assertion is true.
By seeing this cookie changing all the time Symfony/PHP assumes that the session manager have created in fact a new user session, obviously that would require the user to re-authenticate (unless RememberMe=true which wouldn't cause a login page redirection).
For instance, while working in dev environment I had no problem with this session issue. However, as soon I switched to prod environment - and by this I mean (1) I flushed the --env=prod cache then (2) I loaded the production /app.php instead /app_dev.php page - it just started to redirect me to the login page after a successful authentication & request.
Obviously at first I thought that there is a configuration problem, perhaps I'm using a different set of params on these environments. But that wasn't the case. So there must be something else, but what?
I've checked the var/session/prod directory and I saw many sess_xxx files. The same in var/session/dev directory. Obviously that is not OK. So I removed the var/session/{prod,dev} entirely then I reloaded the /app.php page. This created 2-3 sess_xxx files in both environment, in prod but also in dev. That is not good. It is a sign that somehow something sends a request to the app_dev.php which will load the dev enviroment which might log out you automatically (based on your app's security/firewall configuration). I opened the app_dev.php and I added an exit(0) then suddenly everything started to work well. So that was what was happening, somehow these environments were mixed and a call to prod would eventually trigger a call to the dev which would log you out immediately.
For a quick fix some people just change the framework::session::save_path to /tmp, which is going to be shared by both environments and thus you are not going to be logged out although your app will somehow still send a request to both the app.php and app_dev.php but since they used the same session folder they think the session is the same (unchanged). So in general this is a quick fix as long the session path is the same for all environments. However this is not the solution to the problem!
One other fix is to not use the app_dev.php in the same time with app.php (or vice-versa) and by that I mean only one file/env at a time. That's also a quick fix and not the solution.
What I did, but I still don't understand what happened, was to remove entirely the web {assetic,css,js,fonts} (or bin/console assetic:dump --env=prod --no-debug) stuff and recreate them again with --env=prod --no-debug. That did the trick but I still don't understand how that could fix it.
I hope the steps above would help you to trace the cause of your problem better than I did :-)
I had the same issue as you.
While #plewandowski's answer solved my issue, the root cause was that the session.save_path as set in PHP's config was a directory with incorrect permissions.
As a sanity check, run
php -i | grep session. and then see if the permissions for the save_path are correct..
In my case, session.save_path => /var/lib/php/sessions => /var/lib/php/sessions
Checking the permissions
vagrant#vps:/var/www/site$ ls -lah /var/lib/php
total 16K
drwxr-xr-x 4 root root 4.0K Aug 5 18:01 .
drwxr-xr-x 56 root root 4.0K Aug 5 20:29 ..
drwxr-xr-x 6 root root 4.0K Aug 5 18:23 modules
drwx-wx-wt 2 root root 4.0K Jul 26 11:05 sessions
In this case, the user under which PHP runs (www) it could not access the directory and caused the issue.
Fixed with sudo chmod 1777 /var/lib/php/sessions/
In Symfony 4, I had this error.
In my entity I didn't have the username and password, just I have to add them.
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->userId,
$this->userUsername,
$this->userPassword
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->userId,
$this->userUsername,
$this->userPassword
// see section on salt below
// $this->salt
) = unserialize($serialized, array('allowed_classes' => false));
}
Related
How to turn off nginx log collections in DataDog?
datadog.conf log_level: warn log_file: /var/log/datadog/agent.log log_to_syslog: no dd_url: https://app.datadoghq.com api_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx process_config: enabled: "true" logs_enabled: true tags: - env:stage - nginx - webserver - frontend - php-fpm - php use_dogstatsd: true dogstatsd_port: 8125 I needed to enable flag logs_enabled: true in order to collect PHP logs but with this, I also collect Nginx logs (access and error logs) If logs_enabled is set to false then I do not collect even PHP logs. How can I exclude Nginx logs from being collected? # php.d/conf.yaml init_config: instances: logs: - type: file path: "/var/www/{{ env }}/var/log/app-log.json" service: php source: php sourcecategory: sourcecode
The solution was very simple. Data dog agent configuration is related to enabling/disabling collecting logs from a webserver. In order to turn off/on specific service logging, it must be done from the DataDog webservice. Visit the next URL https://app.datadoghq.com/logs/pipelines/indexes And then add the exclusion rule. Simple as that :)
No token from TokenStorage on test environment
I want to include the logged in user's id to my logger. So I have added a monolog.processor that adds the user id to the 'extra'-portion of the record, and added a custom format string that displays the id. On my dev environment this works (mostly) as expected, but on the test environment it does not work at all, the TokenStorage always returns null on getToken(). There are no specific security configs for dev or test. The biggest differences between the configs is this part: framework: test: ~ session: storage_id: session.storage.mock_file profiler: collect: false I have add this to my dev config but could not reproduce the symptoms. I can only reproduce by making symfony think it really is in test. To be honest, I don't even know where to begin to debug this. Any ideas what might be causing this behaviour? Any ideas how I could debug this so I can get to an answer?
In order to have a token you should be inside on of the symfony firewalls. If any of the firewalls aren't matched by the URI, symfony security is not triggered and you will not have a token. If it is a public area allow anonymous users from root '/*' and use ACL for the rest of the URI (or actions). Anonymous users will have the role IS_AUTHENTICATED_ANONYMOUSLY # app/config/security.yml security: firewalls: main: pattern: ^/ anonymous: ~ Documentation: http://symfony.com/doc/current/security.html
Show Symfony profiler only for admins
I would like to show the Symfony profiler bar (and access to profiler) only for page admins (ROLE_SUPER_ADMIN). I have following this instructions: http://symfony.com/doc/2.8/cookbook/profiler/matchers.html#creating-a-custom-matcher But there does not work. I get this error message: AuthenticationCredentialsNotFoundException in classes.php line 2892: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. Can anybody help me, or know this error message? Thanks for all replies in future!
Make sure the dev section in your security.yaml have the right arguments. Make sure you uncomment the following lines in your security.yaml: firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false After there it should working fine.
Failed user login on production server using Symfony framework (Authentication request could not be processed due to...)
I'm using Symfony for a project and I have been trying to get the login to work on production server with no success for the past 2 days. I keep getting the error Authentication request could not be processed due to a system problem. I have followed the guide here (http://symfony.com/doc/current/cookbook/security/entity_provider.html) to setup loading users from database. My security.yml file: security: encoders: Symfony\Component\Security\Core\User\User: plaintext Acceptme\UserBundle\Entity\User: plaintext role_hierarchy: ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH] providers: in_memory: memory: users: patricia: password: patricia roles: 'ROLE_ADMIN' users: name: user_provider entity: { class: AcceptmeUserBundle:User, property: username } firewalls: user_area: pattern: ^/ anonymous: ~ provider: user_provider form_login: login_path: login_route check_path: _login_check default_target_path: homepage dev: pattern: ^/(_(profiler|wdt|error)|css|images|js)/ security: false default: anonymous: ~ http_basic: ~ access_control: - { path: ^/admin, roles: ROLE_ADMIN } My SecurityController.php: namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Symfony\Component\Security\Core\SecurityContext; class SecurityController extends Controller { /** * #Route("/login", name="login_route") * #Template("security/login.html.twig") */ public function loginAction(Request $request) { if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) { $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR); } else { $error = $request->getSession()->get(SecurityContext::AUTHENTICATION_ERROR); } return array( 'last_username' => $request->getSession()->get(SecurityContext::LAST_USERNAME), 'error' => $error, ); } /** * #Route("/login_check", name="_login_check") */ public function securityCheckAction() { // this controller will not be executed, // as the route is handled by the Security system } } I have tried uploading the project on 2 different web hosts (FatCow & GoDaddy) and the problem remains. Locally i am using PHP 5.4.19 (FatCow uses 5.3.2 and GoDaddy uses 5.4.37). Keep in mind that when working on localhost with XAMPP everything works fine! I've confirmed that PDO is enabled in both cases. I've confirmed that the database username, password and host are correct in the parameters.yml file. Error logs on both local and remote servers show nothing. I have followed all directions from this previous post Deploying Symfony2 app getting fosuserbundle errors and still no success.
It looks like that the error: Authentication request could not be processed due to a system problem. is too generic and does not tell anything about where the problem is (there is an issue opened about this matter here). I solved my issue by checking the logs and see what happened (in var/logs/dev.log), hoping this helps someone. In my specific case, there was a wrong parameter in parameters.yml about database connection. But, again, the error is too generic and does not necessarily imply that the problem is related with database connection.
This problem can be fixed running command: php bin/console cache:clear --env=prod --no-debug
UPDATE: Issue solved. The issue was that a table in the entity php file was named with upper case letters while the database table was named with lower case. +1 to ClémentBERTILLON for pointing in the right direction, namely prod.log
AS #ShinDarth mention it. It is too generic and log inspection will help people in our case to get throught this. If it can help in my situation it was : After an SonataUserBundle installation in SF3, I had to bin/console doctrine:schema:update --force My context is particular, I have had already installed and used FOSUserBundle before to install SonataUserBundle. (Because of SF3 compatibility with FOSUser/SonataUSer... Database have been taken 16 queries after that. Working great.
You probably used the template given by Symfony docs here : {% if error %} <div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div> {% endif %} Which actually gives you this error message. The most simple and reliable way to fix this issue is to replace this line by the following : <div class="alert alert-danger">{{ error }}</div> Which will give you the full stack-trace for your error and (hopefully) help you debug your application. Don't forget to revert this before going to production!
In my case, I changed user entity and then I forgot to update table. for table update: php bin/console doctrine:schema:update --force
Currently there is a bug in Symfony and on production IF during authentication system error occurs (missing table, missing column or any other exception) - it's logged as INFO instead of ERROR and with default error logging options it's not logged at all. https://github.com/symfony/symfony/pull/28462 I think there are two options right now - temporary log everything (including INFO) on production until you find the real error. Second option: use this patch or debug directly on production.
I'm sure that this error is too generic. In my case, The follow is incorrect: class: App/Entity/User; Correction: class: App\Entity\User;
This solution is correct for me: https://stackoverflow.com/a/39782535/2400373 But If you do not have access to the terminal, you can enter the server and delete the folders that are inside var/cache. Another solution if you have access to the console is to type #rm -rf var/cache/* or $sudo rm -rf var/cache/* this solution works on symfony 3
In my case the issue was fixed by correcting a typo in connection details in the .env file.
Another possible cause could be MySQL Server. In my case I forgot to start MAMP / MySQL Server and Symfony resulted with this message.
It's a bug on Symfony 5.3 that happens only on the Internet server. On my local server, no problem. Try to downgrade to 4.5 or 5.0. Then try the authentication again. In my case, the token to authenticate the user can't create and is unable to make a query to the database to validate that the user password is correct.
To extend on answer given by gogaz, Symfony's security bundle doesn't seem to be logging these errors by default as (I guess) it's assumed they will be authentication issues. It might be worth it to inject a logger into your action and (conditionally) log the errors. public function loginAction(AuthenticationUtils $authenticationUtils, LoggerInterface $logger): Response { if (($error = $authenticationUtils->getLastAuthenticationError()) && ($error instanceof AuthenticationServiceException)) { $logger->critical($error->getMessage(), $error->getTrace()); } ... } Do note that you might have to extend the logging if your security implementation can throw other error types you may want to log.
Symfony2 - Session timeout
First of all, I've been looking around for informations about this but it was all about Symfony 1.x or even more confusing... Environment Symfony 2.3 FOSUserBundle + Custom User entity Problem In the web site I'm developing I would like user session to end (= have to log in again) either when they close their browser or after 2 hours. In the Symfony2 documentation they say that the default timeout is set with the parameter "framework.session.cookie_lifetime" of the config.yml, and that its default value is 0 which means that the session expires when the user closes his browser. Those options are still on default in my configuration file, but when I a open a session and then close the browser, if I reopen it and go to the website I'm still logged in... So that's where I started getting confused... I tried to force the cookie_lifetime value to 0, but it's the same. The config.yml with the cookie_lifetime option setted : framework: translator: {fallback: %locale%} secret: %secret% default_locale: "%locale%" trusted_proxies: ~ session: cookie_lifetime: 0 fragments: ~ http_method_override: true Do you have any idea why this behavior ?
Usually browsers don't end a session if you keep the tab open — even if you restart the browser.