热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

CakePHP用户认证实例

如果你刚刚接触CakePHP,你会被这个例子所吸引从而将这些代码复制到你的关键业务场景或者敏感数据处理应用中去。注意,本章讨论的是Cake的内部工作机制

CakePHP用户认证实例
示例:简单的用户认证
Section 1 Big Picture
如果你刚刚接触CakePHP,你会被这个例子所吸引从而将这些代码复制到你的关键业务场景或者敏感数据处理应用中去。注意,本章讨论的是Cake的内部工作机制,并不是应用的安全模块。我不确定我是不是提供了一些显而易见的安全漏洞,这个例子的目的是展示Cake内部是如何处理安全问题的,你可以如何为自己的应用创建独立的“防弹衣”

Cake的访问控制是基于内置的ACL引擎,但是用户的认证以及认证信息的持久化是怎么样的呢?

我们发现对于时下的各种应用系统,用户认证模块是各不相同。有些喜欢使用哈希编码后的密文密码,有的喜欢使用LDAP认证,并且对于每个系统,User model总是有着些许差别的。我们将这部分工作留给了你。这会不会在未来的版本中改变呢?现在我们还不是很确定,因为就目前的情况来看,将用户认证模块纳入框架还不是很值得的一件事情,创建你自己的用户认证系统是非常简单的。

你需要做3件事情:

认证用户的方式(通常为校验用户的标识,比如用户名/密码组合)
跟踪用户访问情况的方式(通常使用Session)
校验用户是否已经认证通过的方式(通常是和Session进行交互)
这个示例中,我们会为一个客户管理系统创建简单的用户认证系统。这样一个虚拟项目是用来管理客户联系信息和相关的客户记录等。除了少数的公共的视图用来展示客户姓名和职务以外的所有功能都必须通过用户认证后才能访问。

我们从如何验证那些试图访问系统的用户开始。通过认证的用户信息会被Cake Session Component存储在PHP session中。我们从session中取到用户信息后就可以判断哪些*作是该用户可以执行的。

有件事情需要注意——认证并不是访问控制的同义词。我们现在所做的事情是检查用户是不是真的是他所宣称的那个用户,并且允许他访问相应部分的功能。如果你希望更加具体地调节这种访问,请参考前面的ACL章节。我们觉得ACL比较适合那样的场景,不过现在我们还是只关注最简单的用户认证。

我也要再表达一次,这并不代表这个例子只能服务于最基本应用安全。我们只是希望给你提供足够的蔬菜让你建立自己的“防弹衣”。

Section 2 认证与持久化
首先,我们需要一种将用户信息持久化的方式。这个客户管理系统中我们使用数据库方式来持久化用户信息:

Table 'users', Fictional Client Management System Database  
CREATE TABLE `users` (  
  `id` int(11) NOT NULL auto_increment,  
  `username` varchar(255) NOT NULL,  
  `password` varchar(32) NOT NULL,  
  `first_name` varchar(255) NOT NULL,  
  `last_name` varchar(255) NOT NULL,  
  PRIMARY KEY  (`id`)  
)  
            
非常简单是吧?我们的User model也同样的简单:

class User extends AppModel  
{  
    var $name = 'User';  
}  
?>  
                
第一个要完成的是登陆的view和action。这能给用户提供一个登陆的入口,同时也为系统提供了处理用户信息判断是否可以访问系统的机会。使用HTML helper可以很简单的创建该Form:

/app/views/users/login.thtml  
  

The login credentials you supplied could not be recognized. Please try again.

  
  
 
url('/users/login'); ?>" method="post">  
  
      
    input('User/username', array('size' => 20)); ?>  
  
  
      
    password('User/password', array('size' => 20)); ?>  
  
  
    submit('Login'); ?>  
  
  
         
/app/views/users/login.thtml

The login credentials you supplied could not be recognized. Please try again.


url('/users/login'); ?>" method="post">


   
    input('User/username', array('size' => 20)); ?>


   
    password('User/password', array('size' => 20)); ?>


    submit('Login'); ?>


                
对应这个简单的视图(view),还需要一个action(/users/login),代码如下所示:

/app/controllers/users_controller.php (partial)  
class UsersController extends AppController  
{  
    function login()  
    {  
        $this->set('error', false);  
        // If a user has submitted form data: 
        if (!empty($this->data)) 
        { 
            // First, let's see if there are any users in the database  
            // with the username supplied by the user using the form: 
            $someOne= $this->User->findByUsername($this->data['User']['username']);  
            // At this point, $someone is full of user data, or its empty.  
            // Let's compare the form-submitted password with the one in   
            // the database.  
            if(!emptyempty($someone['User']['password']) && $someone['User']['password'] == $this->data['User']['password']) 
            { 
                // Note: hopefully your password in the DB is hashed,  
                // so your comparison might look more like: 
                // md5($this->data['User']['password']) == ... 
                // This means they were the same. We can now build some basic 
                // session information to remember this user as 'logged-in'. 
                $this->Session->write('User', $someone['User']); 
                // Now that we have them stored in a session, forward them on 
                // to a landing page for the application.  
                $this->redirect('/clients'); 
            } 
            // Else, they supplied incorrect data: 
            else 
            { 
                // Remember the $error var in the view? Let's set that to true:  
                $this->set('error', true);  
            }  
        }  
    }  
 
