How to implement authentication in Yii?

by hal.littel , in category: PHP Frameworks , 2 years ago

How to implement authentication in Yii?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 2 years ago

@hal.littel 

To implement authentication in Yii, follow these steps:

  1. Create a model to represent your user table and generate the corresponding CRUD operations using Gii.
  2. Add authentication component to your application configuration by adding the following code to the file ‘protected/config/main.php’:


'components' => array( 'user' => array( 'class' => 'CWebUser', 'loginUrl' => array('/user/login'), ), 'authManager' => array( 'class' => 'CDbAuthManager', 'connectionID' => 'db', ), ),

  1. Create database tables for authentication and authorization by running the following command:


yii migrate --migrationPath=application.modules.user.migrations

  1. Implement registration and login actions in your UserController. For example:


public function actionLogin() { $model = new LoginForm;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
if(Yii::app()->user->id)
    $this->redirect('/');

if(isset($_POST['LoginForm']))
{
    $model->attributes = $_POST['LoginForm'];

    if($model->validate() && $model->login())
        $this->redirect(Yii::app()->user->returnUrl);
}

$this->render('login',array('model'=>$model));


}


public function actionLogout() { Yii::app()->user->logout(); $this->redirect(Yii::app()->homeUrl); }

  1. Create RBAC authorization roles and operations in the database by running the following command:


yii rbac/init

  1. Implement authorization checks in your Controller actions. For example:


public function accessRules() { return array( array('allow', 'actions'=>array('update','delete'), 'expression'=>'Yii::app()->user->checkAccess("updateOwnModel", array("model"=>$this->loadModel($_GET["id"])))', ), array('allow', 'controllers'=>array('admin'), 'expression'=>'Yii::app()->user->checkAccess("admin")', ), array('deny', 'users'=>array('*'), ), ); }

  1. Use RBAC authorization in your views to display or hide content based on the user's role and permissions. For example:
1
<?php echo CHtml::link('Update',array('update','id'=>$model->id)); ?>


That's it! You've implemented authentication and authorization in your Yii application using RBAC.