Thursday, November 5, 2009
SharePoint FBA – Adding users programmatically
Colleagues of mine have implemented Forms based Authentication (FBA) for a customer site. The customer was so “kind” to supply them with a Excel sheet containing 1200 usernames, email addresses and passwords. Every single user had to be imported into the FBA SQL database and certain SharePoint groups.
I decided to make a friendly web part which allows the user to select a *.csv file on their hard drive, and with a push on the button to import the users from the file.
Adding users to FBA went smooth, but adding those users to SharePoint groups threw Exceptions. Weird thing was, that even though I could not add the users through code, those users could be found in the People picker (and thus could be added through the user interface).
After adding users to FBA, I had to add them to SharePoint explicitly, before I could put them in SharePoint groups through code.
So the code for adding users to FBA, and adding the SharePoint groups should look like this:
MembershipUser existingUser = System.Web.Security.Membership.GetUser(“TheUserName”);
if (existingUser != null)
{
Membership.DeleteUser(“TheUserName”, true);
}
MembershipCreateStatus createStatus;
Membership.CreateUser(“TheUserName”, “ThePassword”, “TheEmailAdress”, "FbaPasswordQuestion", "FbaPasswordAnswer", true, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
string userName = "aspnetsqlmembershipprovider:" + “TheUserName”; //Don’t forget to prefix the username with the membership provider you defined
web.SiteUsers.Add(userName, “EmailAdress”, “Name”, "Batchimport");
SPUser user = web.SiteUsers[userName];
if (user != null)
{
web.Groups["GroupName"].AddUser(user);
web.Update();
}
else
{
throw new Exception("The user was added to FBA, but couldn't be added to SharePoint.");
}
}
else
{
throw new Exception("The user could not be added to FBA.");
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment