Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 straight 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.

like image 652
Mark O'Grady Avatar asked Apr 14 '11 12:04

Mark O'Grady


1 Answers

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();
}
like image 115
hunter Avatar answered Sep 18 '22 09:09

hunter