Search code examples
c#asp.netasp.net-mvc-5asp.net-core-identity

Redirect a user and "block" him on the ChangePassword page


Is an asp.net MVC app. I am using Asp.NetCore.Identity

I want after login if "password has never been changed"(i know how to condition this) to redirect him to the ChangePassword page and block any other page until changing password.(or when he wants to acces other page to redirect on ChangePassword)

Any idea? Maybe to override authorize attribute?


Solution

  • I did the same by creating custom Authorization class. for that we have to make a new class and inherit AuthorizeAttribute class on it and then override a method named AuthorizeCore because it is entry point of custom authorization check.

    public class CheckAuthorization: AuthorizeAttribute
    {
        public CheckAuthorization(){
        }
    
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool _isAuthorize = false;
    
            if(password change required)
                httpContext.Response.Redirect("~/home/changepassword");
    
            if (!httpContext.User.Identity.IsAuthenticated)
                return false;
    
             // Check roles 
    
             return true;
        }
    }
    

    Then use your Authorization attribute like this

    [CheckAuthorization(Roles = "admin, superadmin, root")]
    public ActionResult DashBoard()
    {
        return View();
    }