从公共位置申请授权
本文关键字:授权 位置 | 更新日期: 2023-09-27 18:17:41
我目前有几个控制器,我已经限制了[Authorize]
装饰器。我现在需要在几个不同的控制器中做这个,是否有一个可以放置这个的中心位置?一旦在那个位置,我可以告诉它应用到哪个控制器,而不是我把它放到每个单独的控制器文件?
这样如何:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
string controllerName = actionContext.ControllerContext.ControllerDescriptor.ControllerName;
bool shouldAuthorize = //.. Check if controller needs authorization
if(!shouldAuthorize)
SkipAuthorization(actionContext);
else if(!IsAuthorized(actionContext))
HandleUnauthorizedRequest(actionContext);
}
}
那么你将全局应用这个过滤器:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomAuthorizeAttribute());
}
注意,控制器验证是在自定义属性中完成的。
你可以创建一个基控制器作为其他控制器的继承。在这个类中应用您的主授权属性。
Namespace Controllers
<SecureAuthorizeAttribute>
Public Class SecureController
Inherits Controller
End Class
End Namespace
然后在其他控制器中:
Public Class ViewDetailsController
Inherits SecureController
End Class
这将把<SecureAuthorizeAttribute>
应用到从SecureController
继承的类中的每个动作。