简体   繁体   中英

Symfony2 > Use Security Context in Public Route (possible alternative)

I have a function UserController:saveUserAction() . This function is being used throughout my system WHENEVER a User Entity needs to be created or modified. This can happen from three places:

1) Admin Panel → User Administration (System Admin can create/modify users).
2) Members Dashboard → My Details (User can edit his own details).
3) Registration (Non-users can sign up and a user is created for them).

Now there are certain fields that may ONLY be set by an administrator, for instance, the USER_ROLE. (I do not want someone who is registering 'hacking' the system and signing themselves up as an administrator). Normally if ($this->get('security.context')->isGranted('ROLE_ADMIN')) works fine to determine if the user is an administrator, but seeing as the route to saveUser() is public (in order to facilicate public registrations), I am getting the error:

The security context contains no authentication token. One possible reason may be that there is no firewall configured for this URL.

Is there a way to user the security context on a public route or is there some kind of alternative other than checking manually what roles the logged in user (if any logged in user) has, because this is quite lumbersome as can be seen at Symfony2 > Easier way to determine access

I have found a solution. I placed the route under my firewall and placed an exception in security.yml that the specific route is authenticated anonymously. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM