简体   繁体   English

如何在ASP.NET MVC3中创建自定义授权过滤器

[英]how to create custom authorize filter in asp.net mvc3

i have a problem i am building a site in asp.net mvc3 , 我有一个问题,我正在asp.net mvc3中建立一个站点,
in which i made my several controllers all of them are authorized 在其中我使我的几个控制器都被授权
because i don't want that unauthorized user access that controller. 因为我不希望未经授权的用户访问该控制器。
Let suppose i have a controller and 2 methods in it as following 假设我有一个控制器和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();
        } 
    }
}

now let suppose our method seeyourDetails tells any user his account information , but the problem is this that when user access this method at that time the URL is http://www.exampple.com/Myfirst/seeyourDetails/10 , where 10 is current user id by which i show him his details , but what should i do, if a persons login into my site and he access this URL and manually add 10 or any other number in URL my controller will show him all details regarding that user . 现在,假设我们的方法seeyourDetails告诉任何用户他的帐户信息,但是问题在于,当用户当时访问该方法时,URL为http://www.exampple.com/Myfirst/seeyourDetails/10 ,其中10为当前我向他显示他的详细信息的用户ID,但是如果有人登录到我的网站并且他访问此URL并在URL中手动添加10或任何其他数字,我的控制器将向他显示有关该用户的所有详细信息,该怎么办。

Note : I can do this in one place or two places but i need some solution that i implement in one place and it effects in my whole application . 注意:我可以在一处或两处执行此操作,但是我需要在某处执行一些解决方案,并且该解决方案会影响整个应用程序。 Thanks 谢谢

The only way I see is to check if the user id from query string is the same with the user id logged in. This is more of a patching things solution, the proper way is to change how the app works. 我看到的唯一方法是检查查询字符串中的用户ID是否与登录的用户ID相同。这更多是一种修补程序解决方案,正确的方法是更改​​应用程序的工作方式。 Something like this, you still need to modify it a bit. 这样的事情,您仍然需要对其进行一些修改。

[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();
    }
}

first the Authorize is very powerful and granular. 首先, Authorize功能非常强大且精细。 You can use it at class level and at method level. 您可以在类级别和方法级别使用它。 You can also set which Roles have access to to it. 您还可以设置哪些角色可以访问它。

[Authorize]
public class MyFirstController : Controller

You're basically saying any user that has been authenticated, you can also use 基本上,您说的是已通过身份验证的任何用户,您也可以使用

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

Giving you a finer control. 给您更好的控制。 Here you're saying only user in the Administrator role are allowed to access these contents. 在这里,您是说只有管理员角色的用户才能访问这些内容。 Now for the SeeYourDetails Action you shouldn't really be be sending the user ID. 现在,对于SeeYourDetails动作,您实际上不应该发送用户ID。 If the user is currently logged in, you can access his/her details like this: 如果用户当前已登录,则可以按以下方式访问其详细信息:

var current = Membership.GetUser();

So you're all code would look something like this: 因此,您所有的代码都将如下所示:

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);
        }


    }

} More info on the Authorize attribute http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx }有关Authorize属性的详细信息http://msdn.microsoft.com/zh-cn/library/system.web.mvc.authorizeattribute.aspx

last, but not least. 最后但并非最不重要的。 If you gonna program in C# you should respect it's notation :-) Hope this helps 如果您要使用C#编程,则应尊重它的符号:-)希望这会有所帮助

you dont have to get the user id from querystring parameter. 您不必从querystring参数获取用户ID。 You have to set to Session of authenticated user infos. 您必须将会话设置为经过身份验证的用户信息。 And get it from session when you need to know the authenticated user 当您需要了解经过身份验证的用户时,可以从会话中获取它

What you are trying to say is Data Authorization, the user can see only his details after logged into the site. 您要说的是数据授权,用户登录该站点后只能看到其详细信息。

You can create a custom Authorize filter as said by @MikeSW in the authorization filter check if the logged-in user's id is same as the id passed in the query string and for that you have to store the user id in session. 您可以按照@MikeSW在授权过滤器中所述创建自定义的“授权”过滤器,以检查登录用户的ID是否与查询字符串中传递的ID相同,为此您必须将用户ID存储在会话中。

Since it is a filter you can apply at action level or controller level or global level too. 由于它是过滤器,因此您也可以在操作级别或控制器级别或全局级别应用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM