我想检查一个方法的授权,以便当前用户检查他/她是否有权执行此操作。
以下是我所拥有的属性的示例:
[AttributeUsageAttribute(AttributeTargets.Method)]
public class IsAuthorized : Attribute
{
public IsAuthorized(Rights right)
{
bool isAuthorized = false;
if (right == Rights.None)
isAuthorized = true;
else
{
DataAccessLayer.IDAL dal = new DataAccessLayer.DAL();
string userName = Thread.CurrentPrincipal.Identity.Name;
Guid userID = dal.GetUserIDFromUserName(userName);
isAuthorized = dal.HasRight(userID, right.ToString());
}
if (!isAuthorized)
throw new SecurityException("You don't have the rights to perform this action");
}
}
这就是我如何检查用户是否有权访问该方法:
[IsAuthorized(Rights.CreateUserGroup)]
public string Ping()
{
return "The service is online";
}