Ok, following this thread , this is what I came up with ...
public class SharweAuthorizeAttribute : AuthorizeAttribute { private bool isAuthenticated = false; private bool isAuthorized = false; public new string[] Roles { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (SessionManager.CheckSession(SessionKeys.User) == true) { isAuthenticated = true; foreach (string role in Roles) { if (RolesService.HasRole((string)role)) isAuthorized = true; } } return (isAuthenticated && isAuthorized); } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!isAuthenticated) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { "action", "User" }, { "controller", "Login" } }); } else if(!isAuthorized) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { "action", "Home" }, { "controller", "Error" } }); } } }
How / why did I come up with this? Since I believe that the AuthorizeAttribute workflow looks like this:
- First, AuthorizeCore is launched. If it returns true, the user logs in. If it returns false, HandleUnauthorizedRequest is launched. It is right?
- I read somewhere that to override a property I need to use the
new keyword. Therefore, I override the Roles property. But what if the override property was of a different type of source (the main one in the base class), does it hide it or create a completely different property?
And what do you think? Should this work? I canโt check it now because I didnโt set up the user interface (waiting for the designer to finish the design) ... Actually, this is the first time I appreciate the benefits of TDD, I usually thought it was stupid and useless, but I was wrong:)
PS: In this thread , @tvanfosson sets the cache context context (I think), can someone explain this and why may I need to do this, please?
Thanks in advance.
source share