Users are allowed to access URIs that they are permitted to otherwise they get "403 Forbidden. Access Denied" message so the example below satisfies this rule. Also the users, credentials, roles and URIs are all defined in "security.yml". For more info, click here.

In example below, we have "Backend" and "Frontend" bundles. Backend is accessible for Admin and Superadmin roles only. Frontend is accessible for all roles but only DefaultController requires no roles so the users with no roles can access it too.


Bundles, Controllers and access rights


FrontendBundle



BackendBundle



Security.yml


To assign multiple roles to a user, use roles: [ROLE_ADMIN, ROLE_SUPER_ADMIN]. The access control uses the first matching rule to enforce access so start placing the most strict URIs on top.


security:
encoders:
Symfony\Component\Security\Core\User\User:
algorithm: bcrypt
cost: 12

providers:
in_memory:
memory:
users:
basic:
password: $2a$12$Mnp6eUx1AJ5YABwmprcu/OHo21klIpQ/PA7D7PdKx5SA4urdav6/e #basic
roles: ROLE_USER
admin:
password: $2a$12$aRC0GRcjZS9bXfQYlpT8f.JkkrwuK0xZwKuoQ78i1CsErbHtriWLm #admin
roles: ROLE_ADMIN
super:
password: $2a$12$7SeyjOot3/3Ez1c0Dm8W0u/EenNEs8ykOl16D5aKkJkzLEq4lvXP2 #super
roles: ROLE_SUPER_ADMIN

firewalls:
dev:
pattern: ^/(_(profiler|wdt|error)|css|images|js)/
security: false

default:
anonymous: ~
http_basic: ~
form_login:
login_path: /login
check_path: /login
logout:
invalidate_session: true
path: /logout
target: /

role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

access_control:
- { path: ^/backend/superadmin, role: ROLE_SUPER_ADMIN }
- { path: ^/backend/secret, role: ROLE_SUPER_ADMIN }
- { path: ^/backend, role: ROLE_ADMIN }
- { path: ^/country, role: ROLE_USER }
- { path: ^/, role: IS_AUTHENTICATED_ANONYMOUSLY }

FrontendBundle


Controllers.yml


services:
application_frontend.controller.default:
class: Application\FrontendBundle\Controller\DefaultController
arguments:
- @templating
- @security.context

application_frontend.controller.country:
class: Application\FrontendBundle\Controller\CountryController
arguments:
- @templating
- @security.context

application_frontend.controller.security:
class: Application\FrontendBundle\Controller\SecurityController
arguments:
- @templating
- @security.authentication_utils

DefaultController


namespace Application\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;

/**
* @Route("", service="application_frontend.controller.default")
*/
class DefaultController extends Controller
{
private $templating;
private $securityContext;

public function __construct(
EngineInterface $templating,
SecurityContextInterface $securityContext
) {
$this->templating = $templating;
$this->securityContext = $securityContext;
}

/**
* @Route("")
* @Method({"GET"})
*/
public function indexAction()
{
$message = sprintf('
Controller: /
Method: indexAction
Valid Roles: IS_AUTHENTICATED_ANONYMOUSLY, ROLE_USER, ROLE_ADMIN, ROLE_SUPER_ADMIN
Current Role: %s
Username: %s',
$this->securityContext->getToken()->getRoles()[0]->getRole(),
$this->securityContext->getToken()->getUsername()
);

return $this->getTemplate('index', ['message' => $message]);
}

/**
* @Route("/list")
* @Method({"GET"})
*/
public function listAction()
{
$message = sprintf('
Controller: /list
Method: listAction
Valid Roles: IS_AUTHENTICATED_ANONYMOUSLY, ROLE_USER, ROLE_ADMIN, ROLE_SUPER_ADMIN
Current Role: %s
Username: %s',
$this->securityContext->getToken()->getRoles()[0]->getRole(),
$this->securityContext->getToken()->getUsername()
);

return $this->getTemplate('index', ['message' => $message]);
}

/**
* Creates twig template.
*
* @param string $template
* @param array $parameters
*
* @return Response
*/
private function getTemplate($template, array $parameters = [])
{
return $this->templating->renderResponse(
sprintf('ApplicationFrontendBundle:Default:%s.html.twig', $template),
$parameters
);
}
}

