User permissions on certain views based on roles - asp.net

I am using ASP.NET MVC 3. Please excuse my terminology. We assign roles to certain people at work, then we use Windows authentication to determine what roles a user has. Lets say the roles are RoleA, RoleB and RoleC. So now I get a list of roles for a user. Lets says that UserA belongs to RoleA and RoleB. Some of my views need to be authenticated as not everyone can view certain views. Lets say that ViewA can only be viewed by users that belong to roles RoleA and RoleB. How would I do this? What would I need to look into? When a user that does not belong to these roles tries to access the views then he/she should be redirected to an error page.
Also, I need some sort of helper method to check these roles as well to be used in my views to hide/display certain controls. Where is the best place to use this?
Any sample code / articles would be appreciated.

[Authorize(Roles = "RoleA,RoleB")]
public ActionResult Foo()
{
return View();
}
And if you want to check roles in the view:
#if (User.IsInRole("RoleA"))
{
<div>This will be visible only to users in RoleA</div>
}

Related

How to create secured page that limits access to users with the correct permissions?

For a Drupal 7 site, I need to create a secured page with a list (view) of documents(.pdf's). There will be one page with a list of documents (a view of pdf's). To get to that page and be able to download any of the .pdf's, the user must be logged in with their own unique username/password. So what I believe needs to be done is the following.
Set up a page with a view of the documents (can do).
Make sure the docs (pdf's) can't be viewed with a direct URL (I think private file)
Prevent access to the page by non-logged in users. (no idea. help!)
Create a menu item for the page that only displays when the user is logged in. (no idea. help!)
Define permissions for accessing the page and add the permissions to specific roles. (I think I can do)
Can anyone provide info on how to do this? Is there a module for this functionality?
thank you,
You can use content_access module to do this. You will be able to restrict access to any content (you list page) by role.
If you create a link to this page in the main/secondary nav (for example) then this link should only appear to a user that has the appropriate permissions (as defined in the role).
LF
create some permissions and assign that to particular user then in your hook_meny you can use user_acccess function to check that whether the logged in user has that permisiion or not and according to that return true or false.
if(user_access(YOUR_PERMISSION_HERE)) {
return TRUE;
}
else {
return FALSE
}
You can also write your sql query inside that. You can put this code in your function and call that function in your access callback for that particular form menu definition

User restrictions on views based on customer user properties

I'm using ASP.NET MVC 3.
I would like to create an action filter to determine if a user can access a view. I have a User class with properties like IsAdministrator, IsTrusteeUser and IsAuditUser. How would I create an action filter to block certain users if the don't belong in some of these roles?
And aslo how would I use this in my views to hide/display certain controls? I would appreciated some code :)
Why re-invent the wheel?
Put the [Authorize] action filter on the action/controller, specifying the role required:
[Authorize(Roles = "Administrator")]
public ActionResult SomeAdminPage() { // }
Either that, or you could implement your own custom authorization filter by implementing IAuthorizationFilter.
You can implement IActionFilter interface for writing such an attribute extension for Users access permissions checking, a little about coding you can find on
here
To hide/display certain controls on UI, it is not the work of ActionFilters, rather you should either make separate views for each user and redirect him accordingly or do some
If/else
to acheive this.

asp.net membership - approval from admin

I am using the asp.net mvc sample app and have expanded it a bit. I use the asp.net membership for login and registration for users.
I now want to change it so when people register, instead of instantly being able to login, it goes to some state where an administrator has to approve it. Once this approval happens, then they can log in.
Is there anything built into asp.net membership stuff that will help me to do this or do I have to code it up from scratch using my own implementation?
I have a few ideas and I don't think this is rocket science but I don't want to reinvent the wheel as I want to ship this as soon as possible.
The MembershipUser class has an IsApproved property. You may set it to false when creating a new user and then set it to true when the admin approves the user.
You have to call Membershi.UpdateUser(user) method after setting the property.
Here's some code to build a collection of un-approved users that can be used as the datasource of a data control like a GridView, DataList, or Repeater:
MembershipUserCollection users = Membership.GetAllUsers();
MembershipUserCollection unapprovedUsers = new MembershipUserCollection();
foreach (MembershipUser u in users)
{
if (!u.IsApproved)
unapprovedUsers.Add(u);
}
The MembershipUser class has an IsApproved property, and during user creation you can use one of the overloads on the Membership.CreateUser function which allows that flag to be set. Unfortunately there's no easy way to say "Show me all users who are not yet validated".

Defining Views Based On Selection

Well the title isn't very descriptive but I'm not exactly sure how to explain but here goes!
I have a web application (can use either MVC or standard web forms) which a user signs in to. If the user has signed up for more than one product they will have the option to switch between them. For the sakes of this example lets say User1 signs in and has access to Product1, Product2 and Product3.
Now, each product will be very different and offer different functionally. What I want is the main view to be focused around the product they have selected and not redirected to a sub domain.
What I don't want to have to do is get them to go to www.mysite.com/product1 or www.mysite.com/product2 but simply www.mysite.com regardless of the product they have selected and have the site render the views etc for that product.
Wow does any of that make any sense? I was thinking mabe the use of sessions or something and URL rewriting? Are there any sample apps out there that make use of the same kind of functionallity that I could take a look at?
Thanks for any help I appreciate it!
To keep the product ID out of the URL, you can post your product selection page to the server with a hidden control that contains the desired product ID.
<input type="hidden">
Once you have the value in your codebehind or controller method, you can then set a Session variable with the product id to maintain persistence, and then perform a redirect to the appropriate product page.
This will work in both ASP.NET and ASP.NET MVC.
If you could elaborate more, that would be helpful.
Here is my shot at the answer from what I understood:
What you could do is redirect to the user to a specific page after they login.
public ActionResult Login()
{
//Login Logic
if(UserLoggedIn)
{
User MembershipUser = GetUser(User.Identity.Name);
if(MembershipUser.HasProduct1)
return View("Product1");
else if(MembershipUser.HasProduct2)
return View("Product2");
else if(MembershipUser.HasProduct3)
return View("Product3");
}
}
It would be just a simple redirect to a specific view depending on the user's product.
If you could elaborate more, I could give a better answer.
I think I am going to go with a custom ViewEngine in ASP.NET MVC. I can render different views depending on the product chosen that way. Thanks to everyone for their suggestions.

How can I create a view that has different displays according to the role the user is in?

I want to create a view that has different displays according to the role the user is in.
Should I create a different view for different roles or should I check the roles on the Veiw page itself rather than in the actions?
How would I check the role on the view page?
Or should i use check the roles on the
Veiw page its self rather than on
actions, if so can someone plz show me
how do check that on view page
You need to do both. Check roles on actions as a security measure and check roles on views to enable/disable specific controls.
Within your view page the long form of checking a role is
HttpContext.Current.User.IsInRole("Administrator")
many developers will create page helper methods so you can end up with something more concise for your application like
public static bool IsAdmin(this ViewUserControl pg)
{
return pg.Page.User.IsInRole("Administrator")
}
then in your view you can just use this.IsAdmin()
To keep your view clutter down look into using partial views
<% if (IsAdmin())
{
Html.RenderPartial("AdminPanel");
}
else
{
Html.RenderPartial("UserPanel");
}
%>
If the display changes based on the role -- and the change is small -- then I would do the check in the view. If certain views are restricted based on the role, then I would do the check in the controller. If the views are completely different (this would be hard to imagine), then separate views per role may be appropriate.
You may want to abstract out certain role-specific view components into partial views to simplify your view logic -- basically you only have to check to include the partial or not based on the role.
Also, other than to check for "IsAuthenticated", I would move the role checking logic to the controller and pass (as data) to the view information on which elements to include/exclude based on role. This keeps the actual business logic from bleeding into your view.
If you are using MVC the whole point of development is to keep the logic out of the view and in the controller. It seems to me like you'd be better off on a WebForms development track than an MVC track.
All that being said, I do an Admin check on a lot of my pages by using a check like this:
<% if ((bool)ViewData["Admin"]) { %>
<!-- Show admin controls here -->
<% } %>
But if you are attempting to build actual logic into the View then you need to figure out what you can push back to the controller to do the work and have the view be as dumb as possible, acting on flags sent to it.
without researching the exact mechanism asp.net mvc uses for roles i would scream no for putting any of your business logic in the view which is what you are doing if you are checking roles in the view
Yeah that was something that was bothering me as well ... but at the same time it seems ridiculous to load whole different view for such a small change.
btw
how did you set this up in your controller.
Right now, my controller looks something like the code below, which I don't think is correct.
[Authorize(Roles = "Admin, Member")]
public ActionResult RegistrationInformation()
{
return View();
}
I'm not that familiar with ASP.NET MVC (yet) but can't you do some kind of conditional filter in the View? If the Controller passes the role to the View, then you should be able to do a conditional filter and display a certain block of code if the user is an admin. If you want to display a totally separate page, then you'd have a multiple Views, otherwise you can use one and do some conditional.
In Ruby on Rails it would be something like (sorry, I don't know ASP.NET MVC really yet):
<% if #user.admin? # is the user an admin %>
<h3>Admin Tools</h3>
<% end %>
<p>Regular site content</p>
In Rails you would load the extra content from partials; ASP.NET MVC has something similar but I forget what it's called. Maybe look into that?
Sorry I can't be of more help -- like I said I haven't really gotten to play with ASP.NET MVC.
I have base model which from all others models extend. In this model i have loaded the user's roles. Its based on httpcontext.user.isinrole() method. All views are strong typed expecting the base model type.
So i can always check in all views something like Model.CurrentUser.IsInRoles(Role1 | Role2). Not only in views of course, but in hole application.
I like to have full control over this in the view, and I find that:
<% if (User.IsInRole("Super User")) { %>
<h1>Hello world!</h1>
<% } %>
Works for most scenarios. It also allows you to easily do conditional formatting for other roles, e.g "Content Manager", "Registered", etc.
I do like Todd Smith's answer, because you might change the name of the Admin role, and that will require only one change, whereas, if you put the "Super User" or "Administrator" string directly in the view, you will have to change it wherever you've used the value.

Resources