Can't Logout user in Symfony4 - php

I'm updating a project built with Symfony2.7 to Symfony4, everything is working fine and have good compatibility, but one thing that should be fine, a built-in resource, the security layer, doesn't work as expected.
The problem I'm facing is that I can't logout users anymore. I followed the steps on the guide but nothing changed.
Below is the security config:
#config/packages/security.yaml
security:
encoders:
App\Entity\Clients:
algorithm: bcrypt
providers:
app_user_provider:
entity:
class: App\Entity\Clients
firewalls:
app:
pattern: ^/
anonymous: ~
provider: app_user_provider
remember_me:
secret: "%kernel.secret%"
form_login:
use_referer: true
login_path: login
check_path: login_check
always_use_default_target_path: false
default_target_path: dashboard
csrf_token_generator: security.csrf.token_manager
logout:
path: logout
target: home
invalidate_session: false
The paths I'm using are route names, but also tried the path itself.
I can normally login any user, but when I hit the logout route, I'm just redirected to home route, but the user is still authenticated.
Tried to set a custom handler logout like:
logout:
handlers: [logout_handler]
It references to a service implementing Symfony\Component\Security\Http\Logout\LogoutHandlerInterface, but it didn't even call the handler.
It would be great if I could only use the default handler, and it's necessary to maintain the "remember_me" behavior, which was also working fine in 2.7.
Could anyone help me with that?
EDIT: My config routes.yaml is empty, 'cause I'm using annotation routes, the config/packages/routing.yaml is as follows:
framework:
router:
strict_requirements: ~
Just like when initialized with the composer create-project command.
And for the annotations config I have the file config/routes/annotations.yaml:
controllers:
resource: ../../src/Controller/
type: annotation
Again, it's the config the recipe created by itself.

You need remove logout action in your controller,
next add route to config/routes.yaml.
More info here.
https://symfony.com/doc/current/security.html#logging-out

I achieved the result of logging out by removing the REMEMBERME cookie with a **LogoutSuccessHandler* (reference).
I think of this as being an ugly workaround, but the result was satisfactory, as everything worked fine. But still don't know why it didn't worked automatically with the configs, also why I couldn't use a custom logout handler. If anyone comes up with better answer, I can mark it as the accepted answer.