CountryController


namespace Application\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;

/**
* @Route("country", service="application_frontend.controller.country")
*/
class CountryController extends Controller
{
private $templating;
private $securityContext;

public function __construct(
EngineInterface $templating,
SecurityContextInterface $securityContext
) {
$this->templating = $templating;
$this->securityContext = $securityContext;
}

/**
* @Route("")
* @Method({"GET"})
*/
public function indexAction()
{
$message = sprintf('
Controller: /country
Method: indexAction
Valid Roles: ROLE_USER, ROLE_ADMIN, ROLE_SUPER_ADMIN
Current Role: %s
Username: %s',
$this->securityContext->getToken()->getRoles()[0]->getRole(),
$this->securityContext->getToken()->getUsername()
);

return $this->getTemplate('index', ['message' => $message]);
}

/**
* @Route("/list")
* @Method({"GET"})
*/
public function listAction()
{
$message = sprintf('
Controller: /country/list
Method: listAction
Valid Roles: ROLE_USER, ROLE_ADMIN, ROLE_SUPER_ADMIN
Current Role: %s
Username: %s',
$this->securityContext->getToken()->getRoles()[0]->getRole(),
$this->securityContext->getToken()->getUsername()
);

return $this->getTemplate('index', ['message' => $message]);
}

/**
* Creates twig template.
*
* @param string $template
* @param array $parameters
*
* @return Response
*/
private function getTemplate($template, array $parameters = [])
{
return $this->templating->renderResponse(
sprintf('ApplicationFrontendBundle:Default:%s.html.twig', $template),
$parameters
);
}
}

SecurityController


namespace Application\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

/**
* @Route("", service="application_frontend.controller.security")
*/
class SecurityController extends Controller
{
private $templating;
private $authenticationUtils;

public function __construct(
EngineInterface $templating,
AuthenticationUtils $authenticationUtils
) {
$this->templating = $templating;
$this->authenticationUtils = $authenticationUtils;
}

/**
* @Method({"GET"})
* @Route("/login")
*/
public function indexAction()
{
$loginErrors = $this->authenticationUtils->getLastAuthenticationError();
$lastUsername = $this->authenticationUtils->getLastUsername();

return $this->getTemplate(
'login',
[
'loginErrors' => $loginErrors,
'lastUsername' => $lastUsername
]
);
}

/**
* This controller will not be executed, as the route is handled by the Security system
*
* @Method({"POST"})
* @Route("/login")
*/
public function loginAction() {}

/**
* This controller will not be executed, as the route is handled by the Security system
*
* @Method({"GET"})
* @Route("/logout")
*/
public function logoutAction() {}

/**
* Creates twig template.
*
* @param string $template
* @param array $parameters
*
* @return Response
*/
private function getTemplate($template, array $parameters = [])
{
return $this->templating->renderResponse(
sprintf('ApplicationFrontendBundle:Security:%s.html.twig', $template),
$parameters
);
}
}

Index.html.twig


{% extends '::base.html.twig' %}

{% block body %}
{% spaceless %}
{{ message|raw }}
{% endspaceless %}
{% endblock %}

Login.html.twig


{% extends '::base.html.twig' %}

{% block body %}
{% spaceless %}
{% if loginErrors %}
<div>{{ loginErrors.messageKey|trans(loginErrors.messageData, 'security') }}</div>
{% endif %}

<form action="{{ path('application_frontend_security_login') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ lastUsername }}" />
<br />
<label for="password">Password:</label>
<input type="password" id="password" name="_password" />
<br />
<input type="hidden" name="_target_path" value="/" />
<button type="submit">login</button>
</form>
{% endspaceless %}
{% endblock %}

BackendBundle


Controllers.yml


