asp.netasp.net-membershipauthorizationrole-based

Role based authorization


I am trying to use Role based authorization in declarative way, when unauthorized user attempt to access a page, it never fire an exception or show the user an error message. What I should do to show unauthorized message? is that possible in declarative way?

using coding is not a nice option sense I have several roles, and folder authorized for several roles while other folders are authorized for one role.

thanks


Solution

  • Use the following code in your Login page to redirect the user to either an unauthorized page or the default page.

        protected void Page_Load( object sender, EventArgs e )
        {
            if( Page.IsPostBack )
                return;
    
            if( !Request.IsAuthenticated )
                return;
    
            if( !string.IsNullOrEmpty( Request.QueryString["ReturnUrl"] ) && !UrlAuthorizationModule.CheckUrlAccessForPrincipal(Request.QueryString["ReturnUrl"], User,"GET"))
            {
                // In Forms Authentication, authenticated but unauthorized requests are converted into a Redirect to the Login page.  
                // Redirect these to an error page instead.
                Response.Redirect( "~/UnauthorizedAccess.aspx", false );
            }
            else
            {
                Response.Redirect( FormsAuthentication.DefaultUrl, false );
            }
        }
    

    See this link for a picture of what's happening and more info:

    http://www.asp.net/security/tutorials/user-based-authorization-cs