20.11.2014 Views

O Guia Definitivo do Yii 1.1

O Guia Definitivo do Yii 1.1

O Guia Definitivo do Yii 1.1

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

specific operations by calling CWebUser::checkAccess; and we can also obtain the unique<br />

identifier and other persistent identity information about the user.<br />

Defining Identity Class<br />

As mentioned above, authentication is about validating the identity of the user. A typical<br />

Web application authentication implementation usually involves using a username and<br />

password combination to verify a user's identity. However, it may include other methods<br />

and different implementations may be required. To accommodate varying authentication<br />

methods, the <strong>Yii</strong> auth framework introduces the identity class.<br />

We define an identity class which contains the actual authentication logic. The identity<br />

class should implement the [IUserIdentity] interface. Different identity classes can be<br />

implemented for different authentication approaches (e.g. OpenID, LDAP, Twitter OAuth,<br />

Facebook Connect). A good start when writing your own implementation is to extend<br />

CUserIdentity which is a base class for the authentication approach using a username and<br />

password.<br />

The main work in defining an identity class is the implementation of the<br />

[IUserIdentity::authenticate] method. This is the method used to encapsulate the main<br />

details of the authentication approach. An identity class may also declare additional<br />

identity information that needs to be persistent during the user session.<br />

An Example<br />

In the following example, we use an identity class to demonstrate using a database<br />

approach to authentication. This is very typical of most Web applications. A user will enter<br />

their username and password into a login form, and then we validate these credentials,<br />

using ActiveRecord, against a user table in the database . There are actually a few things<br />

being demonstrated in this single example:<br />

• The implementation of the authenticate() to use the database to validate credentials.<br />

• Overriding the CUserIdentity::getId() method to return the _id property because the<br />

default implementation returns the username as the ID.<br />

• Using the setState() (CBaseUserIdentity::setState) method to demonstrate storing<br />

other information that can easily be retrieved upon subsequent requests.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!