ASP.Net Attribute class
本文关键字:class Attribute Net ASP | 更新日期: 2023-09-27 18:03:37
我想在我的一些类方法中使用一个属性,以确保用户在使用他们调用的方法之前是经过授权的。
我想做一些像
[Authorized()]
public void updateSomething()
{
//TODO:
}
这是我的属性类
class AuthorizedAttribute : Attribute
{
public bool IsAuthorized { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string UserEmail { get; set; }
public AuthorizedAttribute()
{
//This is not the actual implementation
this.IsAuthorized = false;
}
public AuthorizedAttribute(string userEmail, string userPassword)
{
this.UserEmail = userEmail;
this.Password = userPassword;
this.UserName = string.Empty;
BusinessLogic bc = new BusinessLogic();
if (bc.VerifyCredentials(userEmail, userPassword))
{
this.IsAuthorized = true;
}
else
{
this.IsAuthorized = false;
}
}
}
谁能给我指个方向吗?如果有链接就更好了。
谢谢。
我认为您在这里犯的根本错误是将凭据传递给属性。这个属性应该做的是强制一个动作在你调用的函数发生之前发生。
所以请求处理管道必须检查您的属性。也就是说,当函数updatessomething()被调用时,调用程序集应该寻找属性,然后使用当前的HttpContext和User.Identity强制授权发生。
我有使用MVC AuthorizeAttribute的经验,它可以通过派生此属性并向其添加身份验证逻辑来扩展。
public class TestAuthAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
return ResultOfBusinsessLogic;
}
}
可用于任何控制器动作。
我希望这能给你指明正确的方向
您看过内置的AuthorizeAttribute吗?
如果您正在使用表单身份验证/角色,这是已经内置的-检查PrincipalPermission
属性。
[PrincipalPermission(SecurityAction.Demand, Role = "Admin")]