Permission Issue in SharePoint O365 - sharepoint

I created a trial office 365 sharepoint account for learning. While creating my first Insert operation I got an exception as
Access denied. You do not have permission to perform this action or access this resource.
My code is
In Load event
protected void Page_Load(object sender, EventArgs e)
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext == null) return;
Session["clientContext"] = clientContext;
Microsoft.SharePoint.Client.User spUser = clientContext.Web.CurrentUser;
clientContext.Load(spUser, user => user.Title);
clientContext.Load(spUser, user => user.Email);
clientContext.ExecuteQuery();
}
}
On button click save event(Name and EmailId)
protected void Button1_Click(object sender, EventArgs e)
{
try
{
using (var clientContext = Session["clientContext"] as ClientContext)
{
if (clientContext == null) return;
var oList = clientContext.Web.Lists.GetByTitle("SharePointTestList");
var listCreationInformation = new ListItemCreationInformation();
var itemToAdd = oList.AddItem(listCreationInformation);
itemToAdd["EmailId"] = TextBox2.Text; //My List
itemToAdd["Name"] = TextBox1.Text; //My List
itemToAdd.Update();
clientContext.Load(itemToAdd);
clientContext.ExecuteQuery();
}
}
catch (Exception ex)
{
Response.Write("Error Occured"+ex.Message);
}
}
It seems some permission issue. But I am not able to figure it out.

I have already faced the same problem while creating 1st time.I solved it by doing like this
Go to AppManifest.xml in your SharePointApp
Click Permissions Tab
Give FullControl Permissions to Scope Web and List

As already discussed in the comments I have a strong suspicion, that you are lacking the proper permissions to write to your target list.
As you've said you have "limited access". This means:
Can view specific lists, document libraries, list items, folders, or
documents when given permissions.
In order to write to a list, you need to grant the user at least "Contribute" permissions.
So this is not a programming related issue. Read up on the basic permission levels within SharePoint here.

Related

Sharepoint modal window not shown when no permissions to at least one in the library

I have a sharepoint 2013 farm solution with event receiver on Item Added (synchronously triggered) and when user uploads a file: permissions are broken, deleted and added again.
There are 3 groups: Visible, Edit and Hidden.
When file is added as Edit or Visible group everything works fine, permissions are broken, added for Visible and Edit and modal window to input Required fields is shown. But when adding as Hidden group which cannot see the confidential files, permissions are added (Visible, Edit, Hidden) but the file is added and modal is not shown anymore. I can recreate such behaviour when I delete permissions for any group.
I tought it is sharepoint default behaviour but I have recreated this sittuation on a standard library and set same permissions with UI and modal is shown normally as it should.
Code of event:
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
var confidentialField = properties.List.Fields.TryGetFieldByStaticName(Consts.ConfidentialColumnName);
var confidentialVisibleGroup = getGroup(properties.List, confidentialField, Consts.ConfidentialVisibleGroupName);
var confidentialHiddenGroup = getGroup(properties.List, confidentialField, Consts.ConfidentialHiddenGroupName);
var confidentialEditGroup = getGroup(properties.List, confidentialField, Consts.ConfidentialEditGroupName);
using (var scope = new DisabledItemEventsScope())
{
properties.ListItem.File.CheckIn("test"); //need to check in the file because it won't exist when getting it with ID in elevated. it is checked out by default
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
setPermissions(properties, confidentialVisibleGroup, confidentialHiddenGroup, confidentialEditGroup,
confidentialField.InternalName);
});
properties.ListItem.File.CheckOut(); // no matter if the file is checked out or not modal not shown
}
}
private static void setPermissions(SPItemEventProperties properties, SPGroup confidentialVisibleGroup,
SPGroup confidentialHiddenGroup, SPGroup confidentialEditGroup, string confidentialFieldInternalName)
{
try
{
using (var site = new SPSite(properties.SiteId))
{
using (var web = site.OpenWeb(properties.RelativeWebUrl))
{
web.AllowUnsafeUpdates = true;
var list = web.Lists[properties.List.ID];
var listItem = list.GetItemById(properties.ListItemId);
listItem.BreakRoleInheritance(false);
//add 2 permission groups
var roleAssignment = new SPRoleAssignment(confidentialEditGroup);
roleAssignment.RoleDefinitionBindings.Add(
properties.Web.RoleDefinitions.GetByType(SPRoleType.Contributor));
listItem.RoleAssignments.Add(roleAssignment);
roleAssignment = new SPRoleAssignment(confidentialVisibleGroup);
roleAssignment.RoleDefinitionBindings.Add(
properties.Web.RoleDefinitions.GetByType(SPRoleType.Contributor));
listItem.RoleAssignments.Add(roleAssignment);
//add hidden group with no permissions to all files on library
roleAssignment = new SPRoleAssignment(confidentialHiddenGroup);
roleAssignment.RoleDefinitionBindings.Add(
properties.Web.RoleDefinitions.GetByType(SPRoleType.Contributor));
listItem.RoleAssignments.Add(roleAssignment);
listItem.SystemUpdate();
}
}
}
catch (Exception e)
{
Logger.GetLogger().WriteLog("Exception while setting permissions to confidential item", e);
}
}

