arrow_back
Back

Yii2 authentication and authorization: Identity and user component

Andrew Dorokhov Andrew Dorokhov schedule 2 min read
menu_book Table of Contents

Firstly, we have to implement authentication.

The user application component manages the user authentication status. It requires us to specify an identity class which contains the actual authentication logic.

return [
    'components' => [
        'user' => [
            'identityClass' => 'app\models\User',
        ],
    ],
];

Authentication itself is handled by yii\web\User, which is exactly this Yii::$app->user component.

Main properties

// The `identity` of the current user. `Null` if the user is not authenticated.
$identity = Yii::$app->user->identity;

// The ID of the current user. `Null` if the user is not authenticated.
$id = Yii::$app->user->id;

// Check whether the current user is a guest (not authenticated).
$isGuest = Yii::$app->user->isGuest;

open_in_new Official documentation .

Authorization

Authorization is the process of verifying that a user has enough permissions to do something. Yii provides two methods: access control filters (ACF) and role-based access control (RBAC).

Access control filters are the simple option and work best in applications with straightforward access rules. As the name suggests, ACF is a filter attached to a controller or a module as a behavior. It checks a set of access rules to make sure the user is allowed to run the requested action. See controllers for the configuration example.

The “Log out” button

The action itself:

public function actionLogout()
{
    Yii::$app->user->logout();

    return $this->goHome();
}

A plain link will not work if the controller restricts the action to POST:

public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::class,
            'actions' => [
                'logout' => ['post'],
            ],
        ],
    ];
}

The solution is the data-method attribute:

<a href="<?= Url::to(['site/logout']) ?>" data-method="post">Log out</a>

yii\web\YiiAsset contains the JavaScript that reads these attributes and performs the POST submission.

Styling the item in a Nav widget

To add a class to the li item:

['label' => 'Home', 'url' => ['site/index'], 'options' => ['class' => 'list-group-item']]

To add a class to the link as well:

[
    'label' => 'Home',
    'url' => ['site/index'],
    'options' => ['class' => 'list-group-item'],
    'linkOptions' => ['class' => 'item-a-class'],
]
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Yii2 database migrations: up, down, and console commands

arrow_forward