如何创建自定义授权在asp.net MVC3过滤器 [英] how to create custom authorize filter in asp.net mvc3

查看:221
本文介绍了如何创建自定义授权在asp.net MVC3过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题我建立在asp.net MVC3的站点,结果
在我做了我几个控制器所有的人都认可结果
因为我不希望这样的控制器,未经授权的用户访问。结果
让我们假设我有一个控制器和2个方法是如下

i have a problem i am building a site in 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

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 告诉任何用户自己的帐户信息,但问题是这样的,当用户访问当时这种方法的URL是 http://www.exampple.com/Myfirst/seeyourDetails/10 ,其中 10 是我告诉他他目前的用户ID细节,但我应该怎么做,如果一个人登录到我的网站,他访问该网址,然后手动添加 10 或在网址中的其他一些我的控制器会告诉他所有的细节关于该用户。

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 .

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

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

推荐答案

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

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

这篇关于如何创建自定义授权在asp.net MVC3过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