User authentication is the first step in protecting a web application, ensuring that only authenticated users can access restricted resources. In Yii, this can be accomplished by creating a filter class that extends yii\base\ActionFilter.
Here's an example of an authentication filter:
namespace app\filters;
use Yii;
use yii\base\ActionFilter;
class AuthFilter extends ActionFilter
{
public function beforeAction($action)
{
$user = Yii::$app->user;
if ($user->isGuest) {
$user->loginRequired();
return false;
}
return parent::beforeAction($action);
}
}
This filter checks if the current user is a guest (unauthenticated). If so, it redirects them to the login page. If the user is logged in, the request continues as normal.
Next, attach the filter to a controller:
namespace app\controllers;
use yii\web\Controller;
use app\filters\AuthFilter;
class SiteController extends Controller
{
public function behaviors()
{
return [
'auth' => [
'class' => AuthFilter::class,
'only' => ['admin'],
],
];
}
public function actionAdmin()
{
return 'Admin Area';
}
}
In this setup, the AuthFilter is only applied to the admin action, ensuring it is accessible only to logged-in users.
Authorization ensures that authenticated users can only perform actions they are permitted to. This can also be handled using a filter in Yii.
Here’s an example of an authorization filter:
namespace app\filters;
use Yii;
use yii\base\ActionFilter;
use yii\web\ForbiddenHttpException;
class AccessControlFilter extends ActionFilter
{
public function beforeAction($action)
{
$user = Yii::$app->user;
if (!$user->can($action->id)) {
throw new ForbiddenHttpException('You are not allowed to perform this action.');
}
return parent::beforeAction($action);
}
}
This filter uses the can() method to verify if the user has permission to perform the current action. If not, it throws a 403 Forbidden exception.
Here’s how to attach it to a controller:
namespace app\controllers;
use yii\web\Controller;
use app\filters\AccessControlFilter;
class SiteController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControlFilter::class,
'only' => ['admin'],
],
];
}
public function actionAdmin()
{
return 'Admin Area';
}
}
By applying this filter to the admin action, only users with the correct permission can access it.
This article demonstrated how to implement both user authentication and authorization in the Yii framework using filters (middleware). By creating custom filter classes and attaching them to specific controller actions, developers can enforce strict access control in a clean and structured way. Filters are a powerful tool in Yii that can significantly enhance the security and reliability of PHP web applications.