Search code examples
phpphp-5.3symfonysymfony-security

Securized the login system in symfony 3


I have a problem with my system login in symfony 3. So my security.yml is:

security:
role_hierarchy:
  ROLE_ADMIN:       ROLE_USER
  ROLE_FMTI:        ROLE_FMTI
  ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
firewalls:
  dev:
      pattern:  ^/(_(profiler|wdt)|css|images|js)/
      security: false
  secured_area:
      pattern:    ^/admin
      anonymous: ~
      form_login:
          always_use_default_target_path: true
          default_target_path: /admin/homepage
          login_path:  /admin/login
          check_path:  /admin/login_check
      logout:
          path:   /admin/logout
          invalidate_session: true
          target: /admin/login
  access_control:
  - { path: ^/admin/homepage, roles: ROLE_ADMIN }

 providers:
  in_memory:
      memory:
          users:
              admin: { password: admin, roles: 'ROLE_ADMIN' }

 encoders:
  Symfony\Component\Security\Core\User\User: plaintext

The routing :

app_admin_homepage:
  path:     /homepage
  defaults: { _controller: AppAdminBundle:Login:index }
login:
  path:   /login
  defaults:  { _controller: AppAdminBundle:Login:login }
login_check:
  path:   /login_check
logout:
  path: /logout

And the method login from LoginController :

public function loginAction(Request $request)
{
    $authenticationUtils = $this->get('security.authentication_utils');
    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('AppAdminBundle:Member:login.html.twig', array(
        'last_username' => $lastUsername,
        'error'         => $error,
    ));
}

The problem is that if, I'm login in the application with credentials : admin/admin. After that I do the logout.

  1. If I tried to access test.dev/admin/homepage ----> I'm redirecting vers login page witch is test.dev/admin/login, so it's good, I'm login as admin.

  2. If I tried to access test.dev/admin/news/all -----> I can access this page without do the login, and I'm login as anonymous

So I want to redirect to login page for all routes /admin/* if user is not authentificated. Thx and sorry for my english


Solution

  • In the access Control you need to add this :

    access_control:
      - { path: ^/admin/, roles: ROLE_ADMIN }
    

    Which means that for anything beyond the /admin/ route the ROLE_ADMIN is required.

    -- update

    If you need to access to /admin/login/ you need to add to every admin route except the /login, a path pattern like /admin/api/, so in your access control you gonna have this :

    access_control:
          - { path: ^/admin/api/, roles: ROLE_ADMIN }