MVC自定义授权属性来验证请求 [英] MVC Custom Authorize Attribute to validate the Request

查看:107
本文介绍了MVC自定义授权属性来验证请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用jQuery UI的这使得使用Ajax请求MVC的电话。

我想验证对USERPROFILE每个请求(持有帐号的自定义类,身份证等)。

任何人都可以请建议是否可以创建自定义授权属性来验证请求和USERPROFILE相同?

然后,我会喜欢做类似如下:

  [AuthorizeUser]
公众的ActionResult GetMyConsumption(字符串使用accountNumber)
{
  .....
  返回查看();
}


解决方案

您可以编写一个自定义的授权属性:

 公共类AuthorizeUserAttribute:AuthorizeAttribute
{
    保护覆盖布尔AuthorizeCore(HttpContextBase的HttpContext)
    {
        VAR isAuthorized = base.AuthorizeCore(HttpContext的);
        如果(!isAuthorized)
        {
            //用户无权=>没有必要继续
            返回false;
        }        //在这个阶段,我们知道该用户被授权= GT;我们可以取
        //用户名
        字符串的用户名= httpContext.User.Identity.Name;        //现在让我们从请求获取帐号
        串账户= httpContext.Request [了accountNumber];        //所有剩下的就是核实,如果当前用户是所有者
        //帐户
        返回IsAccountOwner(用户名,账号);
    }    私人布尔IsAccountOwner(用户名字符串,字符串帐户)
    {
        // TODO:查询后台进行必要的核查
        抛出新NotImplementedException();
    }
}

I've a UI with Jquery which makes a call to MVC using Ajax request.

I would like to validate each request against the userProfile (custom class which holds account number, ID etc).

Could anyone please suggest whether it is possible to create custom Authorize Attribute to validate that both request and userprofile are same?

I would then like to do something like below:

[AuthorizeUser]
public ActionResult GetMyConsumption(string accountNumber)
{
  .....
  return View();
}

解决方案

You could write a custom Authorize attribute:

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            // The user is not authorized => no need to continue
            return false;
        }

        // At this stage we know that the user is authorized => we can fetch
        // the username
        string username = httpContext.User.Identity.Name;

        // Now let's fetch the account number from the request
        string account = httpContext.Request["accountNumber"];

        // All that's left is to verify if the current user is the owner 
        // of the account
        return IsAccountOwner(username, account);
    }

    private bool IsAccountOwner(string username, string account)
    {
        // TODO: query the backend to perform the necessary verifications
        throw new NotImplementedException();
    }
}

这篇关于MVC自定义授权属性来验证请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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