    function logout()  
    {  
        // Redirect users to this action if they click on a Logout button.  
        // All we need to do here is trash the session information:  
        $this->Session->delete('User');  
        // And we should probably forward them somewhere, too...  
        $this->redirect('/');  
    }  
}  
?>  
         
/app/controllers/users_controller.php (partial)
class UsersController extends AppController
{
    function login()
    {
        //Don't show the error message if no data has been submitted.
        $this->set('error', false);
        // If a user has submitted form data:
        if (!empty($this->data))
        {
            // First, let's see if there are any users in the database
            // with the username supplied by the user using the form:
            $someOne= $this->User->findByUsername($this->data['User']['username']);
            // At this point, $someone is full of user data, or its empty.
            // Let's compare the form-submitted password with the one in
            // the database.
            if(!empty($someone['User']['password']) && $someone['User']['password'] == $this->data['User']['password'])
            {
                // Note: hopefully your password in the DB is hashed,
                // so your comparison might look more like:
                // md5($this->data['User']['password']) == ...
                // This means they were the same. We can now build some basic
                // session information to remember this user as 'logged-in'.
                $this->Session->write('User', $someone['User']);
                // Now that we have them stored in a session, forward them on
                // to a landing page for the application.
                $this->redirect('/clients');
            }
            // Else, they supplied incorrect data:
            else
            {
                // Remember the $error var in the view? Let's set that to true:
                $this->set('error', true);
            }
        }
    }

    function logout()
    {
        // Redirect users to this action if they click on a Logout button.
        // All we need to do here is trash the session information:

        $this->Session->delete('User');

        // And we should probably forward them somewhere, too...
    
        $this->redirect('/');
    }
}
?>
                
还不是很坏:如果你写的简炼点,代码应该不会超过20行。这个action的结果有这样两种:
1 用户通过认证,将信息存入Session,并转向到系统首页
2 未通过认证,返回到登陆页面,并显示相关错误信息。

Section 3 访问校验
现在我们可以认证用户了,让我们使系统可以踢除那些不登陆就希望自己访问非公共内容的用户。

一种办法就是在controller中添加一个函数来检查session状态。

/app/app_controller.php  
class AppController extends Controller  
{  
    function checkSession()  
    {  
        // If the session info hasn't been set...  
        if (!$this->Session->check('User')) 
        { 
            // Force the user to login 
            $this->redirect('/users/login');  
            exit();  
        }  
    }  
}  
?>  
         
/app/app_controller.php
class AppController extends Controller
{
    function checkSession()
    {
        // If the session info hasn't been set...
        if (!$this->Session->check('User'))
        {
            // Force the user to login
            $this->redirect('/users/login');
            exit();
        }
    }
}
?>
                
现在你拥有了一个可以确保未经登陆的用户不能访问系统受限内容的函数了,你可以在任意级别来控制,下面是一些例子:

强制所有action都必须经过认证  
class NotesController extends AppController  
{  
    // Don't want non-authenticated users looking at any of the actions  
    // in this controller? Use a beforeFilter to have Cake run checkSession  
    // before any action logic.  
    function beforeFilter()  
    {  
        $this->checkSession();  
    }  
}  
?>  
在单独的action中要求认证  
class NotesController extends AppController  
{  
    function publicNotes($clientID)  
    {  
        // Public access to this action is okay...  
    }  
 
    function edit($noteId)  
    {  
        // But you only want authenticated users to access this action.  
        $this->checkSession();  
    }  
}  
?>  
         
强制所有action都必须经过认证
class NotesController extends AppController
{
    // Don't want non-authenticated users looking at any of the actions
    // in this controller? Use a beforeFilter to have Cake run checkSession
    // before any action logic.

    function beforeFilter()
    {
        $this->checkSession();
    }
}
?>


在单独的action中要求认证
class NotesController extends AppController
{
    function publicNotes($clientID)
    {
        // Public access to this action is okay...
    }

    function edit($noteId)
    {
        // But you only want authenticated users to access this action.
        $this->checkSession();
    }
}
?>
                
你已经掌握了一些基础知识,可以开始实现自定义或者高级功能。我们建议整合Cake的ACL控制是个不错的开始


推荐阅读
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • Monkey《大话移动——Android与iOS应用测试指南》的预购信息发布啦!
    Monkey《大话移动——Android与iOS应用测试指南》的预购信息已经发布,可以在京东和当当网进行预购。感谢几位大牛给出的书评,并呼吁大家的支持。明天京东的链接也将发布。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • GetWindowLong函数
    今天在看一个代码里头写了GetWindowLong(hwnd,0),我当时就有点费解,靠,上网搜索函数原型说明,死活找不到第 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • Android中高级面试必知必会,积累总结
    本文介绍了Android中高级面试的必知必会内容,并总结了相关经验。文章指出,如今的Android市场对开发人员的要求更高,需要更专业的人才。同时,文章还给出了针对Android岗位的职责和要求,并提供了简历突出的建议。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 禁止程序接收鼠标事件的工具_VNC Viewer for Mac(远程桌面工具)免费版
    VNCViewerforMac是一款运行在Mac平台上的远程桌面工具,vncviewermac版可以帮助您使用Mac的键盘和鼠标来控制远程计算机,操作简 ... [详细]
author-avatar
The-6ixth-Floor乐队
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有