gpt4 book ai didi

asp.net-mvc - MVC定制授权属性以验证请求

转载 作者:行者123 更新时间:2023-12-04 13:17:13 24 4
gpt4 key购买 nike

我有一个带有Jquery的UI,该UI使用Ajax请求对MVC进行了调用。

我想针对userProfile(保存帐号,ID等的自定义类)验证每个请求。

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

然后,我想做如下的事情:

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

最佳答案

您可以编写自定义的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();
}
}

关于asp.net-mvc - MVC定制授权属性以验证请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10327342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com