Vous êtes sur la page 1sur 9

Getting Started with Zend_Auth Rob Allen's DevNotes

http://akrabat.com/zend-auth-tutorial/[22/11/2012 08:54:53]
Home ZF2 tutorial ZF1 tutorial Talks Archives About
Rob Allen's DevNotes
Developing PHP software in the Real World, by Rob Allen
Get t i ng St ar t ed w i t h Zend_Aut h
This tutorial is intended to show the basics of integrating Zend_Aut h into an
application using a login form. Zend_Aut h is responsible for authentication
which is the process of identifying an individual based on their credentials
(usually a username and password).
It has been tested on version 1.10 of Zend Framework. It may not work on
any version prior to version 1.10.
Zend_Aut h is separated into a core component and a set of adapters. The
adapters contain the actual code for authorising a user again a given system,
such as HTTP, a database, LDAP etc. Once successfully logged in, the
Zend_Aut h core object allows access to the identity which is a set of fields
that contain the information gained at login, such as username. The exact
fields within the identity depend upon the adapter that was used. For instance,
the HTTP adapter will return the username and realm whereas the database
table adapter has access to the entire the entire table row.
In this tutorial, we will look at what needs to be done to log in using
authentication against a database table.
The user s t abl e
The first thing we need is a database table, called users. It doesnt need to be
complicated, so the schema looks like this (in MySQL):
We also need a user that can log in:
This user has a username of 'admin' and a password of 'password'. In order to
improve security, we are using a "salt" value with the password that the user
uses to log in with. This results in an SHA1 key that is not reversible with
http://www.sha1-lookup.com. The actual value of the salt doesn't really matter,
as long as it's random. I've used the SHA1 value of a random number.
Run these statements in a MySQL client such as phpMyAdmin or the standard
MySQL command-line client. (Arguably, you should pick a better username
and password!)
CREATE TABLE I F NOT EXI STS user s (
i d i nt ( 11) NOT NULL AUTO_I NCREMENT,
user name var char ( 50) NOT NULL,
passwor d var char ( 50) NOT NULL,
sal t var char ( 50) NOT NULL,
r ol e var char ( 50) NOT NULL,
dat e_cr eat ed dat et i me NOT NULL,
PRI MARY KEY ( i d)
)
I NSERT I NTO user s ( user name, passwor d, sal t , r ol e,
dat e_cr eat ed)
VALUES ( ' admi n' ,
SHA1( ' passwor dce8d96d579d389e783f 95b3772785783ea1a9854'
' ce8d96d579d389e783f 95b3772785783ea1a9854' ,
' admi ni st r at or ' , NOW( ) ) ;

My Zend Framework Book:
Rob Al l en
Rob is a PHP and Zend
Framework expert based in
Worcester, UK. He is the
Technical Director for Big
Room Internet and the author
of Zend Framework in Action.
He also supports the Back Up
Project and the Con Anti-
Harrassment Project.
Around the web:
Twitter: @akrabat
Flickr: photos
Linked in: profile
Ot her pages
Akra's Diary
Disclosure policy
Dynamic J avaScript Tabs
License for code on this site
Shorter Links WP plugin
Search
Getting Started with Zend_Auth Rob Allen's DevNotes
http://akrabat.com/zend-auth-tutorial/[22/11/2012 08:54:53]
Aut h c ont r ol l er and l ogi n f or m
Obviously, we'll need a Zend Framework project, so let's start off with the zf
command line tool:
I will assume you know how to configure your web server to make a ZF project
work. If not, look at my tutorial.
You also need to configure the database in appl i cat i on. i ni :
(Obviously, you should use your own database credentials and set the
database to the same one as where you created the users table earlier!)
We will implement our login and log out functionality within a separate
controller, Aut hCont r ol l er . Change directory to the zf-auth-tutorial root and
use the zf command line tool to create the controller file and view script:
This creates the Aut hCont r ol l er class in
appl i cat i on/ cont r ol l er s/ Aut hCont r ol l er . php including an
i ndexAct i on and associated view script which we'll use for the logging in
process.
We'll also need a log-in form, so back to the zf command line tool:
This creates our Appl i cat i on_For m_Logi n form in
appl i cat i on/ f or ms/ Logi n. php. We need to add three elements to it:
username text field, password password field and a submit button:
zf cr eat e pr oj ect zf - aut h- t ut or i al
r esour ces. db. adapt er = " Pdo_Mysql "
r esour ces. db. par ams. char set = " ut f 8"
r esour ces. db. par ams. host = " l ocal host "
r esour ces. db. par ams. user name = " r ob"
r esour ces. db. par ams. passwor d = " 123456"
r esour ces. db. par ams. dbname = " zf aut ht ut or i al "
zf cr eat e cont r ol l er Aut h
zf cr eat e f or m Logi n
cl ass Appl i cat i on_For m_Logi n ext ends Zend_For m
{
Getting Started with Zend_Auth Rob Allen's DevNotes
http://akrabat.com/zend-auth-tutorial/[22/11/2012 08:54:53]
We now need to load the form in the controller and render in the view script.
The code required is not dissimilar from the form handling explained in my
Zend Framework tutorial and looks like this:
publ i c f unct i on i ni t ( )
{
$t hi s - >set Name( " l ogi n" ) ;
$t hi s - >set Met hod( ' post ' ) ;

$t hi s - >addEl ement ( ' t ext ' , ' user name' , ar r ay(
' f i l t er s' => ar r ay( ' St r i ngTr i m' , ' St r i ng
) ,
' val i dat or s' => ar r ay(
ar r ay( ' St r i ngLengt h' , f al se, ar r ay( 0,
) ) ,
) ,
' r equi r ed' => t r ue,
' l abel ' => ' User name: ' ,
) ) ;
$t hi s -
>addEl ement ( ' passwor d' , ' passwor d' , ar r ay(
' f i l t er s' => ar r ay( ' St r i ngTr i m' ) ,
' val i dat or s' => ar r ay(
ar r ay( ' St r i ngLengt h' , f al se, ar r ay( 0,
) ) ,
) ,
' r equi r ed' => t r ue,
' l abel ' => ' Passwor d: ' ,
) ) ;
$t hi s - >addEl ement ( ' submi t ' , ' l ogi n' , ar r ay(
' r equi r ed' => f al se,
' i gnor e' => t r ue,
' l abel ' => ' Logi n' ,
) ) ;
}
}
Getting Started with Zend_Auth Rob Allen's DevNotes
http://akrabat.com/zend-auth-tutorial/[22/11/2012 08:54:53]
appl i c at i on/c ont r ol l er s/Aut hCont r ol l er .php
The associated view script is:
appl i c at i on/vi ew s/sc r i pt s/aut h/i ndex .pht ml
With a little bit of CSS, ht t p: / / l ocal host / zf - aut h-
t ut or i al / publ i c/ aut h gives us a login form like this:
Aut hent i c at i ng
In order to authenticate, we need to replace our comment of "/ / do
somet hi ng her e t o l og i n" with some real code! For simplicity's sake,
/ / . . .
publ i c f unct i on i ndexAct i on( )
{
$f or m = new Appl i cat i on_For m_Logi n( ) ;
$r equest = $t hi s- >get Request ( ) ;
i f ( $r equest - >i sPost ( ) ) {
i f ( $f or m- >i sVal i d( $r equest -
>get Post ( ) ) ) {
/ / do somet hi ng her e t o l og i n
}
}
$t hi s - >vi ew- >f or m = $f or m;
}
/ / . . .
<?php $t hi s- >headTi t l e( ' Logi n' ) ; ?>
<h1>Logi n</ h1>
<?php echo $t hi s- >f or m- >set Act i on( $t hi s- >ur l ( ) ) ; ?>
Getting Started with Zend_Auth Rob Allen's DevNotes
http://akrabat.com/zend-auth-tutorial/[22/11/2012 08:54:53]
we're going to put the code required into the Aut hCont r ol l er , though in a
bigger application, you may want to consider using a service layer object.
We'll create a method called _pr ocess( ) to do the work so start by updating
i ndexAct i on( ) in Aut hCont r ol l er . php:
appl i c at i on/c ont r ol l er s/Aut hCont r ol l er .php
As you can see, we have added a call to our protected _pr ocess( ) method
and then if it returns true, we redirect to the home page using the
r edi r ect or action helper.
The _pr ocess( ) method looks like this:
appl i c at i on/c ont r ol l er s/Aut hCont r ol l er .php
/ / . . .
publ i c f unct i on i ndexAct i on( )
{
$f or m = new Appl i cat i on_For m_Logi n( ) ;
$r equest = $t hi s- >get Request ( ) ;
i f ( $r equest - >i sPost ( ) ) {
i f ( $f or m- >i sVal i d( $r equest -
>get Post ( ) ) ) {
i f ( $t hi s- >_pr ocess( $f or m-
>get Val ues( ) ) ) {

/ / We' r e aut hent i cat ed! Redi r ect t o t he home page
$t hi s - >_hel per -
>r edi r ect or ( ' i ndex' , ' i ndex' ) ;
}
}
}
$t hi s - >vi ew- >f or m = $f or m;
}
/ / . . .
/ / . . .
pr ot ect ed f unct i on _pr ocess( $val ues)
{

/ / Get our aut hent i cat i on adapt er and check cr edent i al s
$adapt er = $t hi s- >_get Aut hAdapt er ( ) ;
$adapt er - >set I dent i t y( $val ues[ ' user name' ] ) ;
Getting Started with Zend_Auth Rob Allen's DevNotes
http://akrabat.com/zend-auth-tutorial/[22/11/2012 08:54:53]
This code uses another method _get Aut hAdapt er ( ) to set up the
Zend_Auth_Adapter_DbTable object that will be used to do the actual
authentication. Once we have it, we use the set I dent i t y method to tell it the
username that the user has entered and the set Cr edent i al method to tell it
the password.
Having told the adapter all that it needs, we then grab the Zend_Auth object
using $aut h = Zend_Aut h: : get I nst ance( ) ; which shows that
Zend_Auth is a Singleton. Zend_Aut h's aut hent i cat e method is used to
test if the supplied username and password is correct.
If it is, then we retrieve the data (as a st dCl ass) from the users table for this
user using get Resul t RowObj ect ( ) and then store it to the auth adapter for
use in all subsequent requests.
The code for _get Aut hAdapt er ( ) is:
appl i c at i on/c ont r ol l er s/Aut hCont r ol l er .php
$adapt er - >set Cr edent i al ( $val ues[ ' passwor d' ] ) ;
$aut h = Zend_Aut h: : get I nst ance( ) ;
$r esul t = $aut h- >aut hent i cat e( $adapt er ) ;
i f ( $r esul t - >i sVal i d( ) ) {
$user = $adapt er - >get Resul t RowObj ect ( ) ;
$aut h- >get St or age( ) - >wr i t e( $user ) ;
r et ur n t r ue;
}
r et ur n f al se;
}
/ / . . .
/ / . . .
pr ot ect ed f unct i on _get Aut hAdapt er ( ) {

$dbAdapt er = Zend_Db_Tabl e: : get Def aul t Adapt er
( ) ;
$aut hAdapt er = new Zend_Aut h_Adapt er _DbTabl e( $d
) ;

$aut hAdapt er - >set Tabl eName( ' user s' )
- >set I dent i t yCol umn( ' user name' )
- >set Cr edent i al Col umn( ' passwor d' )
- >set Cr edent i al Tr eat ment ( ' SHA1( CONCAT( ?
, sal t ) ) ' ) ;
Getting Started with Zend_Auth Rob Allen's DevNotes
http://akrabat.com/zend-auth-tutorial/[22/11/2012 08:54:53]
We instantiate a Zend_Aut h_Adapt er _DbTabl e, passing it the default
database adapter from Zend_Db_Tabl e which was helpfully configured for us
by Zend_Appl i cat i on as a result of the appl i cat i on. i ni settings. We
can tell tell it to use the user s table and that the i dent i t y column and
cr edent i al columns are user name and passwor d respectively.
We use set Cr edent i al Tr eat ment to tell the adapter that the password is
stored as an SHA1 and that the value in the sal t field should be
concatenated to the supplied password when authenticating. If you don't want
to use a salt or SHA1 hashing, then removing this line will allow you to use
plain text passwords in your database.
The user can now log in by going to http://localhost/zf-auth-tutorial/auth and
filling in the correct username and password.
Who i s l ogged i n?
Now that the user is logged in, it's not uncommon to display the user's name
and provide a link to log out. We could do this as a view helper like this:
appl i c at i on/vi ew s/hel per s/LoggedI nAs.php


r et ur n $aut hAdapt er ;
}
/ / . . .
cl ass Zend_Vi ew_Hel per _LoggedI nAs ext ends
Zend_Vi ew_Hel per _Abst r act
{
publ i c f unct i on l oggedI nAs ( )
{
$aut h = Zend_Aut h: : get I nst ance( ) ;
i f ( $aut h- >hasI dent i t y( ) ) {
$user name = $aut h- >get I dent i t y( ) -
>user name;
$l ogout Ur l = $t hi s- >vi ew-
>ur l ( ar r ay( ' cont r ol l er ' =>' aut h' ,
' act i on' =>' l ogout ' ) , nul l , t r ue) ;
r et ur n ' Wel come ' . $user name . ' . <a hr e
;
}
$r equest = Zend_Cont r ol l er _Fr ont : : get I nst ance
( ) - >get Request ( ) ;
$cont r ol l er = $r equest - >get Cont r ol l er Name( ) ;
Getting Started with Zend_Auth Rob Allen's DevNotes
http://akrabat.com/zend-auth-tutorial/[22/11/2012 08:54:53]
This code is fairly simple. The important thing is that we retrieve the
Zend_Aut h object and the test if a user is logged in using hasI dent i t y( ) .
If the user is logged in, then we use get I dent i t y( ) to retrieve the data that
we loaded earlier - in this case the username.
We can then use it in our layout.phtml like this:
Logout
In order to log out, we create another action, l ogout Act i on in our
Aut hCont r ol l er :
This creates the l ogout Act i on method in the Aut hCont r ol l er class. The
code is trivial:
appl i c at i on/c ont r ol l er s/Aut hCont r ol l er .php
$act i on = $r equest - >get Act i onName( ) ;
i f ( $cont r ol l er == ' aut h' && $act i on == ' i ndex'
) {
r et ur n ' ' ;
}
$l ogi nUr l = $t hi s- >vi ew-
>ur l ( ar r ay( ' cont r ol l er ' =>' aut h' , ' act i on' =>' i ndex' ) ) ;
r et ur n ' <a hr ef =" ' . $l ogi nUr l . ' " >Logi n</ a>' ;
}
}
<di v i d=" header " > <di v i d=" l ogged- i n- as" >
<?php echo $t hi s- >l oggedI nAs ( ) ; ?> </ di v>
</ di v>
zf cr eat e act i on l ogout Aut h
/ / . . .
publ i c f unct i on l ogout Act i on( )
{
Zend_Aut h: : get I nst ance( ) - >cl ear I dent i t y( ) ;
$t hi s - >_hel per -
>r edi r ect or ( ' i ndex' ) ; / / back t o l ogi n page
}
/ / . . .
Getting Started with Zend_Auth Rob Allen's DevNotes
http://akrabat.com/zend-auth-tutorial/[22/11/2012 08:54:53]
Copyright 2005-2012 Rob Allen. All rights reserved. Disclosure policy | License for code on this site | Entries RSS | Comments
Like this article? Tweet
The clearIdentity method of Zend_Aut h performs the logout and then we
redirect wherever we want the user to go. In this case, I've chosen the login
page.
That's all you need to know to get started with Zend_Aut h and add
authentication to your application. To decide when your application needs the
user to be logged in, I recommend using the Zend_Acl component.
Code
A working Zend Framework project of this tutorial is available:
Zip file of tutorial (~16KB)
Zip file of tutorial including ZF 1.10.6 (~7MB)
Pr evi ous ver si ons of t hi s t ut or i al
Zend_Auth tutorial for Zend Framework 1.0 only
Changel og
2.0 (26/J ul/2010)
New version for Zend Framework 1.10

Vous aimerez peut-être aussi