Reputation: 996
I have a admin panel and I have defined a role for it ROLE_ADMIN
. In my security.yml file I am using a pattern ^/admin/*
so every thing under /admin requires ROLE_ADMIN
. Now in frontend of my app I need to check user role and if role is ROLE_ADMIN
render one file and otherwise render another file. This url does not fall under the pattern defined in security.yml.
So how do I check whether the user is admin or a normal user on the homepage which does not fall under the pattern defined in security.yml ?
Upvotes: 13
Views: 41011
Reputation: 11
In Symfony 4 and above you should use code like below, instead of using services like $this->get('security.authorization_checker'):
$hasAccess = $this->isGranted('ROLE_ADMIN');
$this->denyAccessUnlessGranted('ROLE_ADMIN');
Upvotes: 1
Reputation: 44831
Enable the firewall on the whole app using the ^/
pattern, permit anonymous access and use access_control
to restrict access:
security:
firewalls:
secured_area:
pattern: ^/
anonymous: ~
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
As @itsmequinn suggested, use the isGranted()
method of the security context:
if ($this->get('security.context')->isGranted('ROLE_BRAND')) {
// the user has the ROLE_BRAND role, so act accordingly
}
In Symfony 2.6, security.context
has been split into two separate services. Hence you need to use the security.authorization_checker
service to solve the problem:
if ($this->get('security.authorization_checker')->isGranted('ROLE_BRAND')) {
// the user has the ROLE_BRAND role, so act accordingly
}
Upvotes: 31
Reputation: 519
Easiest solution for this are annotations. Instead of this:
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
# User is a ROLE_ADMIN
}
.. try use this:
/**
* ...
* @Security("has_role('ROLE_ADMIN')")
*/
.. or :
/**
* ...
* @Security("is_granted('POST_ADD', post)")
*/
public function addAction(Post $post){...}
You can read more about Security annotations here. Annotations are best practice in Symfony 2 look here Enjoy!
Upvotes: 1
Reputation: 21910
Symfony 3.0
Prior to Symfony 2.6
you would use SecurityContext
.
SecurityContext
will be deprecated in Symfony 3.0
in favour of the AuthorizationChecker
.
For Symfony 2.6+
& Symfony 3.0
use AuthorizationChecker
.
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
# User is a ROLE_ADMIN
}
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
# User is a ROLE_ADMIN
}
Similar Question: How to check if an user is logged in Symfony2 inside a controller?
Read more the docs here: AuthorizationChecker
Upvotes: 20
Reputation: 1084
Are you in the controller for the page? If so, use the isGranted
method of the security context: Access Controls for Controllers
Upvotes: 5