Geeks With Blogs
Fringe SharePoint Continued

I recently wrote a post where I discussed code that gave site access to users. I have had several deployments already that make that code fail. I do not know why it works in some environments and not the other.

 The real issue is SharePoint recognizing users on a site. Usually there is a SpUserCollection in context of an SPWeb or SPSite. The problem stems from users actually existing in that collection. By default only users given access to the site are actually in the collection. When the group, "All Authenticated Users" is added to the site. It does not autmatcially create SPUser objects for users to live inside the SpUsercollection. When the user visits a site, SharePoint creats an SpUser object and ads it to the collection of the site.  In order to grant access to a site to a user that has not visited a new site or an existing old site. You must add the user to the collection before you can grant permission.

Simply add this code before you add the user to the site

                          SPWeb.EnsureUser(string loginName);


The ensureUser method checks against the collection of users to see if the user exists, if it does not, then it the spuser object to the collection as if the user was visiting the site.

I don't know why it works without it in some environments and doesn't in others. I add it in all the time now. Just to make sure.


Posted on Monday, November 30, 2009 2:40 PM SharePoint | Back to top

Comments on this post: SPWeb.EnsureUser before granting site access

# re: SPWeb.EnsureUser before granting site access
Requesting Gravatar...
Very nice article. I worked with EnsureUser and found out that there are a few inconveniences. For example, we need almost always to use elevated privileges to deal with EnsureUser, otherwise exception will be thrown. Or for example, if user doesn't exist in user collection, it will be tried to add to this collection, but this means that spWeb object will be modified and it's required AllowUnsafeUpdates = true. Eventually, I've developed a small method-wrapper for EnsureUser. It's shown in my blog -
Left by dotNetFollower on Aug 15, 2011 10:03 PM

Your comment:
 (will show your gravatar)

Copyright © juanlarios | Powered by: