开发者

ASP.NET IAuthorizationFilter OnAuthorization

Hi I am trying to implement a custom Authorization filter

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

As you can see on the OnAuthorization I get back a result that is true of false. What do I need to set to return where I came from?

EDIT:

It still seems to throw me st开发者_如何学运维raight to the log in page

I do inject IAuthetication

 this.BindFilter<CustomAdminAuthorizationFilter>(FilterScope.Controller, 0);
   Bind<IAuthentication>().To<CustomAuthenticationService>();

Then I decorate my action in the controller as so.

[Authorize]
    public ActionResult Index()
    {
        ViewBag.Title = "Welcome";
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }

In my web.config Im using

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>

Should this be altered?

Any help would be greatly appreciated.


Change that to an Attribute, not simple a 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();
    }
}

And now rather than using [Authorize] use your new [SageAdminAuthorize] attribute

[SageAdminAuthorize]
public ActionResult Index()
{
    ViewBag.Title = "Welcome";
    ViewBag.Message = "Welcome to ASP.NET MVC!";

    return View();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