Check current user's permission if the user has no enumerate permission in SharePoint

As we know, we can check user's permission by doing this:
using (SPWeb web = site.OpenWeb(path))
{
SPUser user = SPContext.Current.Web.CurrentUser;
string loginName = user.LoginName;
if (web.DoesUserHavePermissions(SPBasePermissions.EnumeratePermissions))
{
if (web.DoesUserHavePermissions(user.LoginName, SPBasePermissions.Open))
{
//do something
}
}
}
Here is my question, if current user doesn't have enumerate permission, how to get permissions on SharePoint object? Thanks in advance.
You can do it by opening an "admin" web instance (creating a SPSite object and passing System account's user token to it). This way you do not have to worry about whether current user has or has not got enough permission.
SPUserToken adminToken = SPContext.Current.Web.AllUsers["SHAREPOINT\\System"].UserToken;
using (SPSite adminSite= new SPSite(SPContext.Current.Site.ID, adminToken) ) {
using (SPWeb adminWeb = adminSite.OpenWeb(SPContext.Current.Web.ID)){
if (adminWeb.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser.LoginName, SPBasePermissions.Open)) {
//do something
}
}
}
Of course, you better not do this on every page load as creation and disposing of SPSite/SPWeb objects is relatively expensive.
Here I have defined a function that takes a SharePoint list object, a Role type and a User.
portal : The sharepoint list or document library object.
role : RoleType provided by sharepoint like Read, Design etc.
user : user to whom you want to grant role on portal.
Hope it will help you.
public static void AssignPermissionToPortal(string portal, SPRoleType role, SPUser user)
{
try
{
// Run with elevated privileges
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
{
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
{
web.AllowUnsafeUpdates = true;
SPList portalList = SPListHelper.GetSPList(portal, web);
portalList.BreakRoleInheritance(false);
//Add Readers on portal
SPRoleDefinition permission = web.RoleDefinitions["Read"];
if (role == SPRoleType.Administrator)
permission = web.RoleDefinitions["Full control"];
else if (role == SPRoleType.Contributor)
permission = web.RoleDefinitions["Contribute"];
else if (role == SPRoleType.WebDesigner)
permission = web.RoleDefinitions["Design"];
else
permission = web.RoleDefinitions["Read"];
// Check the user Role on site level.
SPUser roleUser = uHelper.GetUserById(user.ID);
if (roleUser != null)
{
SPRoleAssignment assignment = new SPRoleAssignment(roleUser);
assignment.RoleDefinitionBindings.Add(permission);
portalList.RoleAssignments.Add(assignment);
portalList.Update();
}
web.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
Log.WriteException(ex);
}
}

Access denied error while using People picker on custom page

We have custom upload page for document library.
On upload page we have one people picker field,
(user can enter multiple users id)
Design for People picker
<SharePoint:PeopleEditor ID="pplApprovers" runat="server" Width="250px" Height="25px" MultiSelect="true"/>
to get emp id from people picker we use below code
public ArrayList approversArray;
public SPFieldUserValueCollection approversCollection;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
ArrayList aAccount1 = new ArrayList();
approversArray= pplApprovers.Entities;
approversCollection = new SPFieldUserValueCollection();
SPUser user;
SPGroup group;
SPUser currentUser;
SPWeb web=SPControl.GetContextWeb(Context);
currentUser=web.CurrentUser;
ArrayList aAccount = new ArrayList();
aAccount = pplApprovers.Accounts;
ArrayList peEntities = pplApprovers.Entities;
approversArray = pplApprovers.ResolvedEntities;
foreach (PickerEntity entity in approversArray)
{
if (entity.EntityData["PrincipalType"].ToString() == "SharePointGroup")
{
group = web.SiteGroups[entity.Key];
approversCollection.Add(new SPFieldUserValue(web,group.ID, group.Name));
}
else
{
//handles SecurityGroup, Distribution List and User
user = web.EnsureUser(entity.Key);
approversCollection.Add(new SPFieldUserValue(web,user.ID, user.Name));
}
}
});
catch (Exception ex)
{
// Manage error event
}
and after getting this value we are inserting it in document library.
item.Item["Account Partner"]="approversCollection";
but after clicking upload button the only user who have site admin access can successfully upload the file but other user's who don't have admin access gets redirected to the
https://web/_layouts/AccessDenied.aspx
page
We tried using SPSecurity.RunWithElevatedPrivileges but got no success...
Anyone please let me know how to resolve this issue or alternate way to use people picker
Instead of using the SPContext of the web object you need to create a new site and web object under the elevated privileges.
SPWeb web=SPControl.GetContextWeb(Context)
You need to use this under your elevated permissions:
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using(SPWeb web = site.OpenWeb())
{
....
}
}

