shamp00
shamp00

Reputation: 11326

What is the best practice for ensuring permissions are correct during the launch of an ASP.NET application

I have an ASP.NET application which requires write access on the App_Data subfolder. The MSI used to deploy the application tries to set the permissions correctly, but in spite of this, it seems the permissions are sometimes wrong. Most of the application works fine without this permission. I would prefer that the application fails to start if the permissions are wrong.

What is the best practice for ensuring that the necessary permissions are correct for the IIS user context? Ideally I want to display some simple instructions for fixing whatever is wrong. And I want the message to appear in as many incorrect configurations as possible.

The following describes what I've tried so far, until I realised there's a probably a better or standard way.

I tried putting this in Application_Start()

protected void Application_Start(Object sender, EventArgs e)
{
    // Assert permissions on writeable folders are correct
    var permissionsChecker = new AppDataPermissionsChecker();
    permissionsChecker.AssertFolderIsWriteable(
        HttpContext.Current.Server.MapPath("~/App_Data"));

    // remainder of Application_Start()...
}

where AppDataPermissionsChecker is defined as follows:

public class AppDataPermissionsChecker
{
    private bool CanWriteAccessToFolder(string folderPath)
    {
        try
        {
            // Attempt to get a list of security permissions from the folder. 
            // This will raise an exception if the path is read only or do not have access to view the permissions. 
            DirectorySecurity directorySecurity = Directory.GetAccessControl(folderPath);
            return true;
        }
        catch (UnauthorizedAccessException)
        {
            return false;
        }
    }

    public void AssertFolderIsWriteable(string folderPath)
    {
        if (!Directory.Exists(folderPath))
            throw new Exception(String.Format("The {0} folder does not exist.", folderPath));
        if (!CanWriteAccessToFolder(folderPath))
            throw new Exception(String.Format("The ASPNET user does not have " 
                + "access to the {0} folder. Please ensure the ASPNET user has "
                + "read/write/delete access on the folder.  See 'The App_Data folder' "
                + "here: http://msdn.microsoft.com/en-us/library/06t2w7da.aspx'",
         folderPath));
    }
}

I thought this would throw an ugly exception if the rights are incorrect (which is better than nothing), but in some situations I just get an HTTP Error 503.

Upvotes: 0

Views: 397

Answers (1)

shamp00
shamp00

Reputation: 11326

I found this implementation of a diagnostics page which does exactly what I was looking for (and more besides).

Upvotes: 1

Related Questions