[翻譯] ASP.NET MVC Framework控制器操作安全性

來源:互聯網
上載者:User
[翻譯] ASP.NET MVC Framework控制器操作安全性

原文地址:http://gridviewguy.com/Articles/385_ASP_NET_MVC_Framework_Controller_Action_Security.aspx

翻譯:Anders Liu

摘要:ASP.NET MVC Framework允許開發人員使用更為靈活的方式建立Web應用程式。使用MVC架構可以擺脫令人頭疼的ViewState和Postback,還能讓應用程式便於測試。在這篇文章中,我們將研究控制器操作的角色型安全性。

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允許開發人員使用更為靈活的方式建立Web應用程式。使用MVC架構可以擺脫令人頭疼的ViewState和Postback,還能讓應用程式便於測試。在這篇文章中,我們將研究控制器操作的角色型安全性。

Prerequisite
前提

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:

如果你第一次接觸ASP.NET MVC Framework,我強烈建議你通過下面的連結看一下對它的介紹:

Getting Started with the ASP.NET MVC Framework

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.

這個情境非常簡單。頁面上會顯示一系列分類,當使用者單擊分類時,對應的分類會被刪除。但我們需要確保使用者已被授權,能夠刪除其中的項。

Populating the Page with List of Categories
產生分類列表頁面

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

第一個任務是產生包含分類列表的頁面。我們看看這是如何?的。

[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.

List操作負責產生顯示所需資料的Categories視圖。我們來看一下Categories視圖。

public partial class Categories : ViewPage<ienumerable>><br />{<br />}</ienumerable>(c => c.Delete(category.id),<br /> category.CategoryName, new { onclick = "return confirmDelete(" + category.id + ")" })%><br /> <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.

第一個要注意的是Categories類繼承自用於IEnumerable<Category>的ViewPage類。這意味著在頁面的HTML視圖中,我們將得到對IEnumerable<Category>的強型別支援。接下來,我們討論Categories視圖的HTML部分。

The foreach loop is used to iterate through the categories. The Html.ActionLink method is used to create hyperlinks which are directed to particular controllers. 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.

foreach迴圈用於迭代分類。Html.ActionLink方法用於建立指向特定控制器的超連結。傳給Html.ActionLink的第一個參數是與其操作對應的Linq運算式。參數c => c.Delete(category.id)表示附加到ViewData對象中的所有分類的Delete操作。Delete操作攜帶一個參數categoryId。下一個參數是要顯示成超連結的文字。最後一個參數是HTML 屬性。我們使用超連結的onclick屬性彈出一個確認框。

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

為該頁面產生的HTML看起來象下面這樣:

Beverages Edite<br /><br />Condiments<br /><br />Confections<br /><br />Dairy Products<br /><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 would be able to delete the items.

現在來看一下上面的URL,任何人都可以通過將URL複製到地址欄來刪除其中的項。那麼,我們如何來確保控制器操作的安全性,使得只有已授權的使用者能夠刪除其中的項呢?

Controller Action 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仍處在開發過程中,目標列表中還有很多東西。也許幾個月後這個架構就能為我們帶來靈活的、簡單的、基於操作的安全性。

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.

目前,我們只能通過其他途徑為控制器操作添加安全性。OnPreAction事件會在操作執行前觸發,看起來是個放置使用者授權的好地方。你可以重寫控制器類的OnPreAction方法,但這中解決方案不具延展性,因為出於安全的目的你需要重寫所有控制器。更好的方法是引入一個BaseController並重寫BaseController的OnPreAction方法。所有的控制器都從BaseController繼承,而不再是Controller類。而BaseController類是從Controller類繼承而來的。

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 performing the actual authorization.

IsAuthorized自訂方法負責執行具體的授權。

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("actionName")) == 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:

一點也不複雜!授權的詳細資料存放在一個名為ControllerActionSecurity.xml的XML檔案中。下面是該檔案的內容:

<controllersecurity></add></controllersecurity>

  • controllerName: The name of the controller
  • actionName: The action of the controller
  • Roles: Authorized roles
  • controllerName——控制器的名字
  • actionName——控制器的操作
  • Roles——授權的角色

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.

如果你需要為另一個控制器添加授權,只許用適當的controllerName和actionName在這個XML檔案中建立一個入口即可。

Conclusion
小結

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

在這篇文章中,我們學到了如何基於控制器和操作為使用者授權。希望ASP.NET團隊能夠為基於操作的使用者授權引入更為靈活的方式。

I hope you liked the article happy coding!

希望你能喜歡這篇文章,編碼快樂!

此處下載原始碼:http://gridviewguy.com/ArticleDownloads/AspAllianceMVC_a.zip。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.