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
}
Related
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"))
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
I am building an ASP.net MVC 4 application.
In the past I have used the [Authorize] attribute to authorize users according to their role(s).
However, I now need to a more flexible solution where role authorization can be changed by altering the database rather than changing the source code.
Can anyone recommend a suitable way to do this?
I have looked into overriding the OnAuthorize method but apparently this is not recommended due to issues with output caching.
You can do something like this, we have been using this in our application
[AttributeUsageAttribute
(AttributeTargets.Class | AttributeTargets.Struct |
AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
public class RequirePermissionsAttribute : ActionFilterAttribute, IAuthorizationFilter
{
// Use inbuilt methods
//OnAuthorization
//HandleUnauthorizedRequest
//OnCacheAuthorization
}
[RequirePermissions(PermissionItems.ViewThisPage)]
public ActionResult Index()
{
}
Not sure if I understood your requirement correctly, but you could have two levels of roles, with a data model something like:
User -in-> Role -has-> Permission
With m-n relationships between Users and Roles, and between Roles and Permissions.
If you do this, your permissions can be quite fine-grained and stable, while roles can be coarse-grained and flexibly mapped to sets of permissions.
One way to implement this is to simply write a custom RoleProvider that does the join Users-Roles-Permissions and returns the permissions as application roles.
If you do this, you can use the standard Authorize attribute, specifying one of your fine-grained permission names rather than a coarse-grained role name, e.g.:
[Authorize(Permissions.ViewCustomers)]
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.
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.