R – Prevent Access to Custom Web Application Pages by Non-Admin Users in SharePoint

permissionsSecuritysharepointsharepoint-2007

I have a custom web application that integrates with a SharePoint (MOSS 2007) solution. I would like to add role-based access to pages in this custom web application, with only users in a specified SharePoint group or with a specific role being able to access them. Other users being sent to the default OOTB web page, giving the message "You Are Not Authorized to View This Page".

Can anyone point me towards tutorials on how to implement this, and how to control access on each custom page?

Please note, these pages are part of the custom web application, and are NOT created via the SharePoint API or interface.

Thanks, MagicAndi.

Update

Just to make you aware, I am hoping for a solution where we can make use of the SharePoint functionality to extend security trimming or item permissions to limit access to the custom web application pages. I already have code to check a user's SPGroup on page load, and to redirect if required. Thanks.

Best Answer

I have a similar setting on my current project, I changed it a bit to make more sense to your question, we use a base class for custom webpages, something like:

public abstract class WebPageBase : Page
{
    public SPBasePermissions PagePermissionFlag;
    public override void OnInit(EventArgs e)
    {
        SPWeb web = SPContext.Current.Web;
        if(!web.DoesUserHavePermissions(PagePermissionFlag))
        {
            // build the access denied page
            SPUtility.Redirect(SPUtility.AccessDeniedPage + "?Source=" + SPHttpUtility.UrlKeyValueEncode(web.Site.MakeFullUrl(Request.RawUrl)),
                               SPRedirectFlags.RelativeToLayoutsPage,
                               HttpContext.Current);
        }
} }

Then on the page itself, the permission is defined:

public class ContentPage : WebPageBase
{
    protected void Page_PreInit(Object sender, EventArgs e)
    {
        PagePermissionFlag = SPBasePermissions.ViewFormPages;
    }
}

Note: you can also set that on the:

<%@Page PagePermissionFlagString="SPBasePermissions.ViewFormPages"%> *
* you will have to convert the string to the enum in the WebPageBase)

Just for reference, this extra bit is unrelated to the implementation above, its how we use it internally:

public static class CurrentUser
{
    public static bool IsAdmin
    {
        get
        {
            return SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.ManageWeb);
        }
    }

    public static bool IsReader
    {
        get
        {
            return SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.ViewFormPages);
        }
    }
}