Assign extranet users to a SiteGroup


If you want to manage your extranet users on the your intranet you need to take care of some things.
Add/Remove users from groups via the object model:

string userLogin = @"domain\extranetuser01";
SPSite spSite = new SPSite(serverUrl);
SPWeb spWeb = spSite.OpenWeb(strUrl);
SPGroup spGroup = spWeb.SiteGroups[strGroupName];
 
spGroup.Users.Add(userLogin, userEmail, userName, userNotes); // Error: User does not exist in the site…
spGroup.Update();
 
First time error: "Error: User does not exist in the site…"
reason: Simple, the user doesn’t exist in your site collection => just add him or her to the SiteUsers collection of the SPWeb object 😉
 

if (!IsUserInSite(spWeb.SiteUsers, userLogin))
 spWeb.SiteUsers.Add(userLogin, userEmail, userName, string.Empty); // Error: User does not exist in the site…
 
private static bool IsUserInGroup(SPGroup spGroup, string username)
{
 // the check if the user already exists…
}
Second time error: "Error: User does not exist in the site…"
You would think that this is strange but the cause is also simple. You execute the code in the intranet environment but the user that you want to add lives on the extranet.
The extranet uses in most cases another authentication provider. You need to provide the name of the used membershipprovider of the extranet together with your loginname of the user. Otherwise the system can’t recognize the extranet user.
let’s assume that the name of the Membership Provider from the extranet is "SqlCustomMembershipProvider" (via Central Administration > Application Management > Authentication Providers > YourExtranet). The code needs to be modified in this:

string userLogin = @"SqlCustomMembershipProvider:domain\extranetuser01";
SPSite spSite = new SPSite(serverUrl);
SPWeb spWeb = spSite.OpenWeb(strUrl);
SPGroup spGroup = spWeb.SiteGroups[strGroupName];
 
if (!IsUserInSite(spWeb.SiteUsers, userLogin))
 spWeb.SiteUsers.Add(userLogin, userEmail, userName, string.Empty);
 
spGroup.Users.Add(userLogin, userEmail, userName, userNotes);
spGroup.Update();
 
spWeb.Dispose();
spSite.Dispose();
 
private static bool IsUserInGroup(SPGroup spGroup, string username)
{
 // the check if the user already exists…
}
Advertisements
This entry was posted in Sharepoint. Bookmark the permalink.

One Response to Assign extranet users to a SiteGroup

  1. Mano says:

    you can use SPWeb.EnsureUser(userLogin) to add the user in the site

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