I am currently trying to create some tests for an application, but I'm stuck on authentication.
In the app I use ldap authentication, which also determines the role of each user. It works well, but to simplify the testing (and to not use real users) I use the in_memory provider in my tests.
The problem is that in my views I use {{ app.user.displayname }}, and the display name is not available with the in_memory provider.
Is there a way to add it ? For example this solution (which does not work) would be perfect :
providers:
in_memory:
memory:
users:
john: { password: john, roles: 'ROLE_USER', displayname: 'John Doe' }
admin: { password: admin, roles: 'ROLE_ADMIN', displayname: 'Admin' }
You could either modify the class
src/Symfony/Component/Security/Core/User/InMemoryUserProvider.php
so it uses the displayname as well or (even better) create your own class which will extend the InMemoryUserProvider and use your own provider (http://symfony.com/doc/current/cookbook/security/custom_provider.html)
Related
I have a user with ROLE_ADMIN and I want to connect him as "ROLE_USER" when calling http://localhost/login but connect him as "ROLE_ADMIN" when calling http://localhost/login?role=admin.
Is it possible to do it in Symfony ?
You can just check if the "role" GET parameter is set and defined as "admin" and then write your code.
If there is a role inheritance and that your admin has ROLE_USER and ROLE_ADMIN, just define custom actions if you detect that it's an admin:
if ($this->isGranted('ROLE_ADMIN')) {
//adminCode
} else {
//userCode
}
I'm new on LDAP concept and i have to make a integration with LDAP and FosUserBundle.
I've installed both bundles, fosuser and FR3DLdapBundle, fosuser is working but i'm missing something about LDAP login.
I need to login with email.
I have the following config: http://pastebin.com/USkJqtbD
I'm using this website for tests: http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/
I'm using email: riemann#ldap.forumsys.com and password: password
But i have the following error
[2015-05-18 16:36:58] ldap_driver.DEBUG: ldap_search(cn=read-only-admin,dc=example,dc=com, (&(objectClass=*)(uid=riemann#ldap.forumsys.com)), uid,mail) [] []
[2015-05-18 16:36:58] security.INFO: User riemann#ldap.forumsys.com not found on ldap [] []
Thank you in advance for you help
With the FR3D Ldap bundle the first attribute that you add in the attributes list is then one that it uses to search by.
In your config the first attribute is uid, so I would suspect that if you used the uid as the username then it would properly. To sort it you will just need to switch up the order so the your mail attribute is first in the list.
fr3d_ldap:
// ...
user:
// ...
attributes: # Specify ldap attributes mapping [ldap attribute, user object method]
- { ldap_attr: mail, user_method: setEmail } # Default
- { ldap_attr: uid, user_method: setUsername }
You have to adapt the search query for find by email.
https://github.com/Maks3w/FR3DLdapBundle/blob/master/Resources/doc/index.md#4-configure-configyml
# app/config/config.yml
fr3d_ldap:
driver:
accountFilterFormat: (&(email=%s)) # Optional. sprintf format %s will be the username
I'm trying to implement very basic authentication in Symfony2. Here are main parts of the code I really don't see any problem
EDIT
complete security.yml
jms_security_extra:
secure_all_services: false
expressions: true
security:
encoders:
Symfony\Component\Security\Core\User\User: plaintext
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
in_memory:
memory:
users:
user: { password: userpass, roles: [ 'ROLE_USER' ] }
admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] }
firewalls:
login:
pattern: ^/login
anonymous: ~
secured_area:
pattern: ^/
stateless: true
form_login:
login_path: /login
check_path: /login_check
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: ROLE_USER }
This works fine, anonymous user is always redirected to loginAction controller.
EDIT
Here is the complete code
<?php
namespace AcmeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class SecurityController extends Controller {
public function loginAction() {
$providerKey = 'secured_area';
$token = new UsernamePasswordToken('test', 'test', $providerKey, array('ROLE_USER'));
$this->container->get('security.context')->setToken($token);
return $this->redirect($this->generateUrl('fronthomepage'));
}
}
I don't see any problem, anonymous user is redirected to loginAction, there is created authenticated user, saved to token and than redirected to secured area as an authenticated user. Unfortunately my code ends with redirect loop which looks like security firewall doesn't accept user as authenticated. Do you see any problem?
Well, your controller job is to render just form but not to populate security context. Symfony2 security firewall will do that for you automatically. You don't need to handle it unless you want to build you own custom authentication.
In other words, your job is to display the login form and any login
errors that may have occurred, but the security system itself takes
care of checking the submitted username and password and
authenticating the user.
Please read this document for clear picture.
If you want to do some custom stuff when a user logs in, in Symfony2 you have to add an event listener that will fire after the user successfully logged in. The event that is fired is security.interactive_login and to hook to it you have to specify this in services.yml file form your bundle Resources/config directory:
Pretty sure you need an actual user object before setting an authenticated user. I did something like this:
class BaseController
protected function setUser($userName)
{
if (is_object($userName)) $user = $userName;
else
{
$userProvider = $this->get('zayso_core.user.provider');
// Need try/catch here
$user = $userProvider->loadUserByUsername($userName);
}
$providerKey = 'secured_area';
$providerKey = $this->container->getParameter('zayso_core.provider.key'); // secured_area
$token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
$this->get('security.context')->setToken($token);
return $user;
}
However doing something like this bypasses much of the security system and is not recommended. I also wanted to use a 3rd party authentication system (Janrain). I looked at the authentication system and initially could not make heads or tails out of it. This was before the cookbook entry existed.
I know it seems overkill but once you work through things then it starts to make more sense. And you get access to a bunch of nifty security functions. It took me quite some time to start to understand the authentication system but it was worth it in the end.
Hints:
1. Work through the cook book backward. I had a real hard time understanding what was going on but I started with adding a new firewall to security.yml and then adding the alias for my security factory. I then sort of traced through what the factory was being asked to do. From there I got the listener to fire up and again traced through the calls. Finally the authentication manager comes into play. Again, time consuming, but worth it in the end. Learned a lot.
One thing that drove me crazy is that classes are scattered all over the place. And the naming leaves something to be desired. Very hard to get an overview. I ended up making my own authentication bundle then putting everything under security.
If you want another example of a working bundle then take a look at: https://github.com/cerad/cerad/tree/master/src/Cerad/Bundle/JanrainBundle
I need to extend SonataUser to set a field called isAdmin to true when a user is being created from the backend.
I have different User groups for ADMIN => (can create admin users and perform CRUD on other entities) and STAFF => (can perform CRUD on other entities).
Customers register from the frontend.
Both backend_users (STAFF) and customers are instances of the User entity, which extends SonataUser.
Till now I was using the default User and Group Admin classes. Here is how my app/config/config.yml looked
...app/config/config.yml...
users:
label: Users
items: [ sonata.user.admin.user ]
groups:
label: Groups
items: [sonata.user.admin.group]
...
It worked fine for me.
Now I needed to customize the default implementation so I copied the code from Sonata/UserBundle/User/BaseUser.php to <my namespace>/AdminBundle/Admin/BackendUser.php
I created the new service and mapped it in config.yml
...app/config/config.yml...
users:
label: Users
items: [ gd_admin.backend_user ]
groups:
label: Groups
items: [sonata.user.admin.group]
...
...GD/AdminBundle/Resources/services.yml...
parameters:
gd_admin.backend_user.class: GD\AdminBundle\Admin\BackendUserAdmin
..
services:
gd_admin.backend_user:
class: %gd_admin.backend_user.class%
tags:
- { name: sonata.admin, manager_type: orm, label: Backend User }
arguments: [null, GD\AdminBundle\Entity\User, null]
# NOTE: No group defined in tags
...
Earlier I had granted the following roles my ADMIN Group:
'ROLE_SONATA_USER_ADMIN_USER_EDIT',
'ROLE_SONATA_USER_ADMIN_USER_LIST',
'ROLE_SONATA_USER_ADMIN_ USER _CREATE',
'ROLE_SONATA_USER_ADMIN_ USER _VIEW',
'ROLE_SONATA_USER_ADMIN_ USER _DELETE',
'ROLE_SONATA_USER_ADMIN_ USER _OPERATOR',
'ROLE_SONATA_USER_ADMIN_ USER _MASTER',
Now they are:
'ROLE_GD_ADMIN_BACKEND_USER_EDIT',
'ROLE_GD_ADMIN_BACKEND_USER_LIST',
'ROLE_GD_ADMIN_BACKEND_USER_CREATE',
'ROLE_GD_ADMIN_BACKEND_USER_VIEW',
'ROLE_GD_ADMIN_BACKEND_USER_DELETE',
'ROLE_GD_ADMIN_BACKEND_USER_OPERATOR',
'ROLE_GD_ADMIN_BACKEND_USER_MASTER',
When I log into my admin/dashboard
I am able to see the BackendUser in Admin Dashboard widget.
But when I click on the "List" or "Add new" I get a 403: Access Denied Exception.
Where am I going wrong?
Thanks,
Amit
I don't think you have to mess around with the BaseUser class from the sonata user bundle.
Instead you could create a new admin crud in your own bundle based on the sonata user admin crud (Sonata\UserBundle\Admin\Document\UserAdmin) and extend it with a prePersist() method to set isAdmin to true:
public function prePersist($object)
{
$object->setIsAdmin(true);
}
prePersist is actually a hook that is called before persisting a new entity.
I see from the official Symfony2 doc on Security that new roles can be defined besides the "classical" ones (i.e. ROLE_USER, ROLE_ADMIN, etc.).
How can I define new roles and register them to my Symfony2 application in order to create roles hierarchy in the security.yml?
Sorry to have bothered all of you! I think that the answer is simple. In fact, it seems that is sufficient to start to use a new role by starting the name with ROLE_.
E.g., it is possible to say ROLE_NEWS_AUTHOR to let only people with that role to be capable to insert a news in the website.
Thanks.
Sure you can simply add any roles starting with ROLE_SOMEROLE.In security.yml file there are two main part to 1.limit the access 2. Who are the memebers can access
a. access_control: Which limit the pattern and specify a role who can access.
b. role_hierarchy: here the hierarchical structure of role, for the below example an Admin user(ROLE_ADMIN) have roles ROLE_USER,ROLE_NEWS_AUTHOR. So he can access all pages of a USER and NEWS_AUTHOR.Whatever the hierarchy you can give.
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }/login any one can access this pattern
- { path: ^/admin/, roles: ROLE_ADMIN }//block all pattern /admin/anything*
- { path: ^/news/, roles: ROLE_NEWS_AUTHOR } //block all pattern /news/anything*
role_hierarchy:
ROLE_ADMIN: [ROLE_USER,ROLE_NEWS_AUTHOR]
In your controller you can check the roles,
if(TRUE ===$this->get('security.context')->isGranted('ROLE_ADMIN') )
{
// do something related to ADMIN
}
else if(TRUE ===$this->get('security.context')->isGranted('ROLE_NEWS_AUTHOR') )
{
// do something related to News Editor
}
Hope this helps you .
HAppy coding.