您好我正在尝试实施自定义授权过滤器
//The Authourization attribute on a controller
public class CustomAdminAuthorizationFilter : IAuthorizationFilter
{
private readonly IAuthentication _authentication;
public SageAdminAuthorizationFilter(IAuthentication authentication)
{
_authentication = authentication;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
bool result = _authentication.Authorize(filterContext.HttpContext);
}
}
正如你在OnAuthorization上看到的那样,我得到的结果是假的。 我需要设置什么才能返回我来自哪里?
编辑:
它似乎仍然让我直接进入登录页面
我注射了IAuthetication
this.BindFilter<CustomAdminAuthorizationFilter>(FilterScope.Controller, 0);
Bind<IAuthentication>().To<CustomAuthenticationService>();
然后我在控制器中装饰我的动作。
[Authorize]
public ActionResult Index()
{
ViewBag.Title = "Welcome";
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
在我的web.config中使用
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
这应该改变吗?
非常感谢任何帮助。
答案 0 :(得分:17)
将其更改为Attribute
,而不是简单的IAuthorizationFilter
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class SageAdminAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
readonly IAuthentication _authentication;
public SageAdminAuthorizeAttribute(IAuthentication authentication)
{
_authentication = authentication;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!_authentication.Authorize(filterContext.HttpContext))
filterContext.Result = new HttpUnauthorizedResult();
}
}
现在而不是使用[Authorize]
使用新的[SageAdminAuthorize]
属性
[SageAdminAuthorize]
public ActionResult Index()
{
ViewBag.Title = "Welcome";
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}