c# - Web API 拦截器
问题描述
我在我的 web api 上创建了一个自定义授权属性。我的目标是检查用户是否有权直接访问 web api url,否则将他重定向到未经授权的页面。这个过程需要我在任何地方添加 [CustomAuthorize("modulename")]。有没有其他方法可以做到这一点? 可能是拦截器?。任何指导将不胜感激。
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
class 。刚刚注意到,你不是。见编辑版本。如果是这样,您可以为所有 Web api 操作和控制器全局注册过滤器,WebApiConfig.cs
如下所示:
public static void Register(HttpConfiguration config)
{
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)
{
filters.Add(new CustomAuthorize());
}
或仅用于特定的控制器/动作。
请注意,这种方法不适用于 web api,仅适用于 mvc,因为 web api 有它自己的AuthorizeAttribute
位置System.Web.Http
(MVC 版本位于System.Web.Mvc
)。实现方式略有不同,但您可以查找示例。所以你需要拥有不同的属性——一个用于 MVC,一个用于 WEB API。请参阅原始答案以了解如何全局注册 WEB API 过滤器,或仅将其用于特定控制器。
推荐阅读
- html - 无法在 addeventListener 函数中更新全局变量
- c# - 部分视图 - 如何从 mvc 中的部分视图列表中获取按钮的 ID,以及如何通过传递 id 来调用相同的操作
- reactjs - 如何从 React Js 项目中删除所有 unsed 导入?(VS代码)
- apache-spark - 未分区的大型数据集连接另一个已分区的大型数据集。结果数据集是否分区?
- java - 如何进行放心认证?
- django - 连接路径位于基本路径组件之外
- python - 在 Django 中使用 {% if %} {% else %}
- angular - 使用 Ionic / Angular 遍历来自 Firebase 的逗号分隔图像
- angular - 如何在 Angular 8 中使用 EventEmitter
- roku - 有没有办法在 ROKU 中为按钮设置边框?