Forms Authentication and Read/Anonymous Access


I had created a .ascx control as a footer for a SharePoint MasterPage which displayed the date the page was changed and it worked great.  It was great until I created a user account (Forms Based Authentication) with “Read” access and when the account logged in I would get an “Error: Access Denied”, this error did not occur if the account was granted “Contributor” access.

image

I tested the account using the default MasterPage in SharePoint and the account was fine when it had to display that page so I suspected some code I had attached to my .ascx control.

The code block that executed was pretty simple which is below:

        String PageName = FileName();
        using(SPSite RootSite = new SPSite(Page.Request.Url.ToString()))
        {
            using (SPWeb SiteCollection = RootSite.OpenWeb())
            {
                string path = RootSite.MakeFullUrl(PageName);
                SPFile file = SiteCollection.GetFile(path);
                String LastModifiedDate = file.TimeLastModified.ToString("yyyy-MM-dd");
                String ModifiedBy = file.ModifiedBy.ToString();
                theDate = LastModifiedDate;
            }
        }

If I commented out that code in the control the MasterPage loaded for the user account with “Read” access so I figured I needed to run the code “elevated” so I changed it slightly and surrounded it with

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {

            // code here

         });

This solved my issue with my .ascx control and the user with “Read” access no longer gets the “Error: Access Denied” page. 

A call to RunWithElevatedPrivileges switches both the User Identity and the Windows Identity, if you want to read more about this check out this great MSDN article on Security Programming in SharePoint 2007 by Ted Pattison.

 

About wesmacdonald

Wes MacDonald is a Visual Studio ALM MVP, PSD, MCT and a Principal Consultant for LIKE 10 INC., a SharePoint Server, Visual Studio and Team Foundation Server Consulting Firm providing premium support and guidance services.

No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: