Thursday, 24 July 2014

SharePoint Security

1.Get login user detail: We can get logged in detail using CurrentUser property of the SPWeb object associated with the current site.
Sample Code:
SPUser currentUser = SPContext.Current.Web.CurrentUser;
string userName = currentUser.Name;
string userLogin = currentUser.LoginName;
string userEmail = currentUser.Email;

2. Display and create SharePoint group: SiteGroups and Groups properties of the SPWeb object to get details of the SharePoint security groups.
Sample Code:
using(SPSite siteCollection = new SPSite(""))
{
using(SPWeb site = siteCollection.OpenWeb())
{

// Print all groups name of site
foreach (SPGroup group in site.Groups)
{
Console.WriteLine(group.Name);
}
// Print all groups name of site collection
foreach (SPGroup group in site.SitesGroups)
{
Console.WriteLine(group.Name);
}
}
}
SiteGroups Vs Groups:
Groups would return the group collection of the current site. This would be a subset of the groups available in the site collection, which is available through the SiteGroups property.
Example:
Suppose there is a site collection called “http://localhost/sites/SharePoint” and it has following security groups:
· Approver
· Site Owner
· Site Viewer
· Custom Group
There is site under this collection called “http://localhost/sites/SharePoint/ChildSite” and only last two groups which have any kind of permissions defined within this site.
So Groups will return only “Site Viewer” and “Custom Group” but SiteGroups will return all cross site groups.
Sometime we need to add SharePoint group at runtime. If you try to add new SharePoint group in the site using Groups property available, you get an exception stating, “You cannot add a group directly to the Groups collection. You can add a group to the SiteGroups collection”. So We will have to use SiteGroups to add new group.
Sample Code:
// Adds a new group to the site collection groups:
site.SiteGroups.Add("", site.CurrentUser,
site.CurrentUser, "");
//Set pemission to the new site group
SPGroup secGroup = site.SiteGroups[""];
SPRoleAssignment roleAssignment = new SPRoleAssignment(secGroup);
SPRoleDefinition roleDefinition = site.RoleDefinitions["Full Control"]; //e.g. "Full Control", "Contributor" etc..
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
site.RoleAssignments.Add(roleAssignment);
3. Update SharePoint Group properties: We need to get SPGroup object to update any properties of SharePoint groups. Refer follwing links to know avaiable properties and methods in SPGroup
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spgroup_members.aspx
Sample code to update Owner of SharePoint group:
using(SPSite siteCollection = new SPSite(""))
{
using(SPWeb site = siteCollection.OpenWeb())
{
SPGroup currentGroup = site.SiteGroups[""];
currentGroup.Owner = SPGroup or SPMember object;
currentGroup.Update();
}
}