services:
application_backend.controller.default:
class: Application\BackendBundle\Controller\DefaultController
arguments:
- @templating
- @security.context

application_backend.controller.superadmin:
class: Application\BackendBundle\Controller\SuperadminController
arguments:
- @templating
- @security.context

DefaultController


namespace Application\BackendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;

/**
* @Route("", service="application_backend.controller.default")
*/
class DefaultController extends Controller
{
private $templating;
private $securityContext;

public function __construct(
EngineInterface $templating,
SecurityContextInterface $securityContext
) {
$this->templating = $templating;
$this->securityContext = $securityContext;
}

/**
* @Route("")
* @Method({"GET"})
*/
public function indexAction()
{
$message = sprintf('
Controller: /backend
Method: indexAction
Valid Roles: ROLE_ADMIN, ROLE_SUPER_ADMIN
Current Role: %s
Username: %s',
$this->securityContext->getToken()->getRoles()[0]->getRole(),
$this->securityContext->getToken()->getUsername()
);

return $this->getTemplate('index', ['message' => $message]);
}

/**
* @Route("/list")
* @Method({"GET"})
*/
public function listAction()
{
$message = sprintf('
Controller: /backend/list
Method: listAction
Valid Roles: ROLE_ADMIN, ROLE_SUPER_ADMIN
Current Role: %s
Username: %s',
$this->securityContext->getToken()->getRoles()[0]->getRole(),
$this->securityContext->getToken()->getUsername()
);

return $this->getTemplate('index', ['message' => $message]);
}

/**
* @Route("/secret")
* @Method({"GET"})
*/
public function secretAction()
{
$message = sprintf('
Controller: /backend/secret
Method: secretAction
Valid Roles: ROLE_SUPER_ADMIN
Current Role: %s
Username: %s',
$this->securityContext->getToken()->getRoles()[0]->getRole(),
$this->securityContext->getToken()->getUsername()
);

return $this->getTemplate('index', ['message' => $message]);
}

/**
* Creates twig template.
*
* @param string $template
* @param array $parameters
*
* @return Response
*/
private function getTemplate($template, array $parameters = [])
{
return $this->templating->renderResponse(
sprintf('ApplicationBackendBundle:Default:%s.html.twig', $template),
$parameters
);
}
}

SuperadminController


namespace Application\BackendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;

/**
* @Route("superadmin", service="application_backend.controller.superadmin")
*/
class SuperadminController extends Controller
{
private $templating;
private $securityContext;

public function __construct(
EngineInterface $templating,
SecurityContextInterface $securityContext
) {
$this->templating = $templating;
$this->securityContext = $securityContext;
}

/**
* @Route("")
* @Method({"GET"})
*/
public function indexAction()
{
$message = sprintf('
Controller: /backend/superadmin
Method: indexAction
Valid Roles: ROLE_SUPER_ADMIN
Current Role: %s
Username: %s',
$this->securityContext->getToken()->getRoles()[0]->getRole(),
$this->securityContext->getToken()->getUsername()
);

return $this->getTemplate('index', ['message' => $message]);
}

/**
* @Route("/list")
* @Method({"GET"})
*/
public function listAction()
{
$message = sprintf('
Controller: /backend/superadmin/list
Method: listAction
Valid Roles: ROLE_SUPER_ADMIN
Current Role: %s
Username: %s',
$this->securityContext->getToken()->getRoles()[0]->getRole(),
$this->securityContext->getToken()->getUsername()
);

return $this->getTemplate('index', ['message' => $message]);
}

/**
* Creates twig template.
*
* @param string $template
* @param array $parameters
*
* @return Response
*/
private function getTemplate($template, array $parameters = [])
{
return $this->templating->renderResponse(
sprintf('ApplicationBackendBundle:Default:%s.html.twig', $template),
$parameters
);
}
}

Index.html.twig


{% extends '::base.html.twig' %}

{% block body %}
{% spaceless %}
{{ message|raw }}
{% endspaceless %}
{% endblock %}

Login webform



Authenticated page



Profiler




403