MVC User Multi-Level Hierarchy and Dynamic Role Assignment - asp.net-mvc

I am new to MVC, but I have a good experience in C# Winforms, Database Designing and normalization.
I want to define a User and his roles dynamically, using MVC.
Detailed Description
There is an Organization with the Head Of Department(HOD).
There are several branch offices and each office have a Branch Head Officer Working under HOD.
Each Branch Officer has a power to Assign Different Accessibility to his employees. For Eg: A Cashier can also have an access to Generate Bills.
My Problems are:
HOD(Admin) Will Create A Branch Officer(BO).HOD Will Have Access To all the defined Actions in All the controller.
How BO Can create a User that can have access only to the "Controllers's Actions" defined by the BO , and What If the Second Level User Want to create another third level user
BO and his descendants will have access only to their Branch Office. They cannot see Any details of another Branch, but HOD can view any detail of any Branch. (I want this Authorization at Server Side to avoid Cross Site Scripts)
Please guide Me, How Can I Implement This Model of Multi Access Level And Dynamic Role Management?
I have searched a lot but Couldn't found anything that can help me. BTW This Project is Employee Management System that includes Payroll, Leave Management, Employee Service Book etc.
Thanks in advance.

Just for guidance not to be take as a 100% solution.
If you are using MVC 5 you can use ASP.NET Identity Core
There are two common authorization approaches that are based on Role and Claim.
This is role based authentication. So basically you create roles as per your requirement, then you assign those roles to users. So the user immediately gets all the access rights defined for that role.
In your database:
You will have a list of users in AspNetUsers table
List of Roles in AspNetRoles table --> Admin, Branch Manager, Manager etc
Then finally decorate your controller or action with [Authorize(Roles="Admin, etc")]
[Authorize(Roles = "Admin")]
public ActionResult TestMethod()
{
ViewBag.Message = "This View is designed for the Admin's";
return View();
}
Or Whole Controller
[Authorize(Roles = "Admin")]
public class TestController
{
}
So once those are in place you will have a create an action where the admin can assign roles to others. Branch Officer can assign roles to employees.
Useful link: http://www.dotnetcurry.com/aspnet-mvc/1102/aspnet-mvc-role-based-security
http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity

Related

ASP.Net MVC: How to associate a role with action from my custom UI

