Search code examples
sharepointhttp-redirecthttpmodule

HttpModule events - intercept sharepoint redirect to accessdenied.aspx


For my SharePoint setup I have a a specific user group that does not have access to the frontpage of the site. If they visit it directly, they get the standard "Access denied" page from SharePoint.

I am developing a HttpModule that intercepts visit to the frontpage, checks the current user and redirects him to the sub-site they have access to.

I first tried using the PostAuthorizeRequest, but it seems SharePoint triggers on an earlier event and still redirects to the Access Denied page. I have tested with a user that had access to the frontpage but still be redirected, and there the redirect works fine.

Which event do I need to capture to be able to get the user after they've entered username/password but before SharePoint redirects them?


Solution

  • Instead of catching an "unauthorized" event in your code, I suggest that you go with custom errors. When a user is redirected to the Access denied page, SharePoint is actually throwing an error with the error code "401" (for unauthorized).

    In your web.config you can configure the behavior of your application for the 401 errors. If you've ever done an custom error page on a web app, it's the same thing. Look for the CustomError node in your web.config and modify it to something like this :

    <customErrors mode="On" defaultRedirect="~/_layouts/CustomErrorPage.aspx">
      <error statusCode="401" redirect="~/_layouts/AccessDeniedPage.aspx" />
    </customErrors>
    

    Then create your CustomErrorPage.aspx and your AccessDeniedPage.aspx and deploy them to the 12 hive.

    In the code behind of these pages, you can override the PageLoad event to redirect them wherever you want to :

    protected void Page_Load(object sender, EventArgs e)
    {
        bool isLogged = HttpContext.Current.User.Identity.IsAuthenticated;
        Response.Redirect("wherever");
    }
    

    Note that at this point you will still have access to the SPContext object if you need it (and i'm assuming you will want to write specific code depending on the group membership of the user).

    This is not a SharePoint specific behavior. All ASP.NET apps work that way. Using a site-wide configuration will allow you to only run your code when it needs to run (i.e. when the access is denied) instead of checking for permissions on every page load or something like that.