MVC自定义授权属性以验证请求。

6

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

我想根据用户资料(自定义类,包含帐号、ID等)验证每个请求。

请问是否可能创建自定义授权属性来验证请求和用户资料是否相同?

然后,我想做以下操作:

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

如果您愿意解析请求表单/查询字符串中的数据并验证它们,那么这是可能的。在自定义授权属性中,您将完全访问httpContext。您必须假设变量“accountNumber”必须存在于POST的表单中或GET的QueryString中。参数绑定(将请求中的数据映射到操作中的参数)将在OnActionExecuting方法周围发生,该方法是post-Authorize。 - Nick Bork
Yep的账号ID将被传递。 - Nil Pun
1
请查看 https://dev59.com/uWw15IYBdhLWcg3wD3Zk(AuthorizeCore vs OnAuthorize),这里有一个人正在查看某些请求数据(预算),以确定用户是否已获授权:https://dev59.com/C1fUa4cB1Zd3GeqPFCev。 - Nick Bork
1个回答

17

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接