[英]ASP.Net MVC Custom Authorization for Web API
I have a complex application with lots of Web Api Calls which need permission checks that are within the database. 我有一个复杂的应用程序,其中包含许多Web Api调用,这些调用需要数据库中的权限检查。 An example simple api call I might have is: 我可能有一个简单的api调用示例:
[HttpGet]
public IEnumerable<StudentContact> GetStudentContacts(int id)
{
return db.StudentContacts.AsNoTracking().Where(n => n.StudentId == id && n.Current_Record == true).OrderBy(n => n.RankOrder);
}
And to do a permissions check I have to do the following: 要进行权限检查,我必须执行以下操作:
int staffID = (User as CustomPrincipal).UserId;
int siteId = Functions.GetSiteIdFromCookie();
if (Functions.UserHasAccess(staffID, AccessLevels.access_StudentDetailsUpdate,siteId) == true) return true;
else return false;
What I would like to achieve is to create a custom authorization annotation so that I can have: 我想要实现的是创建一个自定义授权批注,以便可以拥有:
[HttpGet]
[PermissionAuth(AccessLevels.access_StudentDetailsUpdate,AccessLevels.access_StudentDetailsReadOnly)]
public IEnumerable......
And I may need to have an option of and/or ie both are true or one is true. 我可能需要选择一个和/或两个都是正确的或一个是正确的。 Can anyone help? 有人可以帮忙吗?
This is possible by extending the AuthorizeAttribute
and overriding the IsAuthorized
method. 这可以通过扩展AuthorizeAttribute
并覆盖IsAuthorized
方法来实现。 Something like the following is what you need. 您需要以下内容。
public class PermissionAuthAttribute : AuthorizeAttribute
{
private readonly List<string> _accessLevels;
public PermissionAuth(params string[] accessLevels)
{
_accessLevels = accessLevels.ToList();
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (!base.IsAuthorized(actionContext))
{
return false;
}
int staffID = (User as CustomPrincipal).UserId;
int siteId = Functions.GetSiteIdFromCookie();
if (Functions.UserHasAccess(staffID, AccessLevels.access_StudentDetailsUpdate,siteId) == true) {
return true;
}
else {
return false
};
}
}
Then above your method use [PermissionAuth(/*permissions here*/)]
然后在您的方法上方使用[PermissionAuth(/*permissions here*/)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.