ASP.Net Web API 的 MVC 自定义授权

本文关键字:MVC 自定义 授权 API Net Web ASP | 更新日期: 2023-09-27 18:36:48

我有一个复杂的应用程序,其中包含许多Web Api调用,这些调用需要数据库内的权限检查。 我可能有一个示例简单的 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);
    }

要进行权限检查,我必须执行以下操作:

int staffID = (User as CustomPrincipal).UserId;
int siteId = Functions.GetSiteIdFromCookie();
if (Functions.UserHasAccess(staffID, AccessLevels.access_StudentDetailsUpdate,siteId) == true) return true;
else return false;

我想实现的是创建自定义授权注释,以便我可以拥有:

[HttpGet]
[PermissionAuth(AccessLevels.access_StudentDetailsUpdate,AccessLevels.access_StudentDetailsReadOnly)]
public IEnumerable......

我可能需要有一个选项和/或,即两者都是真的或一个是真的。 谁能帮忙?

ASP.Net Web API 的 MVC 自定义授权

这可以通过扩展AuthorizeAttribute并重写IsAuthorized方法来实现。您需要的如下所示的内容。

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
        };
    }
}

然后在您的方法上方使用[PermissionAuth(/*permissions here*/)]