Cakephp 3 Redirect when session expires - authentication

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?

Related

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.

Allow everyone to access in Yii2 controller

I have a project where I am implementing an existing Yii project on top. The issue is the new Yii project has its own user login and authentication. I want to allow anyone access by global rights or just remove all of the authentication all together and use my own page authentication.
In my site controller I have modified to:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['?'],
],
// ...
],
],
];
}
I have removed the actionLogin() and actionLogout() from this site controller as well but am still sent to the logon page.
*: any user, including both anonymous and authenticated users.
?: anonymous users.
#: authenticated users.
This is what I have added:
https://github.com/gugoan/economizzer
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::classname(),
'only' => ['index','create','update','delete','view','target','accomplishment','overview','performance'],
'rules' => [
[
'allow' => true,
'roles' => ['*']
],
]
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
There is no role *, you need to use:
'roles' => ['?', '#']

Yii2 RBAC based on permissions

I am designing a system but I need to give the admin user the power to create roles and assign a set of permissions against them.
Currently in the RBAC
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index','view'], // these action are accessible
//only the yourRole1 and yourRole2
'allow' => true,
'roles' => ['yourRole1', 'yourRole2'],
],
[ // all the action are accessible to superadmin, admin and manager
'allow' => true,
'roles' => ['superAdmin', 'admin', 'manager'],
],
],
],
];
}
However what I ideally need is
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index','view'],
'allow' => true,
'permission' => ['canView'],
],
[
'actions' => ['update','delete'], // these action are accessible
'allow' => true,
'permission' => ['canDelete', 'canUpdate'],
],
],
],
];
}
By doing this and creating a set of permissions an admin user can then create roles, assign permissions and assign roles to users.
Does anyone know of a package for yii2 that does this?
The AccessControl Filter you are using already allows you to do that via the "permissions" field.
[
'actions' => ['index','view'],
'allow' => true,
'permissions' => ['canView'],
],
Check the documentation:
http://www.yiiframework.com/doc-2.0/yii-filters-accessrule.html#$permissions-detail

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);
}

Yii2 - How to implement RBAC Authorization in RESTful 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;
}