Adding Users Programmatically to A Claims Site in SharePoint 2010

I had a friend send me kind of an interesting problem the other day.  He was trying to add a new user programmatically to a Windows claims site and having all sorts of difficulties.  His initial attempt at adding the user with domain\username and the SPRoleAssignment class was not working for him.  He then tried various flavors of providing the claims encoded value for what the user name should be and got that to work partially, but had some strange side effects like the name appearing twice.  While I didn’t have a chance to personally examine all the variations and issues he had, what I did find worked for me on the first try was just to use the EnsureUser method on SPWeb.  It’s much simpler than having to fool around to try and get the encoding for an account name; it’s also a lot easier because you only need to pass in the account name instead of the four parameters you normally have to use to add a user.  EnsureUser automatically takes care of encoding the name and really simplified his code. 

For completeness here’s a short example:

using (SPSite theSite = new SPSite(“http://foo”))
  using (SPWeb theWeb = theSite.OpenWeb())
    SPUser theUser = theWeb.EnsureUser(“domain\username”);

UPDATE:  Make sure you read this post on how you should format the user name:


Leave a Reply

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

You are commenting using your 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