I want to give site level permission to user programmatically. I want that user can only be able to view the site. How can I do this?
-
1By "programatically" do you mean PowerShell Script or compiled code (console app)? Do the user have access to any web application in the farm today? – Benny Skogberg♦ May 19 '15 at 8:06
You could use PowerShell to do this:
Set-SPUser -Identity 'domain\user_name' -Web http://siteCollection/site -AddPermissionLevel Read
If you are looking for granting the user permission through SharePoint Object Model Programming then the below code should help you. Not sure how you would prefer executing the below code. But yes you may put this code in an Event Receiver or Console Application, the choice is yours.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using(SPSite spSite = new SPSite("yourSite")
{
using(SPWeb spWeb = spSite.OpenWeb())
{
//get current permission definitions so we can apply permissions
SPRoleDefinitionCollection roleDefs = spWeb.RoleDefinitions;
//get a specific user or ad security group by username
SPUser myUser = web.EnsureUser(@"domain\username");
SPRoleAssignment addUser = new SPRoleAssignment(myUser);
//create new roles binding for user or group
SPRoleDefinitionBindingCollection bindUser = addUser.RoleDefinitionBindings;
//give read permission to the user
bindUser.Add(roleDefs[“Read”]);
spWeb.Update();
}
}
});