Yii RBAC implementation with "rights" extension - yii

I am learning Yii framework and I am creating a sample application also.
In my Application I have three user roles as
Super admin
Author
and Registered Users
I want Authors to do CRUD operations to Articles.
I have extended all my Controllers with yii's RController and added the following code to the filters.
public function filters()
{
return array(
//'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
'rights',
);
}
According to the Yii documentation and as I understand Yii should do automatic filter for me? But Even I log with an Super Admin account it says "Error 403 You are not authorized to perform this action."

Related

Yii2 Rest API user authentication

I am implementing Rest API in yii2. I want to authenticate the user using access token. I have referred various SO answers as follows
Rest api bearer authentication
Rest api bearer auth
Yii2 Rest api authentication
But I m not clear, which authentication method I should use and how I will get user identity.
I have created findIdentityByAccessToken() method in my user identity class as suggested in Yii2 Rest guide .
Below is the behaviour implemented in my controller
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'except' => ['login','forgot-password']
];
return $behaviors;
}
now, how I will get the user identity inside my controller action? As far as i know, access token will be set from the web service inside request header.
Note : I am using Yii2 advanced app
please help me.
Simple answer there's more than one possibility to implement this behavior.
Both HttpBearerAuth and HttpBasicAuth can use the findIdentityByAccessToken() methode when configured correctly. the behavior you should use depends on the way you want users to authenticate themselves.
if you read the documentation of HttpBasisAuth HttpBasicAuth you'll see
The default implementation of HttpBasicAuth uses the loginByAccessToken() method of the user application component and only passes the user name. This implementation is used for authenticating API clients.
loginByAccesToken will invoke the findIdentityByAccesToken methode
You can manipulate this behavior by defining a closure in the auth attribute see auth attribute.
HttpBeareAuth almost does the same. it also implements the loginByAccessToken
So what make the two different from each other? simple the location where the get the data from. where HttpBasicAuth expects that client has set the basic header example header('Authorization: Basic '. base64_encode("user:password")); (PHP has build in support for this see: http://php.net/manual/en/features.http-auth.php)
the HttpBearerAuth expects that the header is defined as the following header('Authorization: Bearer '. $token);
So the solution you should use depends on the way you want users/clients to authenticate themselves. you could also use the QueryParamAuth which gives the users the possibility to authenticate themselves whit a GET param see queryparamauth
And if you want to use a custom header let's say X-API-Token create your own custom class that implements the AuthMethod interface see AuthMethod
Hope this helps

Yii multiple user login in an application

I am a new in Yii framework, I just setup an application and separate front-end & Back-end part. Both User can register / log in properly. Now I want to login different user from front-end site.
Example : Front-End user are tow types
1. Customer
2. Merchant
I want to set different role of theme. How to possible it, Please share with me.
You will probably need to use Yii's RBAC. In order to implement and use RBAC in yii you need to follow the following steps:
1-configure main.php which is located at '/path/to/yourApp/protected/config/main.php'
'authManager'=>array(
'class'=>'CDbAuthManager',
'connectionID'=>'db', //your database config name
),
2-import yii's rbac database scheme into your database. You can find it under /path/to/yii/framework/web/auth/ directory
3-add your operations. Operations such as 'VIEW_POST' or 'EDIT_POST':
$auth=Yii::app()->authManager;
$auth->createOperation('VIEW_POST','view a post');
$auth->createOperation('EDIT_POST','edit a post');
4-create your roles. For example in your case you will have two roles. First Customer and second Merchant.
$role=$auth->createRole('CUSTOMER');
5- Assign operations to your roles:
$role->addChild('VIEW_POST');
6- All done! You can restrict the access like below:
if(Yii::app()->user->checkAccess('VIEW_POST'))
{
//user has access to view a post
}else{
//logged in user has no access to view a post
}
You can also check access with role like below:
if(Yii::app()->user->checkAccess('CUSTOMER')) {}
In order to assign a role to a user use the assign method:
$auth->assign('CUSTOMER','USERNAME | USER ID'); //user will hold the CUSTOMER ROLE
It might also be noted that, I assumed that you have implemented your authentication class. You can find more about Yii's RBAC and authentication in the following link which is Yii's official document:
Yii Authentication and Authorization

How to restrict access some part of module in ZendFramework 2 (i.e. only administrator can do some actions)

so!
I have a question: how to allow access some part of module only for adminisitrator, for example.
For example, I have module album. It has controllers index, delete, add, edit, full. I want full and index controller be available for all roles, but edit, delete and add action only for administrators.
What module I have to use to do that? I found Zend\Authentification.
Table is: username, password, role.
How to authentificate user?:
// do the authentication
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
// success: store database row to auth's storage
// system. (Not the password though!)
$data = $authAdapter->getResultRowObject(null, 'password');
$auth->getStorage()->write($data);
$this->_redirect('/');
} else {
// failure: clear database row from session
$this->view->message = 'Login failed.';
}
After that I will get access to user data, for example, by:
Zend_Auth::getInstance()->getIdentity()->username;
So, in action, in which I want to restrict access I just need to use:
if(Zend_Auth::getInstance()->getIdentity()->role == admin) {
redirect("auth/login");
}
Right?
The questions:
Is my suggestion about how to check user role in each contoller correct?
Do I understand correctly how to work with Zend\Authentification and restrict access to some actions? So in future I will just use same for each action, right?
Additional question: Does Aclmodule uses for managing permissions? So Acl is needed to help Zend_Auth with permissions, right?
To be able to do this you have to build or implement an ACL (Access Control List). You can also use a third party solution in combination with the earlier mentioned Zend_Auth (or any other authentication module). You can read more on Zend ACL here: Zend ACL introduction
You could for example also take a look at BjyAuthorize. This ACL module provides a complete authorization solution for your application but depends on ZfcUser for user authentication and registration. It might be a good way to get started.
If you are done building or implementing BjyAuthorize you can easily tie your access permission checking to your routes (but there are many other ways). You can see how this works here on the BjyAuthorize GitHub page
These modules will teach you a lot about how authentication and authorization can be build into your Zend Framework 2 application.

