Yii - Uwierzytelnianie
Nazywa się proces weryfikacji tożsamości użytkownika authentication. Zwykle używa nazwy użytkownika i hasła, aby ocenić, czy użytkownik jest tym, za kogo się podaje.
Aby korzystać z platformy uwierzytelniania Yii, musisz -
- Skonfiguruj komponent aplikacji użytkownika.
- Zaimplementuj interfejs yii \ web \ IdentityInterface.
Podstawowy szablon aplikacji zawiera wbudowany system uwierzytelniania. Używa komponentu aplikacji użytkownika, jak pokazano w poniższym kodzie -
<?php
$params = require(__DIR__ . '/params.php'); $config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this
//is required by cookie validation
'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
//other components...
'db' => require(__DIR__ . '/db.php'),
],
'modules' => [
'hello' => [
'class' => 'app\modules\hello\Hello',
],
],
'params' => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for 'dev' environment $config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [ 'class' => 'yii\debug\Module', ]; $config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [ 'class' => 'yii\gii\Module', ]; } return $config;
?>
W powyższej konfiguracji klasa tożsamości dla użytkownika jest skonfigurowana jako app \ models \ User.
Klasa tożsamości musi implementować yii\web\IdentityInterface następującymi metodami -
findIdentity() - Wyszukuje wystąpienie klasy tożsamości przy użyciu określonego identyfikatora użytkownika.
findIdentityByAccessToken() - Szuka wystąpienia klasy tożsamości przy użyciu określonego tokenu dostępu.
getId() - Zwraca identyfikator użytkownika.
getAuthKey() - Zwraca klucz używany do weryfikacji logowania przy użyciu plików cookie.
validateAuthKey() - Implementuje logikę weryfikacji klucza logowania opartego na plikach cookie.
Model użytkownika z podstawowego szablonu aplikacji realizuje wszystkie powyższe funkcje. Dane użytkownika są przechowywane w pliku$users nieruchomość -
<?php
namespace app\models;
class User extends \yii\base\Object implements \yii\web\IdentityInterface {
public $id;
public $username; public $password;
public $authKey; public $accessToken;
private static $users = [ '100' => [ 'id' => '100', 'username' => 'admin', 'password' => 'admin', 'authKey' => 'test100key', 'accessToken' => '100-token', ], '101' => [ 'id' => '101', 'username' => 'demo', 'password' => 'demo', 'authKey' => 'test101key', 'accessToken' => '101-token', ], ]; /** * @inheritdoc */ public static function findIdentity($id) {
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null) {
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user); } } return null; } /** * Finds user by username * * @param string $username
* @return static|null
*/
public static function findByUsername($username) { foreach (self::$users as $user) { if (strcasecmp($user['username'], $username) === 0) { return new static($user);
}
}
return null;
}
/**
* @inheritdoc
*/
public function getId() {
return $this->id; } /** * @inheritdoc */ public function getAuthKey() { return $this->authKey;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey) { return $this->authKey === $authKey; } /** * Validates password * * @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password) { return $this->password === $password;
}
}
?>
Step 1 - Przejdź do adresu URL http://localhost:8080/index.php?r=site/login i zaloguj się do witryny internetowej za pomocą administratora, aby uzyskać login i hasło.
Step 2 - Następnie dodaj nową funkcję o nazwie actionAuth() do SiteController.
public function actionAuth(){
// the current user identity. Null if the user is not authenticated.
$identity = Yii::$app->user->identity; var_dump($identity);
// the ID of the current user. Null if the user not authenticated.
$id = Yii::$app->user->id;
var_dump($id); // whether the current user is a guest (not authenticated) $isGuest = Yii::$app->user->isGuest; var_dump($isGuest);
}
Step 3 - Wpisz adres http://localhost:8080/index.php?r=site/auth w przeglądarce internetowej zobaczysz szczegółowe informacje o admin użytkownik.
Step 4 - Aby się zalogować i zalogować, możesz użyć następującego kodu.
public function actionAuth() {
// whether the current user is a guest (not authenticated)
var_dump(Yii::$app->user->isGuest); // find a user identity with the specified username. // note that you may want to check the password if needed $identity = User::findByUsername("admin");
// logs in the user
Yii::$app->user->login($identity);
// whether the current user is a guest (not authenticated)
var_dump(Yii::$app->user->isGuest); Yii::$app->user->logout();
// whether the current user is a guest (not authenticated)
var_dump(Yii::$app->user->isGuest);
}
Najpierw sprawdzamy, czy użytkownik jest zalogowany. Jeśli wartość zwraca false, następnie logujemy użytkownika za pośrednictwem Yii::$app → user → login() zadzwoń i wyloguj go za pomocą Yii::$app → user → logout() metoda.
Step 5 - Przejdź do adresu URL http://localhost:8080/index.php?r=site/authzobaczysz, co następuje.
Plik yii\web\User klasa podnosi następujące zdarzenia -
EVENT_BEFORE_LOGIN- Podniesione na początku yii \ web \ User :: login ()
EVENT_AFTER_LOGIN - Podniesiono po pomyślnym zalogowaniu
EVENT_BEFORE_LOGOUT- Podniesione na początku yii \ web \ User :: logout ()
EVENT_AFTER_LOGOUT - Podniesiony po udanym wylogowaniu