[Symfony1.4] Authentication and Authorization Checks Are Configured in security.yml
In Symfony1.4, I was using preExecute for authentication checks to prevent users who weren’t logged in from executing specific actions.
I was writing preExecute methods like the one below in all action files of modules that required authentication checks, but it seems like authentication and authorization processing can be done collectively by changing settings in security.yml…
/**
* Check if login authentication is passed before executing action
* If authentication fails, redirect to login page
**/
public function preExecute() {
if (!$this->getUser()->isAuthenticated()) {
$this->redirect('@user_login');
}
}
For authentication and authorization processing settings, you modify security.yml as follows:
■ /project/apps/frontend/config/security.yml
# You can find more information about this file on the symfony website:
# http://www.symfony-project.org/reference/1_4/en/08-Security
#default:
# is_secure: false
all:
is_secure: true
credentials: login
After modifying security.yml, don’t forget to run symfony cc.
Now when accessing the website, if not authenticated, users will be redirected to the login processing page.
If you haven’t written the module and action corresponding to login processing in settings.yml, the default seems to be ‘action’ => ‘login’, ‘module’ => ‘default’, which resulted in a 500 error.
500 | Internal Server Error | sfConfigurationException Unable to find a matching route to generate url for params "array ( 'action' => 'login', 'module' => 'default',)".
The configuration for the module and action corresponding to login processing is written as follows:
(In this case, the UserLogin module’s Login action handles the login processing.)
■ /project/apps/frontend/config/settings.yml (partial excerpt)
all:
.actions:
login_module: UserLogin
login_action: Login
Now when accessing pages other than the login page before authentication, the login processing screen will be displayed.
Login processing works fine with this setup, but this would also display the login processing page when accessing the new user registration page.
This is not usable, so we need to disable authentication checks for the module handling new user registration.
Create a new /config/security.yml in the module’s directory.
■ /project/apps/frontend/modules/UserRegister/config/security.yml
all:
is_secure: false
You can also configure whether to perform authentication checks for specific actions within a module.
For example, if you want New and Complete actions to not require authentication checks, but Confirm action to require authentication checks, you write it as follows:
new:
is_secure: false
confirm:
is_secure: true
complete:
is_secure: false
After editing security.yml and settings.yml, don’t forget to run symfony cc.
That’s all from the Gemba.
【References】
・The symfony Reference Book | security.yml 設定ファイル | symfony | Web PHP Framework
・security.yml 設定ファイル | 日本Symfonyユーザー会