ASP.NET MVC: Restricting access using url

自作多情 提交于 2019-12-01 23:57:59

问题


The URL for the administration section of my website always starts with Admin/. Is it possible in ASP.NET MVC to restrict access to users by using this part of the URL?

Obviously I would keep the [Authorize(Roles = "Administrator")] on appropriate controllers and actions but I wonder if it would be quicker for the application if it can just look at the URL instead of stepping into code.


回答1:


Found the answer in Steven Sanderson's book, Pro ASP.NET MVC Framework.

Put the following code in your web.config file.

<location path ="Admin">
  <system.web>
    <authorization>
      <deny users="?"/>
      <allow roles="Administrator"/>
      <deny users="*"/>
    </authorization>
  </system.web>
</location>

This means for any URL matching ~/Admin/*, the application will deny access to unauthenticated visitors or any other visitors other than those with the role 'Administrator'.




回答2:


That will work but you then tie the authorisation to your current Routing model. The beauty of authorising the Actions is that it abstracts the functionality (which is, actually, what you want to control) from the url structure that you are currently using.

It also means that you can Unit Test this functionality.




回答3:


You can create a BaseAdminController, having all of your Admin Controllers extend this:

[Authorize(Roles = "Administrator")]
public class BaseAdminController : Controller {
}

Now, if you want it by URL, you did it correct already, but if you are just saving yourself from making sure it's on everything, above is the way. Then, you're tests can just make sure that all controllers in the Admin namespace extend this controller.



来源:https://stackoverflow.com/questions/1370315/asp-net-mvc-restricting-access-using-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!