如何在asp.net mvc3中创建自定义授权过滤器

时间:2012-04-20 05:57:48

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-2 authorization

我有一个问题我在asp.net mvc3中建立一个网站,
其中我制作了我的几个控制器,所有这些控制器都被授权 因为我不希望未经授权的用户访问该控制器 假设我有一个控制器和2个方法,如下所示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Com.health.Controllers
{
    [Authorize]
    public class MyfirstController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }        
        public ActionResult seeyourDetails(int id)
        {
            return View();
        } 
    }
}

现在假设我们的方法seeyourDetails告诉任何用户他的帐户信息,但问题是,当用户访问此方法时,网址为http://www.exampple.com/Myfirst/seeyourDetails/10,其中10为我向他展示他的详细信息的当前用户ID,但是如果有人登录我的网站并访问此URL并手动添加10或URL中的任何其他号码,我的控制器将向他显示所有详细信息关于那个用户。

注意:我可以在一个地方或两个地方做到这一点,但我需要一些解决方案,我在一个地方实施,它影响我的整个应用程序。谢谢

4 个答案:

答案 0 :(得分:2)

我看到的唯一方法是检查查询字符串中的用户ID是否与登录的用户ID相同。这更像是一个修补程序解决方案,正确的方法是更改​​应用程序的工作方式。像这样的东西,你仍然需要修改一下。

[AttributeUsage(AttributeTargets.Method|AttributeTargets.Class, AllowMultiple = false)]
public class  MyAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        var ctx = filterContext.HttpContext;
        var name = ctx.User.Identity.Name;

        //get user id from db where username= name   

        var urlId = Int32.Parse(ctx.Request.Params["id"]);
        if (userId!=urlId)
            filterContext.Result = new HttpUnauthorizedResult();
    }
}

答案 1 :(得分:2)

首先Authorize非常强大且精细。您可以在类级别和方法级别使用它。您还可以设置哪些角色可以访问它。

[Authorize]
public class MyFirstController : Controller

您基本上是在说任何已经过身份验证的用户,您也可以使用

[Authorize(Roles="Administrator")]
public class MyFirstController : Controller

给你一个更好的控制。在这里,您只说允许管理员角色的用户访问这些内容。 现在对于SeeYourDetails操作,您不应该真正发送用户ID。如果用户当前已登录,您可以访问他/她的详细信息:

var current = Membership.GetUser();

所以你所有的代码看起来都像这样:

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Collections.Generic;


namespace TestArea.Controllers
{
    [Authorize]
    public class MyFirstController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult SeeYourDetails() 
        {
            //get the currently logged in user
            var current = Membership.GetUser();
            //you can always do something else here
            return View(current);
        }


    }

} 有关授权属性http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx

的更多信息

最后,但并非最不重要。如果你要用C#编程,你应该尊重它的符号:-) 希望这有帮助

答案 2 :(得分:0)

您不必从querystring参数获取用户ID。您必须设置为经过身份验证的用户信息的会话。当您需要知道经过身份验证的用户时,从会话中获取

答案 3 :(得分:0)

您要说的是数据授权,用户登录网站后只能看到他的详细信息。

您可以在授权过滤器中创建@MikeSW所述的自定义授权过滤器,检查登录用户的id是否与查询字符串中传递的id相同,并且您必须在会话中存储用户ID。

由于它是一个过滤器,您可以在操作级别或控制器级别或全局级别应用。