SharePoint 2010: Adding a User to a Group from code

I am trying to add a user to an existing group from a custom login page. Right now, I have no problem getting the current user from SPWeb.CurrentUser. I can view all of this current users groups, but now I am having a problem adding this user to an existing group. I think I need to use SPRoleDefinition and SPRoleAssignment, but all I can find is how to change the permissions on a group using these classes. Does anyone know how I can add this user to a group by the groupname?
Thanks!
You can utilize this function to add user to the current site. You need to pass Group name and UserName.
public void AddUsers(string groupname, string username)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Gets a new security context using SHAREPOINT\system
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb thisWeb = site.OpenWeb())
{
thisWeb.AllowUnsafeUpdates = true;
SPUser Name = thisWeb.EnsureUser(username);
thisWeb.Groups[groupname].AddUser(Name);
thisWeb.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
//Log error here.
}
}
Have you tried any of this?
If you're trying to add a user to a group, this should work:
SPUser currentUser = SPContext.Current.Web.CurrentUser;
SPGroup group = SPContext.Current.Web.SiteGroups["My Group Name"];
group.AddUser(currentUser);
http://msdn.microsoft.com/en-us/library/ms454048.aspx

Checking permissions of a user with a site collection

I want to check whether a user has permissions to a site collection. But i dono how to use SPSite.DoesUserHavePermissions().
What is SPReusableAcl? How can i get it for checking the permissions of the user?
Doesn't the MSDN article (SPWeb.DoesUserHavePermissions Method (String, SPBasePermissions)) help you? The example code can be used to check whether the user has access to a site collection:
using System;
using Microsoft.SharePoint;
namespace Test
{
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
// Make sure the current user can enumerate permissions.
if (web.DoesUserHavePermissions(SPBasePermissions.EnumeratePermissions))
{
// Specify the permission to check.
SPBasePermissions permissionToCheck = SPBasePermissions.ManageLists;
Console.WriteLine("The following users have {0} permission:", permissionToCheck);
// Check the permissions of users who are explicitly assigned permissions.
SPUserCollection users = web.Users;
foreach (SPUser user in users)
{
string login = user.LoginName;
if (web.DoesUserHavePermissions(login, permissionToCheck))
{
Console.WriteLine(login);
}
}
}
}
}
Console.ReadLine();
}
}
}
In the sample code above you would just have to change your Site URL and the Variable permissionToCheck. SPBasePermissions has a lot of possible permissions to check against, you can see the enumeration here (SPBasePermissions Enumeration).
Actually there are a lot of tutorials on how to check some user's permissions and you are not limited to DoesUserHavePermissions, see the following Google Search.
As usual, the MSDN examples provide nice textbook examples that do not always apply to real-life scenarios.
In the context of an application page running on SharePoint 2010, from what i understand this code needs to be wrapped in a call to RunWithElevatedPrivileges and even then, as my comment implies, it seems there is an implied catch-22 in the requirements. This works for me (the LoginName is just the FBA username or "domain\user" for AD user for the site - in our case an e-mail address is used):
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite elevatedSite = new SPSite(siteCollectionUrl))
{
foreach (SPSite siteCollection in elevatedSite.WebApplication.Sites)
{
using (SPWeb elevatedWeb = siteCollection.OpenWeb())
{
bool allowUnsafeUpdates = elevatedWeb.AllowUnsafeUpdates;
bool originalCatchValue = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
try
{
elevatedWeb.AllowUnsafeUpdates = true;
// You can't verify permissions if the user does not exist and you
// can't ensure the user if the user does not have access so we
// are stuck with a try-catch
SPUser innerUser = elevatedWeb.EnsureUser(loginName);
if (null != innerUser)
{
string splogin = innerUser.LoginName;
if (!string.IsNullOrEmpty(splogin) && elevatedWeb.DoesUserHavePermissions(splogin, SPBasePermissions.ViewPages))
{
// this user has permissions; any other login - particularly one that
// results in an UnauthorizedAccessException - does not
}
}
}
catch (UnauthorizedAccessException)
{
// handle exception
}
catch (Exception)
{
// do nothing
}
finally
{
elevatedWeb.AllowUnsafeUpdates = allowUnsafeUpdates;
// reset the flag
SPSecurity.CatchAccessDeniedException = originalCatchValue;
}
}
}
}
});
SPSite.DoesUserHavePermissions(SPReusableAcl, SPBasePermissions);

Resources