6

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

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

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

然后我想做如下的事情:

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

1 回答 1

17

您可以编写自定义 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();
    }
}
于 2012-04-26T07:18:54.777 回答