If you follow the instructions at Symfony Security Logging Out, make sure you use the proper route name to get to /logout. I had to use 'app_logout' to actually get it to logout and I was not able to change that path name in the Security.yaml file without also modifying the controller annotations (see below). No controller needed. No custom handler needed (thank god).
After you configure logout, try running php bin/console debug:router to check the actual route to /logout.
The logout part of my Security.yaml looked like this:
logout:
path: app_logout
# where to redirect after logout
target: front
Based on instructions, I added an empty controller (if you want custom path names, you'll have to change the path names here plus add the change to Security.yaml):
<?php
//App/Controller/SecurityController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class SecurityController extends AbstractController
{
/**
* #Route("/logout", name="app_logout")
*/
public function logout()
{
throw new \Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
}
}
My call looked like this:
<a class="nav-link" href="{{ path('app_logout') }}">Logout</a>

Related

Looked for namespace "security", found none

I am trying to create a custom bundle that is using a special authentication service. This bundle will be used by all of our projects.
I want to make it so it is needed a little configuration to use it.
My problem appears when i'm trying to add a security config inside my package like so:
# security.yml
security:
providers:
specialauth:
id: AuthBundle\Security\SpecialAuthProvider
firewalls:
main:
logout:
path: '/logout'
When I do this inside my bundle I get this error:
Looked for namespace "security", found none
If I move this security configuration inside my app/config it works ok but I want this config to stay in the AuthBundle so the developers don't have to configure much stuff for every project.
Is this a restriction from symfony not allowing security configs from external bundles or what can the problem be?
You can import your security.yml inside the security file of the project:
app/config/security.yml :
imports:
- { resource: '#AuthBundle/Resources/config/security.yml' }

How do I create a logout route in symfony?

I'm trying to implement a simple login and logout in my symfony app and in the documentation it says I need to create a route to the logout page. And there is a code like this:
# app/config/routing.yml
logout:
path: /logout
I'm trying to paste it into my app/config/routing.yml, so it looks like this:
# app/config/routing.yml
app:
resource: '#AppBundle/Controller/'
type: annotation
logout:
path: /logout
But I get an error
The file "(...)\app/config\routing.yml" does not contain valid YAML
I was searching through the documentation and couldn't find anythig that would help me solve it. I can't really understand how this routing configuration file works and why I get this error.
Suggest when making changes to any yaml file in a development environment, save the yaml first, make the change, then check for error messages. If you get error messages back them out.
Also set up your editor so that it points out things like tabs, spaces, etc... So it's easier to see right away.

Symfony2 Firewall: protect /web folder

I am developping a SF2 web-app which is fully behind a firewall: nobody shouldn't be able to see or modify anything before behing logged (except login form, of course).
So here is the firewall part of my security.yml file:
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main_login:
pattern: ^/login$
anonymous: true
main:
pattern: ^/
anonymous: false
form_login:
login_path: fos_user_security_login
check_path: fos_user_security_check
logout:
path: fos_user_security_logout
target: /
This works fine: if I type the url http://mywebsite.com/app.php/article/show/1 while unlogged, I am forwarded to the login page.
My problem is that I have some documents and media files located in Symfony's web directory (e.g. myapp/web/document/myTextFile.txt). They are accessible via my app for logged users, but also for non-logged users!
Anybody who types http://mywebsite.com/app.php/document/myTextFile.txt can download the file...
Why doesn't the pattern: ^/ line prevent this? Is the web folder excluded by default because it contains app.php and js/and css/ folder?
How do I protect my documents?
Update: Display protected images
I tried the solution suggested by Gerry, it works fine to protect the download of my documents.
However, I also have pictures in my document folder and I would like to display these pictures, directly included in the relevant pages.
For example, in http://mywebsite.com/app.php/article/show/1 there will be some text and the picture myapp/app/Resources/document/AAA.jpg, and in http://mywebsite.com/app.php/article/show/2 there will be some text and the picture myapp/app/Resources/document/BBB.jpg, etc.
I tried to do it with Assetic but it seems that it is done for "static" images (like top logo, or images which are not object-dependent).
A solution I see is to convert the image in Base64 and include it like this : <img alt="" src="data:image/png;base64(...)" />, but it seems really ugly...
The web directory is your public root directory, being served by the webserver (Apache/Nginx/...).
By default any request to an existing file does not pass Symfony at all, so no firewall setting is going to prevent access to files residing in the web root.
The clean solution is to move these files to another directory, outside the webroot, for example app/Resources/uploads. Then you could write a Symfony controller for downloading these files.
I don't have a working installation of Symfony right now, but try to move your documents from web, if will firewall proceed.
Let me know the answer please, will try to find out a solution if it will not work, or if you will not be able to move those files in production.

In Symfony2.0, I want to disable some url in router.yml when using app.php (prod env)?

When using app_dev.php, there are some useful url for me to debug project. Such as
check_debug:
pattern: /check_url1
defaults: {....}
check_debug_and_prod:
pattern: /check_url2
defaults: {....}
check_prod:
pattern: /check_url3
defaults: {....}
I want to disable 'check_debug' when I using app.php(prod env), and disable 'check_prod' when I using app_dev.php(dev env), and keep 'check_debug_and_prod' both when using app.php or app_dev.php.
How to config in SF2?
You can have multiple routing.yml files for different environments. E. g. app/config/routing.yml, app/config/routing_dev.yml
You can have different routing files for different environments:
Create src/AAA/Bundle/CCBundle/Resource/config/routing.yml
Create src/AAA/Bundle/CCBundle/Resource/config/routing_dev.yml
Include src/AAA/Bundle/CCBundle/Resource/config/routing.yml in app/config/routing.yml
Include src/AAA/Bundle/CCBundle/Resource/config/routing_dev.yml in app/config/routing_dev.yml
You can use the routing_dev.yml to add routes you only want in the dev mode. When you will use app.php it will only check for routing.yml and this way you will not have to be preoccupied by the unwanted routes.
You can also create your own routing files. See how Sf2 handles to import inside yml files.

How to create the route in symfony 2 which maps to external URL?

Referring to this,
http://symfony.com/doc/current/book/routing.html
we can map url pattern to controller and action
app/config/routing.yml
blog_show:
path: /blog/{slug}
defaults: { _controller: AcmeBlogBundle:Blog:show }
I want to map the path to external url.
app/config/routing.yml
blog_show:
path: /blog/{slug}
defaults: "www.example.com/blog"
The requirement is, my current website is in kohana, I am porting it gradually to symfony 2. For my symfony2 app kohana URL are like external urls, I want to configure these urls in routing and use them in standard way,
e.g. in Twig,
<a href="{{ path('blog_show'}}">
Read this blog post.
</a>
So later on when I port my pages to Symfony, I will have to change only routing file so that I could use same blog_show key to refer to url and I wont' have to change all the files where I have used urls.
You can do this by using one of the Symfony framework controllers although I'm not sure how this would work with parameters:
blog_show:
path: /blog/{slug}
defaults:
_controller: FrameworkBundle:Redirect:urlRedirect
path: "http://example.com/blog"
permanent: true
Note that path: /blog/{slug} grabs the slug directly, but path: "http://example.com/blog/{slug}" doesn't work.
Source: http://symfony.com/doc/current/cookbook/routing/redirect_in_config.html
As of Symfony 2.2 this is possible by adding the host constraint to the routes:
routing.yml
user_homepage:
path: /path/to/whatever
host: "sub.domain.ext"
defaults:
_controller: forExampleAnyNamespaceBundle:Controller:action
There's an official blog post on this issue: http://symfony.com/blog/new-in-symfony-2-2-url-host-support-in-the-routing
The router feature of Symfony doesn't work that way...
I suggest you create a Twig extension for this. Read more about this here:
http://symfony.com/doc/current/cookbook/templating/twig_extension.html
You could create a function that works very similar to the regular url() function, so you can migrate as easily as possible.
{{ legacyUrl('blog_post', {slug: 'my-blog-post'}) }}
After you migrated the blog to Symfony, all you need to do is create a route called "blog_post" and change "legacyUrl" to "url".
Seems there is no native Symfony way to handle this problem.

Categories