Restricting access to controller methods in ASP.NET MVC 3 - asp.net-mvc-3

I have a site with a page that contains some tabs and when selecting one, its content is retrieved from the server using an AJAX call. Every tab is loaded through a different controller. For example, I have a Customer page which contains Products and Clients tabs.
The site has different types of users with different permission levels.
What I want to do is to protect the controllers, and show the content of the tabs only if the logged in user has permission. So if a user without permission enters the url of the controller, it should redirect to the login page. The url is like this:
http://localhost/MyApp/Products/1
where 1 is the database ID of the product.
I can implement these 2 solutions but none of them is optimal:
Use the ChildOnlyAction attribute. I would mark the actions of the Product controller with this attribute and render the tabs from the main view using RenderAction. But it would mean that all the tabs on the page would have to be rendered, which is not optimal because I only want to load the data when the user clicks on the tab.
On every request to the Product controller, I would make a database query using the ID of the record to check if the user has permission to access it. But this means that for every request I would have to run an extra query.
I'm wondering if there is a better approach to this.

Similar to what Romias has suggested. You can combine the Authorize meta-attribute with a custom IAuthorizationFilter filter.
When you implement the Authorize meta-attribute you specify a list of users or roles that should have permission to that action. This lacks the ability to use a database to specify which ID's a user should have access to.
It is this ID-to-User mapping where the IAuthorizationFilter comes in to play. In the filter you can check the current user against the database.
A sample IAuthorizationFilter and its usage can be found on the following page:
http://geekswithblogs.net/brians/archive/2010/07/08/implementing-a-custom-asp.net-mvc-authorization-filter.aspx

Have you tried using Authorize filter to decorate the controllers you want to protect?
[Authorize(Roles = "UserType1")]
You could also extend the Authorize filter to add your own logic.
Here you can see an example of extending Authorize filter: https://stackoverflow.com/a/428266/7720

Related

Access to Auth or Request in Laravel Model

I have a shop-store project. This project starts with basic functionality and grow up on each software life-cycle. Recently tendency to deploy some customization for user and analytics grow. I wanted to add favorite capability to project. The project has guest mode which unauthenticated user can see products.
Each user may choose to add a product to his/her favorites(after Auth). so far so good. I decide to append favorite attribute to products.
Trouble comes when i try to return products from controller as response. If i use Auth middleware unauthenticated users redirected to login. If i use custom code, every API with product should be changed accordingly. If i try to append filed in product model, i don't have access to Auth class nor requestin product model.
What's the way to handle such a situation? I appreciate your help.
UPDATE:
There are many models in my project. Order, OrderProduct, Product, User, Payment, Category, Delivery, ....
I want to have a new table named Bookmark which has two column: user_id and product_id.
Product == One Many == Bookmark
User == One Many == Bookmark
You can use the blade #auth directive to check for user authentication.
Then for templating
{{auth()-> user -> bookmark -> all()}}
This should work if you have established a one to may relationship between user and bookmark in your model.

MVC 5 Role based Permissions (Authorization)

I want to implement Role based authorization in mvc 5, i am using asp.net identity 2.0 for user authentication.
Please suggest how to implement this by using authorize attribute or any other possible way.
I also want to store user rights after login and do not want to fetch again and again from database while authorizing on controller action. (Don't want to use Session).
[![Role Permissions stored in DB][1]][1]
I probably am not understanding the depth of your question, but I see that your Authorize statement is slightly incorrect.
Try [Authorize(Roles="admin")]
It uses Microsoft.AspNetCore.Authorization;
There's also a Policy Based Authorization. [Authorize(Policy = "Seniors")]
I also found an answer here that may be of interest to you, it speaks of customizing Role Permissions:create custom authorize attribute
The trick will be to assign the User a role, then use the 'Authorize' on the action methods or on the page, or even in the view HTML by testing if the user IsInRole like:
#if(User.IsInRole"admin"){ Add HTML Here }
And if you do use 'Roles', remember that you can add multiple roles to the 'Authorize' tag something like [Authorize(Roles="admin, staff, user")] etc.

Display buttons based on the user roles in ASP .NET MVC 5

I have to display the buttons in the view based on the roles, let's say I have roles like admin user and default user wherein admin user will be able to see the delete, modify and add buttons but default user can only search. Currently, when a user logs in I am capturing the userid and sending the userid to the database to get the role of a user and I am storing those roles in session. In the view retrieving the role value using below code
#if (Session["UserRole"].ToString() == "Admin")
{
//show delete,modify and create buttons
}
but in my production, the code will be hosted on multiple servers and request can go to any of the servers.
My question is it a good practice to store the roles in the session, is there any better approach to solve my requirement. If I am going with the session in the production environment where there will be multiple servers will the session approach works?
You can have some performance problems with this solution, so I recommend to get the role in the action method and storage this in a ViewData.
But I think that the best solution is to create a partial view with this and in the method an authorize tag.

Validation in Spring with different Roles

I'm just trying to understand the "Validation" within Spring MVC. I set up a small validation form, which is working just fine. However I got a couple of questions all those Tutorials don't answer
As far as I understood the Validator just gets every form-element altered and checks if it is valid or not. What if I want a user to only be able to alter specific form-elements.
Let's say I have an Admin and a regular User on my webpage, they both are allowed to edit their profiles. The admin however is allowed to alter his username, the regular isn't allowed to do that. They both use the "edit-profile.jsp" and therefore the same Validator. I could just grey out the username field in my regular user's view, but let's assume he's not a total BDU and adds a form-field via debugger of his webbrowser, overriding the actual username input-field. He then alters his username and sends the request to MVC. The validator assumes the username altered came from the original input-field and updates the user's nickname in the db accordingly, since both, the admin and the regular user just use the same Validator and the same "updateAllAltered"-DAO method. The same goes for select option-lists. Let's say the Admin is allowed to set a status of a profile to active AND inactive. The user however is only allowed to set it's own profile to inactive but can't reactivate it by himself. I could do the same as above, just altering the option-panel in the frontend to only show "INACTIVE" in the regular user's dropdown box. But we could repeat the same scenario, where the user just adds a debug form-field containing also the option "ACTIVE". This can get out of hand if e.g. the Admin is allowed to change Roles to "admin, member, moderator", while a user, who's i.e. a moderator within a forum can change roles to "member or moderator". He could just again add another field and plugin "admin" and gain total control of the forum.
How is this handled in Spring?
Basically you have to handle by spring security for your use case, design your application security, you will find basic spring security examples easily.
Example you can block your HTML code in JSP by spring security tags by user roles.
<sec:authorize access="hasAnyRole('ROLE_ADMIN')">
Delete
</sec:authorize>
You can annotate any of your methods by roles to block access.
#Secured({ "ROLE_ADMIN" })

Let Authenticated User view only his/her own profile

In my codeigniter application following is the format of user profile
http://example.com/foo/view_profile/userid
how can I restrict a user to view others profile? that means he cannot browse any other link than his profile.
so user foobar420 can not browse following links for example
http://example.com/foo/view_profile/foobar250
http://example.com/foo/view_profile/
http://example.com/any-this-else
How can I achieve this?
Was going to comment this, but it's sort of an answer. Well an idea on this subject at least.
Instead of having "/view-profile/userId" why not just "/view-profile" and send the user model as an object to the page. Then you can just render the proper information only for the user who is actually logged in to the server. Assuming you have access to the user model in your server side script, this is the preferred method.
And if no user model is present, redirect to the login page.

Resources