- CakePHP 1.3 Application Development Cookbook
- Mariano Iglesias
- 1088字
- 2021-04-09 22:04:14
The first task to be completed when we are in the process of adding authentication to an application is to identify which controllers will need user access. Normally we would make every controller and action protected by default, and then we would specify which areas of our application allow public access.
We must have a users
table that should contain, at least, two fields: username
(to hold the username) and password
(to hold a hash made out of the user's password).
If you don't have a table for this purpose, you can use the following SQL statement to create it:
CREATE TABLE `users`( `id` INT UNSIGNED AUTO_INCREMENT NOT NULL, `username` VARCHAR(255) NOT NULL, `password` CHAR(40) NOT NULL, PRIMARY KEY(`id`) );
- Create a file named
users_controller.php
and place it inside yourapp/controllers
folder with the following contents:<?php class UsersController extends AppController { public function login() { } public function logout() { $this->redirect($this->Auth->logout()); } } ?>
- Create a file named
login.ctp
in yourapp/views/users
folder (create the folder if you don't have one already), and add the following contents:<?php echo $this->Form->create(array('action'=>'login')); echo $this->Form->inputs(array( 'legend' => 'Login', 'username', 'password' )); echo $this->Form->end('Login'); ?>
- Create a file named
app_controller.php
in yourapp/
folder with the following contents:<?php class AppController extends Controller { public $components = array( 'Auth' => array( 'authorize' => 'controller' ), 'Session' ); public function isAuthorized() { return true; } } ?>
- Modify the
UsersController
, and add the following code before thelogin
method:public function beforeFilter() { parent::beforeFilter(); $this->Auth->allow('add'); } public function add() { if (!empty($this->data)) { $this->User->create(); if ($this->User->save($this->data)) { $this->Session->setFlash('User created!'); $this->redirect(array('action'=>'login')); } else { $this->Session->setFlash('Please correct the errors'); } } }
- Create a file named
add.ctp
and place it in yourapp/views/users
folder with the following contents:<?php echo $this->Form->create(); echo $this->Form->inputs(array( 'legend' => 'Signup', 'username', 'password' )); echo $this->Form->end('Submit'); ?>
We now have a fully working authentication system. We can add new users by browsing to
http://localhost/users/add
, logging in by browsing tohttp://localhost/users/login
, and finally logging out by browsing tohttp://localhost/users/logout
.After creating a user, you should see the login form with a success message, as shown in the following screenshot:
We start by creating two actions in the UsersController
class: login()
, to show and process submissions of the login form, and logout()
, to handle users logging out.
You may be surprised that the login()
method has no logic whatsoever. To display the form, all we need to do is display the action's view. The form submission is taken care of by the Auth
component, leaving us with no need to implement any controller logic. Therefore, the only implementation we need is to create a view for this action, which includes a simple form with two fields: username
, and password
.
The logout()
controller action simply calls the Auth
component's logout()
method. This method removes the logged-in user data from the session, and returns the address to which the user should be redirected after logging out, obtained from the previously configured logoutRedirect
setting of the component (defaults to the application's home page if the setting was not configured.)
Next, we add two components to the controller: Session
, and Auth
. The Session
component is needed to create the messages (through the use of its setflash()
method) that informs the user if a login attempt was unsuccessful, or if a user was created.
The Auth
component operates between your controller's actions and the incoming request by means of the beforeFilter
callback method. It uses it's authorize
setting to check what type of authentication scheme is to be used.
Once the Auth
component is added to a controller, all actions in that controller are not accessible unless there is a valid user logged in. This means that if we had any actions that should be public (such as the login()
and add()
actions in our controller), we would have to tell the Auth
component about them.
If one wishes to make some actions public, one can add the name of these actions to the allowedActions
setting of the Auth
component, or by calling its allow()
method. We use the later approach to tell the Auth
component that the add()
action should be reachable without a logged-in user. The login()
action is automatically added to the list of public actions by the Auth
component.
When the user attempts to reach an action that is not within the public actions, the Auth
component checks the session to see if a user is already logged in. If a valid user is not found, it redirects the browser to the login
action. If there is a user who is logged in, it uses the controller's isAuthorized
method to check if the user has access. If its return value is true
, it allows access, otherwise access is rejected. In our case, we implemented this method in AppController
, our base controller class. If the attempted action requires a user who is logged in, the login()
action is executed. After the user submits data using the login form, the component will first hash the password field, and then issue a find operation on the User
model to find a valid account, using the posted username and password. If a valid record is found, it is saved to the session, marking the user as logged in.
When the Auth
component is enabled on a controller and the user submits a form with a field named password
(regardless if it is being rendered in the login form), the component will automatically hash the password
field before executing the controller's action.
Note
The Auth
component uses the salt defined in the configuration setting Security.salt
(in your app/config/core.php
file) to calculate the hash. Different salt values will produce different hashes even when using the same password. Therefore, make sure you change the salt on all your CakePHP applications, thus enhancing the security of your authentication system.
This means that the action will never hold the plain password value, and this should be particularly noted when utilizing mechanisms to confirm password validations. When you are implementing such validation, make sure you hash the confirmation field using the proper method:
if (!empty($this->data)) { $this->data['User']['confirm_password'] = $this->Auth->password($this->data['User']['confirm_password']); // Continue with processing }
- Creo Parametric 8.0中文版基礎(chǔ)入門一本通
- Photoshop 2022從入門到精通
- SOLIDWORKS 2021中文版基礎(chǔ)入門一本通
- COSPLAY的后期藝術(shù):Lightroom+Photoshop修圖技法攻略
- 新編三維CAD習(xí)題集
- 專業(yè)級(jí)音樂制作理論與實(shí)踐Pro Tools:從入門到應(yīng)用
- PyTorch深度學(xué)習(xí)簡(jiǎn)明實(shí)戰(zhàn)
- 中文版Photoshop CC平面設(shè)計(jì)實(shí)用教程
- Photoshop CS6完美創(chuàng)意設(shè)計(jì):不一樣的圖像藝術(shù)處理
- Photoshop CS6案例教程(第3版)
- 中文版3ds Max 2016/VRay效果圖制作技術(shù)大全
- 中文版Photoshop CS5實(shí)用教程(第2版)
- Microsoft Silverlight 4 and SharePoint 2010 Integration
- 寫給大家看的PPT設(shè)計(jì)書(第2版)
- Expert Python Programming