保护在ASP.NET MVC应用程序Ajax调用

问题描述:

我有一个ASP.NET MVC基于应用程序,允许根据用户不同的访问级别。它目前的工作方式是当用户访问一个页面,检查对数据库进行,以确定该用户具有的权利。那么该视图是基于用户的访问级别选择。有些用户看到更多的数据,比别人做的提供给他们更多的功能。每一页还使得各种AJAX调用来显示和更新页面上显示的数据。

I have an ASP.NET MVC based application that allows different levels of access depending on the user. The way it currently works is when a user accesses a page, a check is done against the database to determine the rights that user has. The view is then selected based on the level of access that user has. Some users see more data and have more functionality available to them than do others. Each page also makes a variety of ajax calls to display and update the data displayed on the page.

我的问题是什么,是确保一个特定的Ajax调用源自观点,并没有手动制作返回或更新数据的用户不必访问的最佳方式?我想preFER不要有去到数据库,重新检查每一个Ajax调用时,因为当用户开始加载的页面已经完成时间。

My question is what is the best way to ensure that a particular ajax call originated from the view and was not crafted manually to return or update data the user does not have access to? I would prefer not to have to go to the database to re-check every time an ajax call is made since that was already done when the user initially loaded the page.

检查出的授权属性,你可以把它放在你的控制器内的整个控制器或只是具体的方法上。

Check out the Authorize Attribute, you can put it on an entire controller or just specific methods within your controller.

例如:

[Authorize(Roles = "Administrator")]
public class AdminController : Controller
{
 //your code here
}

public class AdminController : Controller
{
    //Available to everyone
    public ActionResult Index()
    {
        return View();
    }

    //Just available to users in the Administrator role.
    [Authorize(Roles = "Administrator")]
    public ActionResult AdminOnlyIndex()
    {
        return View();
    }
}

另外,你可以写一个自定义的属性授权提供自己的逻辑。

Alternately, you can write a custom Authorize attribute to provide your own logic.

public class CustomAuthorizeAttribute : AuthorizeAttribute 
{           
    protected override bool AuthorizeCore(HttpContextBase httpContext)     
    {
        IPrincipal user = httpContext.User;     
        var validRoles = Roles.Split(',');//Roles will be a parameter when you use the Attribute        
        List<String> userRoles = GetRolesFromDb(user);//This will be a call to your database to get the roles the user is in.

        return validRoles.Intersect(userRoles).Any();
    }
} 

要使用:

 [CustomAuthorizeAttribute(Roles = "Admin,Superuser")] 
 public class AdminController : Controller {

 }