ASP. net mvc Framework controller Operation Security

Source: Internet
Author: User
Tags actionlink
ASP. net mvc Framework controller Operation Security

Address: http://gridviewguy.com/Articles/385_ASP_NET_MVC_Framework_Controller_Action_Security.aspx

Translation: Anders Liu

Abstract: ASP. net mvc Framework allows developers to create Web applications in a more flexible way. Using the MVC framework can free you from the headaches of ViewState and Postback, and make applications easy to test. In this article, we will study role-based security of controller operations.

Introduction
Introduction

ASP. net mvc Framework allows the developers to build their web application in a more flexible way. using MVC framework you by passes the headaches of ViewState and Postbacks and also enable your application for testing. in this article we are going to take a look at the Controller Action Role-Based Security.

ASP. net mvc Framework allows developers to create Web applications in a more flexible manner. Using the MVC framework can free you from the headaches of ViewState and Postback, and make applications easy to test. In this article, we will study role-based security of controller operations.

Prerequisite
Prerequisites

If this is your first encounter with ASP. net mvc Framework then I strongly suggest that you check out the introductory article using the link below:

If you are familiar with ASP. net mvc Framework for the first time, I strongly recommend that you use the following link to view its introduction:

Getting Started with the ASP. net mvc Framework

Scenario
Scenario

The scenario is really simple. A list of categories is displayed on the page and when the user clicks on the category it will be deleted. but we need to make sure that the user is authorized to delete the items.

This scenario is very simple. A series of categories are displayed. When you click a category, the corresponding category is deleted. However, we need to ensure that the user has been authorized to delete the items.

Populating the Page with List of Categories
Generate category list page

The first task is to populate the page with a list of categories. Let's see how this can be implemented.

The first task is to generate a page containing the category list. Let's see how this works.

[ControllerAction] <br/> public void List () <br/> {<br/> NorthwindDataContext northwind = new NorthwindDataContext (); <br/> var list = northwind. categories; <br/> RenderView ("Categories", list); <br/>}

The List action is responsible for populating the Categories view with the required data. Let's check out the Categories view.

The List operation is responsible for generating the Categories view for displaying the required data. Let's take a look at the Categories view.

Public partial class Categories: ViewPage <ienumerable >>< br/>{< br/>}</ienumerable>(C => c. delete (category. id), <br/> category. categoryName, new {onclick = "return confirmDelete (" + category. id + ")"}) %> <br/>

The first thing to note is the Categories class inherits from the ViewPage which is of IEnumerable <Category> type. this means that we will have the strong type support for IEnumerable <Category> in the HTML view of the page. now, let's discuss the HTML part of the Categories view.

The first thing to note is that the Categories class inherits from the ViewPage class used for IEnumerable <Category>. This means that in the HTML view of the page, we will get strong support for IEnumerable <Category>. Next, we will discuss the HTML section of the Categories view.

The foreach loop is used to iterate through the categories. the Html. actionLink method is used to create hyperlinks which are directed to fig. the first argument to the Html. actionLink is the Linq expression for the action. the argument c => c. delete (category. id) means that we are attaching the Delete action to all the categories in the ViewData object. the Delete operation will take a single parameter which is categoryId. the next parameter is the text to appear for the hyperlink. the final parameter is the HTML attributes. we are using onclick attribute of the hyperlink which will popup a confirmation box.

The foreach loop is used for iterative classification. The Html. ActionLink method is used to create a hyperlink pointing to a specific controller. The first parameter passed to Html. ActionLink is the corresponding Linq expression for its operation. The c => c. Delete (category. id) parameter indicates the Delete operation for all categories attached to the ViewData object. The Delete operation carries the categoryId parameter. The next parameter is the text to be displayed as a hyperlink. The last parameter is the HTML attribute. A confirmation box is displayed using the onclick attribute of the hyperlink.

The HTML generated for the page might look something like this:

The HTML generated for this page looks like the following:

Beverages Edite <br/> Condiments <br/> Confections <br/> Dairy Products <br/>

Now, looking at the URL's above anyone can easily delete the item by simply copying the URL in the address bar. so, the question is how do we secure the controller actions so only authorized users wocould be able to delete the items.