often we attach role with action like below way
[Authorize(Roles = "Admin, SuperUser")]
[Authorize(Users="Jacquo, Steve", Roles="Admin, SuperUser")]
Users : Comma-separated list of usernames that are allowed to access the action method.
Roles : Comma-separated list of role names. To Access the action method, users must be in at least one of these roles.
[Authorize(Roles = "Producer")]
[Authorize(Roles = "Admin")]
public ActionResult Details(int id) {
// Only available to users who are Producers AND Editors
}
now see authorize and role name is hard coded with action method. suppose action Details is associated with admin role which is hard coded but how could i attach more role to details action or remove any role from details action at run time. i guess it is not possible because asp.net mvc not providing anything built in.
i search google to see that anyone does it anything such as what i am looking for. unfortunately found no similar write up.
so i need some guidance that how could i develop a UI from where admin can associate role with action instead of hard coding at development time.
so tell me your think how could i associate a role or multiple roles with action from a custom UI.
also tell me how could i check at run time that user has that role when user try to access a specific action.
please discuss in details for designing this part what i am looking for. still it is not clear to you what i am looking for then tell me i will try to explain the same in more details.
thanks
First: in every controller you should create a user object in controller constructor. like this:
public class MyController : Controller
{
ApplicationUser user;
public MyController ()
{
user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
}
Then you could use user object anywhere in your controller methods.
"how could i develop a UI from where admin can associate role": in razor view use :
#if (User.IsInRole("Admin"))
{}
"how could i associate a role or multiple roles with action from a custom UI":
No need to that. When you create user in controller, you have access user all roles in controller methods.
"how could i check at run time that user has that role":
Use
if(user.IsInRole("Admin"))

desing pattern idea for role management

I develop a web project. I use Asp.Net MVC, Entity Framework. I will have roles for users in admin panel. Usrs makes processes according to their roles. I want to use design patterns for this projects. Which type of a pattern do I use for this role authorisation? Any idea?
Thanks in advance.
Easiest way to implement role management is using ASP.NET membership provider.
You then have two ways of protecting actions based on roles.
If you want to ensure that only certain roles can execute an action method, you would use the Authorize attribute and define the list of allowed roles:
[Authorize(Roles = "Admin, Manager")]
public ActionResult AdministratorsOnly()
{
return View();
}
If you need to hide functionality on the views, you can use the User.IsInRole() method to check if the currently logged in user has that role:
if(User.IsInRole("Admin"))
{
Delete account
}

2 sets of Custom Membership in ASP .Net MVC

I can setup custom membership easily enough, but what if I need two sets i.e. admin for control panel and registered for logged on customers. This would mean two seperate tables to get users from. My question is how can I integrate the two to control through 1 custom membership and how can I authenticate on the controller for the 2?
You wouldn't separate users this way, you'd implement a custom role provider and allocate these roles to the user. So say you have created two roles admin and user you'd set an attribute to your controller like so:
Admin page controller
[Authorize(Roles = "Admin")]
public ActionResult AdminAction() { }
User page controller
[Authorize(Roles = "User")]
public ActionResult UserAction() { }
If you wanted your administrators to view all logged in user pages, you'd simply just assign the user role to your administrators.

Custom membership or not

I am creating website (football, soccer) in ASP.NET MVC3 and I want have users (with additional information then user in default membership, these are ordinary visitors) and players which I think it is best thet they would inherit users and have some addional iformation as dress number, ... Players also could post articles, users can just comment articles. What is best way to do this? Should I use default membership provider or should I make my own or use some 3rd party solutions? And can you post some articles and tutorials for changing original provider or article for making own provider for asp.net MVC3? Or is it same as MVC2?
It is very easy to create your own Membership Provider. Just create class derived from MembershipProvider. And implement members which look into DB, for example (or any other data source).
public class YourMembershipClass: MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
return YourDataLayer.ValidateUser(username, password);
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
return YourDataLayer.GetSpecificUser(providerUserKey, userIsOnline);
}
// Implement the other methods as well
}
Then add your YourMembershipClass to web.config:
<membership defaultProvider="MlgMembership">
<providers>
<clear />
<add name="CustomMembership" type="YourMembershipClass" enablePasswordRetrieval="false" />
</providers>
</membership>
If you are looking to store profile type information e.g. first name, last name, job title etc. against each user then you should be able to use the Profile system built into ASP.NET Membership. If you are looking to store more identity related information then yes you will have to create some sort of custom membership provider. There is a good video on creating a custom provider on the ASP.NET website: http://www.asp.net/general/videos/how-do-i-create-a-custom-membership-provider
Regarding allowing different types of users to perform different actions you can use the Roles system built into ASP.NET Membership. You can tell your action methods to only allow calls from users in certain roles. For example if you had a PostArticle action method and you only wanted players to be able to access it you would have something like this:
[Authorize(Roles="Player")]
public ActionResult PostArtcile(){
return View();
}
The Authorize attribute tells MVC to only allow authenticated users in the "Player" role to call the action method. You'll still need to restrict the availability of a post article link in your front end but there are several ways to do that.
There is a great series of articles by Scott Mitchell which covers all things membership based: https://web.archive.org/web/20211020202857/http://www.4guysfromrolla.com/articles/120705-1.aspx
Have a look at this soccer Club Site asp.net starter kit.
I Advice you to:
Use Membership provider to just deal
with user registration and
authentication. And let it take care of user security stuffs (rest password, validate user ....)
Then use Roles to separate your
users to their roles ("Players,
normalUsers,..").
And NEVER use Profile provider
cause it cost so many traffic you
don't want and instead of you could
make your custom table in DataBase to
store your additional information.
Then you may use EF or any ORM to get
this information whenever you want.
Don't forget to use authorization attributes [Authorize(Roles="Players")]in your Controllers and Actions deppending on the Roles.
I would advise implementing your own membership provider, it means implementing only the bits you need and forms a foundation for all your user management.
The Membership provider is the same for WebForms and MVC, there are quite a few examples on SO and Google.

Routing Business Branches: Granular access control in ASP.NET MVC

How should ASP.NET MVC routes be structured to allow granular role-based access control to business branches?
Every business entity is related to a branch, either by itself or via its parent entities. Is there an elegant way to authorize actions based on user-roles for any number of branches?
1. {branch} in route?
{branch}/{controller}/{action}/{id}
Action:
[Authorize(Roles="Technician")]
public ActionResult BusinessWidgetAction(BusinessObject obj)
{
// Authorize will test if User has Technician role in branch context
// ...
}
2. Retrieve branch from business entity?
{controller}/{action}/{id}
Action:
public ActionResult BusinessWidgetAction(BusinessObject obj)
{
if (!User.HasAccessTo("WidgetAction", obj.Branch))
throw new HttpException(403, "No soup for you!"); // or redirect
// ...
}
3. Or is there a better way?
I ended up using the same codebase on separate applications and databases for each business branch. This means I have to update each individually, but allows forking of features.
I rolled my own [BranchAuthorize(Roles = "Editor, Stock Keeper")] attribute which checks the authenticated user's roles against the controller action's required roles and displays a message detailing the required roles if none are assigned.
Unified branch access control would require a separate authorization service, but would allow for central rights administration.

Resources