Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
850 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...