User Authorization Attribute (Subsequent)

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.

+4
source share
1 answer
 public class CustomAuthorizeAttribute : AuthorizeAttribute { private readonly bool _authorize; private readonly string[] _roles; public CustomAuthorizeAttribute(string roles) { _authorize = true; _roles = roles.Split(','); } public CustomAuthorizeAttribute(string roles, bool isAdminPath) { _authorize = true; _roles = roles.Split(','); } protected override bool AuthorizeCore(HttpContextBase httpContext) { //if controller have role auth and user is not loged if(_authorize && !httpContext.User.Identity.IsAuthenticated) return false; // if controller have role auth and user is loged if(_roles != null) { //grab user roles from DB var UserRole = RoleRepository.GetUserRole(new Guid(httpContext.User.Identity.Name)); if (_roles.Contains(UserRole)) return true; } return false; } } 

In the controller

 [CustomAuthorize("Administrator,Company,OtherRole")] public ActionResult Test(){ return View(); } 
+2
source

Source: https://habr.com/ru/post/1340847/


All Articles