C# Web Api拦截器
我已在web api上创建了自定义授权属性。我的目标是检查用户是否有权直接访问web api url,或者将其重定向到未经授权的页面。此过程要求我在任何地方添加[CustomAuthorize(“modulename”)。是否有其他方法可以做到这一点?可能是拦截器?任何指导都将不胜感激C# Web Api拦截器,c#,.net,asp.net-web-api,interceptor,C#,.net,Asp.net Web Api,Interceptor,我已在web api上创建了自定义授权属性。我的目标是检查用户是否有权直接访问web api url,或者将其重定向到未经授权的页面。此过程要求我在任何地方添加[CustomAuthorize(“modulename”)。是否有其他方法可以做到这一点?可能是拦截器?任何指导都将不胜感激 Customised authorize attribute pseudo code snippet: public override void OnAuthorizatio
Customised authorize attribute pseudo code snippet:
public override void OnAuthorization(HttpActionContext context){
var username = HttpContext.Current.Request.LogonUserIdentity.Name;
var accesiblemodulelistforuser = GetPermissions(username );
if (user != null)
{
if (modulename does not exist in list )
{
var response =
context.Request.CreateResponse(HttpStatusCode.Forbidden);
context.Response = response;
}
else{
return;
}
}
else{
//redirect to unauthorized page
}
}
您的ASP.NET版本中没有类定义,因此我假设您继承了
ActionFilterAttribute
类。只是注意到,你不是。见编辑版本。如果是这样,您可以在WebApiConfig.cs
中全局注册所有web api操作和控制器的筛选器,如下所示:
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new CustomAuthorize());
}
public static void Register(HttpConfiguration config)
{
filters.Add(new CustomAuthorize());
}
编辑
完全误解了你的处境。所以有更多的信息。
您可以使用自己的全局授权筛选器:
public class CustomAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// user not authorized, redirect to login page
filterContext.Result = new HttpUnauthorizedResult();
return;
}
string roleName = GetModuleName(filterContext);
var user = filterContext.HttpContext.User;
// Chaeck user permissions
if (!user.IsInRole(roleName))
{
// Handle not authorized requests and redirect to error page
filterContext.Result = new RedirectResult("~/Error/NotAuthorized");
return;
}
base.OnAuthorization(filterContext);
}
string GetModuleName(AuthorizationContext filterContext)
{
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
var actionName = filterContext.ActionDescriptor.ActionName;
return controllerName; // or actionName
}
}
然后,您可以在WebApiConfig.cs
中全局注册所有操作和控制器的筛选器,如下所示:
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new CustomAuthorize());
}
public static void Register(HttpConfiguration config)
{
filters.Add(new CustomAuthorize());
}
或仅在特定控制器/操作上使用
请注意,这种方法不适用于web api,只适用于mvc,因为web api有自己的AuthorizeAttribute
位于System.web.Http
(mvc版本位于System.web.mvc
)。实现略有不同,但您可以只查找示例。因此,您需要具有不同的属性—一个用于MVC,另一个用于WEB API。请参阅原始答案以了解如何全局注册WEB API过滤器,或仅对特定控制器使用它