Yii2 - How to implement RBAC Authorization in RESTful API? - api

HI I just discovered Yii framework and I need some guidelines to implement this...
Yii2 RBAC - Official Guide
...in my RESTful app. I know I have to override the method [checkAccess][3]() in my controllers but I can't found any example. My API has token based Beare autentication and sessions are disabled (stateless).

In your controller:
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBearerAuth::className(),
],
];
// add CORS filter
$behaviors['corsFilter'] = [
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
],
];
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options', 'login', 'signup'];
$behaviors['access'] = [
'class' => AccessControl::className(),
'only' => [
'update',
'delete',
'view',
'index',
],
'rules' => [
[
'actions' => [
'update',
'delete',
'view',
'index',
],
'allow' => true,
'roles' => ['#'],
],
],
];
$behaviors['verbFilter'] = [
'class' => VerbFilter::className(),
'actions' => [
'signup' => ['POST'],
'login' => ['POST'],
'update' => ['PUT'],
'delete' => ['DELETE'],
'view' => ['GET'],
'index' => ['GET'],
],
];
return $behaviors;
}

Related

Cakephp 3 Redirect when session expires

I use the AuthComponent and I want when the session expires and the user press a link or refreshes, to redirect him on the login page.
However for some actions I don't want above redirect, even if user is logged out, as they are used as an API by another application also.
For example, I want to allow the 'view' action for logged-out users, but redirect the 'index' action.
My AppController.php is:
$this->loadComponent('Auth', [
'authorize' => [
'Acl.Actions' => ['actionPath' => 'controllers/']
],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
]
],
'loginAction' => [
'plugin' => false,
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Pages',
'action' => 'index',
'plugin' => 'Pages'
],
'logoutRedirect' => [
'plugin' => false,
'controller' => 'Users',
'action' => 'login'
],
]);
If I add below, 'index' is also working if user is logged-out, even though it should be in deny state.
MyController.php
public function beforeFilter(\Cake\Event\Event $event)
{
$this->Auth->allow('view');
The only way I managed to do what I want is to add it in the controller action as:
MyController.php
public function index()
{
if (empty($this->auth_user['username'])) {
return $this->redirect($this->Auth->logout());
}
Is there a better way to do this?

How to implement CakePHP ACL plugin using Authentication plugin

I've been working on a project and the first thing I did was adding the Authentication and Authorization plugins. I did not used AuthComponent at all since its deprecated.
Now I want to add extra logic on the database and installed the ACL Plugin. I haven't managed to find documentation and all the examples on the internet implement the plugin using the old AuthComponent.
What I need is find a way to make for the ACL to use the new Authentication plugin
This is my AppController.php:
public function initialize(): void
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
// Add this line to check authentication result and lock your site
$this->loadComponent('Authentication.Authentication');
$this->loadComponent('Authorization.Authorization');
$this->loadComponent('Acl', [
'className' => 'Acl.Acl'
]);
$this->loadComponent('Auth', [
'authorize' => [
'Acl.Actions' => [
'actionPath' => 'controllers/',
'userModel' => 'Users'
]
],
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email'],
'userModel' => 'Users'
],
],
'loginAction' => [
'plugin' => false,
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'plugin' => null,
'controller' => 'Users',
'action' => 'index'
],
'logoutRedirect' => [
'plugin' => null,
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => [
'controller' => null,
'action' => 'login',
'prefix' => false
],
'authError' => 'You are not authorized to access that location.',
'flash' => [
'element' => 'error'
]
]);
/*
Found on stackoverflow that "These two plugins are not ment to work together, cakephp/acl is strictly ment for use with the deprecated auth component. If you want ACLs for cakephp/authorization, then you need to implement that yourself".
I have no idea how to do that, so Im still listening if anyone has any idea on how to do that or what could be another solution.

CakePHP4 - How to create multiple user login with the Authentication plugin?

There are two types of users in the application I am developing. Users (table users.sql) for frontend users and AdminUsers (table admin_users.sql) for administration.
In CakePHP3, I solved this problem as follows with AuthComponent in AppController:
public function initialize()
{
parent::initialize();
// ...
//user login
if (!empty($this->request->params['prefix']) AND
$this->request->params['prefix'] == 'admin'
) {
$this->setAdminLogin();
}else{
$this->setUserLogin();
$this->Auth->allow();
}
// ...
}
//frontend users
public function setUserLogin()
{
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Users',
'action' => 'edit'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'authError' => false,
'authenticate' => [
'Xety/Cake3CookieAuth.Cookie' => [
'userModel' => 'Users',
'scope' => ['Users.active' => 1],
'fields' => ['username' => 'email','password' => 'password'],
],
'Form' => [
'userModel' => 'Users',
'scope' => ['Users.active' => 1],
'fields' => ['username' => 'email','password' => 'password'],
'passwordHasher' => [
'className' => 'Fallback',
'hashers' => ['Default']
]
],
],
'storage' => ['className' => 'Session', 'key' => 'Auth.User']
]);
}
//admin users
public function setAdminLogin()
{
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginAction' => [
'controller' => 'AdminUsers',
'action' => 'login',
],
'loginRedirect' => [
'controller' => 'AdminHelps',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'AdminUsers',
'action' => 'login'
],
'authError' => false,
'authenticate' => [
'Form' => [
'userModel' => 'AdminUsers',
'scope' => ['AdminUsers.active' => 1],
'fields' => ['username' => 'email','password' => 'password'],
'passwordHasher' => [
'className' => 'Fallback',
'hashers' => ['Default']
]
],
],
'storage' => ['className' => 'Session', 'key' => 'Auth.AdminUser']
]);
}
How can I do the same thing in CakePHP4 version with Authentication plugin? How can I create multiple user login?

in yii2 : why my default language is en

how to change default language from en to another language
$config = [
'on beforeAction' => function ($event)
{
Yii::$app->language = 'fa';
},
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'language' => '/fa',
'components' => [
'jdate' => [
'class' => 'jDate\DateTime'
],
'mycomponent' => [
'class' => 'app\components\MyComponent',
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '******',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'urlManager' => [
'class' => 'codemix\localeurls\UrlManager',
// Disable index.php
'languages' => ['fa', 'en'], // List all supported languages here
'showScriptName' => true,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
// '' => 'site/index/fa',
// '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
// '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
this is my $config in web.php
i want set default to 'fa' in root site !
my site automatic change lang to 'en' in first time in any browser!
i try to change lang with
'on beforeAction' => function ($event)
{
Yii::$app->language = 'fa';
},
but that is dosent correct work!
Remove this ridiculous 'on beforeAction' thing and just set
'language' => 'fa', // NOT '/fa'!
سلام
ویدئو های آقای صیف زاده رو مشاهده کردین؟
لینک زیر آموزش های ویدئویی ایشون هست . در شماره های 17 و 18 و 19
این موضوع رو آموزش دادن.
https://drive.google.com/drive/folders/0B4ZlNlar4Ij6XzJrbVZOejRCcGM

CakePHP 3.2: Prevent authError showing when user is not logged in

Even when user is not logged in and tries to open homepage, after being redirected to login page, authError is displayed.Is there an elegant way to prevent this, without modifying Auth component? This is how I load Auth component(I am using TinyAuth as authorization adapter):
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Home',
'action' => 'index'
],
'authError' => 'You dont have permissions for that action',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'scope' => ['Users.active' => true],
'contain' => ['Roles']
]
],
'authorize' => [
'TinyAuth.Tiny' => [
'roleColumn' => 'role_id',
'rolesTable' => 'Roles',
'multiRole' => true,
'pivotTable' => 'roles_users',
'superAdminRole' => null,
'authorizeByPrefix' => false,
'prefixes' => [],
'allowUser' => false,
'adminPrefix' => null,
'autoClearCache' => true
]
]
]
);
According to CakePHP's documentation you can prevent the error message from being shown by setting authError to false.
Sometimes, you want to display the authorization error only after the
user has already logged-in. You can suppress this message by setting
its value to boolean false.
This should disable the error message:
if (!$this->Auth->user()) {
$this->Auth->config('authError', false);
}