【问题标题】:MVC Custom Authorize Attribute to validate the RequestMVC 自定义授权属性来验证请求
【发布时间】:2013-05-08 04:11:52
【问题描述】:

我有一个带有 Jquery 的 UI,它使用 Ajax 请求调用 MVC。

我想根据 userProfile(包含帐号、ID 等的自定义类)验证每个请求。

谁能建议是否可以创建自定义授权属性来验证请求和用户配置文件是否相同?

然后我想做如下的事情:

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

【问题讨论】:

  • 如果您愿意从请求表单/查询字符串中解析数据并验证它们,那么这是可能的。您将拥有对自定义授权属性中的 httpContext 的完全访问权限。如果是 POST,则必须假设变量“accountNumber”必须存在于表单中,如果是 GET,则必须存在 QueryString。参数绑定(将请求中的数据映射到 Action 中的参数)将发生在授权后的 OnActionExecuting 方法周围。
  • 是的 accountID 将被传递。
  • 查看stackoverflow.com/questions/6860686/…(AuthorizeCore vs OnAuthorize),这里有人正在查看一些请求数据(预算)以确定用户是否被授权:stackoverflow.com/questions/5989100/…跨度>

标签: asp.net-mvc asp.net-mvc-3


【解决方案1】:

你可以写一个自定义的 Authorize 属性:

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

【讨论】:

    猜你喜欢
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    相关资源
    最近更新 更多