Now let's take a look at the above URL. Anyone can copy the URL to the address bar to delete the items. So, how can we ensure the security of controller operations so that only authorized users can delete the items in them?

Controller Action Security
Controller Operation Security

ASP. net mvc Framework is still in its development phases and there is still a lot on the wish list. Maybe in few months the framework will provide us the flexibility to configure action based security easily.

ASP. net mvc Framework is still under development, and there are many other things in the target list. Maybe a few months later, this framework will bring us flexible, simple, and operation-based security.

For now let's use another approach to add security to our controller actions. the OnPreAction event is fired before the action is executed and this seems to be an ideal place to authorize the user. you can override the OnPreAction of the controller class but this solution is not scalable since then you will need to override all the controllers for security purposes. A better approach is to introduce a BaseController and override the OnPreAction of the BaseController. all the controllers will derive from the BaseController class instead of the Controller class. and the BaseController will derive from the Controller class.

Currently, we can only add security for controller operations in other ways. The OnPreAction event is triggered before the operation is executed. It seems to be a good place to place user authorization. You can override the OnPreAction method of the controller class, but this solution is not scalable, because for security purposes, you need to override all controllers. A better way is to introduce a BaseController and rewrite the OnPreAction method of BaseController. All controllers are inherited from BaseController instead of the Controller class. The BaseController class is inherited from the Controller class.

Protected override bool OnPreAction (string actionName, System. Reflection. MethodInfo methodInfo) <br/>{< br/> string controllerName = methodInfo. DeclaringType. Name; <br/> if (! IsAuthorized (controllerName, actionName) throw new SecurityException ("not authenticated"); <br/> return base. OnPreAction (actionName, methodInfo); <br/>}

The IsAuthorized custom method is responsible for processing the actual authorization.

The IsAuthorized custom method is used to perform specific authorization.

Private bool IsAuthorized (string controllerName, string actionName) <br/>{< br/> System. web. httpContext context = System. web. httpContext. current; <br/> XDocument xDoc = null; <br/> if (context. cache ["ControllerActionsSecurity"] = null) <br/>{< br/> xDoc = XDocument. load (context. server. mapPath ("~ /ControllerActionsSecurity. xml "); <br/> context. cache. insert ("ControllerActionsSecurity", xDoc); <br/>}< br/> xDoc = (XDocument) context. cache ["ControllerActionsSecurity"]; <br/> IEnumerable <xelement> elements = xDoc. element ("ControllerSecurity "). elements (); <br/> var role = (from e in elements <br/> where (string) e. attribute ("controllerName") = controllerName <br/> & (string) e. attribute ("act IonName ") = actionName <br/> select new {RoleName = e. attribute ("Roles "). value }). singleOrDefault (); <br/> if (role = null) return true; <br/> if (! User. IsInRole (role. RoleName) <br/> return false; <br/> return true; <br/>}</xelement>

Nothing too complicated! The authorization details are stored in an XML file called ControllerActionsSecurity. xml. Here are the contents of the file:

Not complicated at all! The authorization details are stored in an xml file named ControllerActionSecurity. XML. The content of this file is as follows:

<Controllersecurity> </add> </controllersecurity>

  • ControllerName: The name of the controller
  • ActionName: The action of the controller
  • Roles: Authorized roles
  • ControllerName -- controller name
  • ActionName -- controller operation
  • Roles -- authorized role

If you need to add authorization to a different controller then simply make an entry in the XML file with the appropriate controllerName and the actionName.

If you need to add authorization for another controller, you only need to use the appropriate controllerName and actionName to create an entry in this XML file.

Conclusion
Summary

In this article we learned how to authorize the user based on the controller and the action. Hopefully, ASP. NET team will introduce more flexvisible ways to authorize the users based on their actions.

In this article, we learned how to authorize users based on controllers and operations. The ASP. NET team is expected to introduce more flexible methods for user authorization based on operations.

I hope you liked the article happy coding!

I hope you will like this article and enjoy coding!

Download the source code here: http://gridviewguy.com/articledownloads/aspalliancemvc_a.zip.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.