发布于 2015-08-01 11:30:56 | 402 次阅读 | 评论: 0 | 来源: 网络整理
Authentication is the process of verifying the identity of a user. It usually uses an identifier (e.g. a username or an email address) and a secret token (e.g. a password or an access token) to judge if the user is the one whom he claims as. Authentication is the basis of the login feature.
Yii provides an authentication framework which wires up various components to support login. To use this framework, you mainly need to do the following work:
The yiiwebUser application component manages the user authentication status. It requires you to specify an yiiwebUser::identityClass which contains the actual authentication logic. In the following application configuration, the yiiwebUser::identityClass for yiiwebUser is configured to be appmodelsUser
whose implementation is explained in the next subsection:
return [
'components' => [
'user' => [
'identityClass' => 'appmodelsUser',
],
],
];
The yiiwebUser::identityClass must implement the yiiwebIdentityInterface which contains the following methods:
If a particular method is not needed, you may implement it with an empty body. For example, if your application is a pure stateless RESTful application, you would only need to implement yiiwebIdentityInterface::findIdentityByAccessToken() and yiiwebIdentityInterface::getId() while leaving all other methods with an empty body.
In the following example, an yiiwebUser::identityClass is implemented as an Active Record class associated with the user
database table.
<?php
use yiidbActiveRecord;
use yiiwebIdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
public static function tableName()
{
return 'user';
}
/**
* Finds an identity by the given ID.
*
* @param string|integer $id the ID to be looked for
* @return IdentityInterface|null the identity object that matches the given ID.
*/
public static function findIdentity($id)
{
return static::findOne($id);
}
/**
* Finds an identity by the given token.
*
* @param string $token the token to be looked for
* @return IdentityInterface|null the identity object that matches the given token.
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
/**
* @return int|string current user ID
*/
public function getId()
{
return $this->id;
}
/**
* @return string current user auth key
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @param string $authKey
* @return boolean if auth key is valid for current user
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
}
As explained previously, you only need to implement getAuthKey()
and validateAuthKey()
if your application uses cookie-based login feature. In this case, you may use the following code to generate an auth key for each user and store it in the user
table:
class User extends ActiveRecord implements IdentityInterface
{
......
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->auth_key = Yii::$app->security->generateRandomString();
}
return true;
}
return false;
}
}
Note: Do not confuse the
User
identity class with yiiwebUser. The former is the class implementing the authentication logic. It is often implemented as an Active Record class associated with some persistent storage for storing the user credential information. The latter is an application component class responsible for managing the user authentication state.
You mainly use yiiwebUser in terms of the user
application component.
You can detect the identity of the current user using the expression Yii::$app->user->identity
. It returns an instance of the yiiwebUser::identityClass representing the currently logged-in user, or null if the current user is not authenticated (meaning a guest). The following code shows how to retrieve other authentication-related information from yiiwebUser:
// the current user identity. Null if the user is not authenticated.
$identity = Yii::$app->user->identity;
// the ID of the current user. Null if the user not authenticated.
$id = Yii::$app->user->id;
// whether the current user is a guest (not authenticated)
$isGuest = Yii::$app->user->isGuest;
To login a user, you may use the following code:
// find a user identity with the specified username.
// note that you may want to check the password if needed
$identity = User::findOne(['username' => $username]);
// logs in the user
Yii::$app->user->login($identity);
The yiiwebUser::login() method sets the identity of the current user to the yiiwebUser. If session is yiiwebUser::enableSession, it will keep the identity in the session so that the user authentication status is maintained throughout the whole session. If cookie-based login (i.e. "remember me" login) is yiiwebUser::enableAutoLogin, it will also save the identity in a cookie so that the user authentication status can be recovered from the cookie as long as the cookie remains valid.
In order to enable cookie-based login, you need to configure yiiwebUser::enableAutoLogin to be true in the application configuration. You also need to provide a duration time parameter when calling the yiiwebUser::login() method.
To logout a user, simply call
Yii::$app->user->logout();
Note that logging out a user is only meaningful when session is enabled. The method will clean up the user authentication status from both memory and session. And by default, it will also destroy all user session data. If you want to keep the session data, you should call Yii::$app->user->logout(false)
, instead.
The yiiwebUser class raises a few events during the login and logout processes.
You may respond to these events to implement features such as login audit, online user statistics. For example, in the handler for yiiwebUser::EVENT_AFTER_LOGIN, you may record the login time and IP address in the user
table.