How can we create account users under super admin

Can any one explain me how to create User Accounts under super admin with accesses and restrictions in ASP.Net MVC4.
You can have a look at this example in the asp.net website, which shows how to implement Membership and Authentication in MVC3 but this applies to MVC4 too.
You first need to setup your database for Membership
Create a SQL Database and call it what you want. If your application already uses one, you can use it for Membership too.
Assign and user and password to the Database.
Run the ASP.Net SQL Server Setup Wizard located in your .NET
Framework directory. The wizard is called aspnet_regsql.exe.
You can find more information about this process in this msdn article.
Once you have setup Membership, you would be able to designate Actions or Controllers that only SuperAdmins will have access to.
[Authorize(Roles = "Superadmin")]
public class SomeController : Controller
{
// Controller code here
}

How to Authenticate users differently in service stack based on service routes?

I am using servicestack.
I want to authenticate users differently based on the route in the API.
For example:
If the user is accessing a company route: /api/company (POST) (update to company data) I want to use the master keys stored in super admin account (for example).
But if the user is accessing some trivial data say employee departments, then the authentication of that employee, Route: /api/employees/74274762764/departments (GET)
So how do I do this if I am using Credentials Authentication (inheriting and implementing).
Do I detect the paths and write logic? That will be very brittle.
Theoretically I want to specify attribute on services and provide the authentication needed. So something like:
[CorporateAuthentication] or [UserAuthentication] so the authentication logic can figure out where to validate the user.
Please help.
Thanks
Amit
Normally when you have resources with different levels of accessibility, you don't actually want to Authenticate differently, instead you want the resources protected by varying roles or permissions that are attached on Authenticated users.
There's an example of how to use ServiceStack's Authentication and authorization wiki page:
[Authenticate]
//All HTTP (GET, POST...) methods need "CanAccess"
[RequiredRole("Admin")]
[RequiredPermission("CanAccess")]
[RequiredPermission(ApplyTo.Put | ApplyTo.Post, "CanAdd")]
[RequiredPermission(ApplyTo.Delete, "AdminRights", "CanDelete")]
public class Secured
{
public bool Test { get; set; }
}
This earlier StackOverflow Answer goes into detail of how Roles and Permissions work in ServiceStack.