I want regular user can access the "User Information List" in Mysite root site. I am using "RunWithElevatedPrivileges" method. Still throwing access denied error. per example my root site collection for mysite is "http://network.test.com". the user want assess userinformation list this site collection. How can he access that?
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
{
ServerContext sc = ServerContext.Current;
UserProfileManager upm = new UserProfileManager(sc);
UserProfile up = null;
//get current user's profile (visitor)
if (upm.UserExists(SPContext.Current.Web.CurrentUser.LoginName))
{
up =upm.GetUserProfile(SPContext.Current.Web.CurrentUser.LoginName);
SPWeb web = SPContext.Current.Web;
SPList userInformationList = web.Lists["User Information List"];
SPContext.Current runs outside the RunWithelevatedPrivileges elevated context. For more info see this blog post.
You're setting your SPWeb to SPContext.Current.Web, this doesn't have elevated privileges. Only SPWebs created from SPSites created inside the delegate are elevated.
So you need to replace
SPWeb web = SPContext.Current.Web;
with
SPWeb web = site.OpenWeb(SPContext.Current.Web.ID);
You're setting your SPWeb to SPContext.Current.Web this doesn't have elevated privileges.
Refer this post:
Related
I am trying to display full name of user from active directory. It works fine on my local. But when I publish this code to IIS on server it shows display name as null. What may be the issue? My account is using windows authentication.
using (var context = new PrincipalContext(ContextType.Domain))
{
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
var displayName = principal?.DisplayName;
}
I had to use HostingEnvironment.Impersonate() in order to access my AD properties on my IIS server. (It worked without it on local)
using (HostingEnvironment.Impersonate())
{
// your code
}
Also, you'd have to change your Application Pool's identity from "AppPoolIdentity" to "NetworkService".
I have a SharePoint solution with a custom application where a user should be able to change some properties in his own Active Directory object.
I am doing the following:
PrincipalContext ctx = ActiveDirectory.GetPrincipalContext("lab");
UserPrincipal user = ActiveDirectory.GetUserPrincipal(ctx, "Administrator");
user.DisplayName = user.DisplayName + DateTime.Now.ToString("ddMMyyyyHHmmss");
user.Save();
I am logged in to SharePoint as the domain administrator and i am trying to change my own DisplayName.
What is wrong with my code?
Update 20.04.2016
I have built a small Console Application with the following code:
static void Main(string[] args)
{
try
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "lab");
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "administrator");
DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry);
user.DisplayName = user.DisplayName + DateTime.Now.ToString("ddMMyyyyHHmmss");
user.Save();
Console.WriteLine("OK");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This works fine! That means normally, that the Authentication goes wrong or the user which is logged into SharePoint is not getting used to connect to AD and do the changes. If this could be the case, how could i find out with which user i am doing the operation?
Update 20.04.2016 - 2
I have now tried to put the username and password in the PrincipalContext contructor as below:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "lab", "administrator", "pass");
This works, too! That means now definitely, that the user which is logged in to SharePoint is not used to create the PrincipalContext. But why? Normally code is always executed in the context of the current user!?
How can i find out which user is used to create the PrincipalContext and how can i change it that the logged in user is getting used?
I had the same problem, I resolved it like this:
In IIS, in the advanced settings of my app -> In Identity I add my service account (example: domain\service-account)
In my active directory, I give to this service account full control on folder and sub-folder where I want to create/update user (you need to modify view to see security tab -> right click -> view -> advanced features)
If you already have that, check if your service account is not disabled
And now everything is working :)
Am trying to find the current logged user in sharepoint site workflow 2010 while creating a project. Based on the user, I would like to retrieve the current user's project manager. Every time am trying to retrieve current user name, it's giving System Account.
I even tried logging in as different user but still displaying System Account as the current user.
I tried following options :
SPUser user = workflowProperties.OriginatorUser;
SPUser user = SPContext.Current.Web.CurrentUser;
SPWeb web = SPContext.Current.Web;
SPUser user = web.CurrentUser;
SPContext.Current.Web.CurrentUser.LoginName;
But everything failed. Am sure that am doing something wrong. I don't know the correct procedure. Some procedures give me null or Object reference not set to an instance of the object or System Account details. I have even tried using elevated permission and its giving me null value.
SPSecurity.CodeToRunElevated elevatedSubmit = new SPSecurity.CodeToRunElevated(delegate
{
//SPUser user = SPContext.Current.Web.CurrentUser;
//string strAssignedTo = user.Name;
string sspURL = "http://localhost/PWA/default.aspx";
SPSite site = new SPSite(sspURL);
SPWeb web = site.OpenWeb();
SPUser theUser = web.CurrentUser;
string strUserName = theUser.Name;
});
SPSecurity.RunWithElevatedPrivileges(elevatedSubmit);
Am I supposed to add users explicitly as SPUser or any other changes before trying to retrieve current user via workflow ?
SharePoint 2010 Get Current Username / Logged in User
check this StackExchange answer as well
Get the current user interacting with a site workflow
if you are wanting to get the current user when you log in you can try something like this
SPWeb webSite = SPControl.GetContextWeb(SPContext);
SPUser spUser = webSite.CurrentUser;
string strUserName = spUser.LoginName;
using this line below will return the OriginatorUser however if you are not logged in as Admin you will get the System Account UserName
//This give the Login name e.g <domain>\<name>
workflowProperties.OriginatorUser.LoginName;
** Note ** I noticed that in your code you are trying to get / assign user twice
you should only need this line if you decide to use your code
SPUser user = SPContext.Current.Web.CurrentUser;
its seem to work :
SPUser user = this.workflowProperties.OriginatorUser;
RunWithElevatedPrivileges gives you system account privileges in addition to the privileges you would get with a reverto call.
is that code executed on SPSecurity.RunWithElevatedPrivileges method ??
Here is a another trick that i found :
string ModifiedbyUserName = Convert.ToString(workflowProperties.Item.GetFormattedValue("Modified By"));
see this : logged-in user in workflow
Helps it helps!!
I'm trying to add permissions for a user that is under a subsite in SharePoint. I was able to successfully set the permissions for the user on the root level, but I am not sure how to approach the problem for a lower level subsite. Below is what I have at the moment but it crashes although it shows no error building in VS. Any ideas would be great
foreach (SPWeb subSite in spSite2.RootWeb.GetSubwebsForCurrentUser())
{
if (subSite.Name == "templates")
{
Console.WriteLine("\nTEMPLATES SITE");
Console.Write("\nApplying 'Read' permission to App_user Account");
spRoleAssignment = new SPRoleAssignment(SPContext.Current.Web.Users[appUserAccount]);
spRoleAssignment.RoleDefinitionBindings.Add(SPContext.Current.Web.RoleDefinitions["Read"]);
SPContext.Current.Web.RoleAssignments.Add(spRoleAssignment);
SPContext.Current.Web.Update();
Console.ForegroundColor = ConsoleColor.Green;
Console.CursorLeft = Console.BufferWidth - 16; Console.WriteLine("Applied");
Console.ForegroundColor = ConsoleColor.Gray;
}
}
I'm not completely sure what you are trying to achieve nor where your code is supposed to be executed (console application or timer job or in a web part?).
I see the following problems:
You log to the console (which let's me assume your code runs in a console application), but you access the SPContext.Current, which is only available if your code runs in a HTTP request.
You are iterating over a collection of webs. But in your for-each body the SPContext.Current.Web is updated.
You do retrieve your web collection via the web.GetSubwebsForCurrentUser(), but are then changing permissions on these objects. This smells a little since updating permissions is an "admin task" and the the method GetSubwebsForCurrentUser is more likely to be used for a low level user context to avoid access denied exception. For instance to safely display a list of webs.
You do update permissions/roles on a web, but a check if the web has unique role assignments is missing.
You check for a web with the name "templates". Since GetSubwebsForCurrentUser is not recursive there can only be one web named "templates" in this collection. This web can be opened direclty => no need to waste resource by opening every sub web.
If your task is to set role permissions on a given web "templates" (which is a 1st level sub web of your root web) you can use the follwing code:
// Open the web directly since it is a direct child of the site collection.
// Use a using to properly release the resources
using (SPWeb web = spSite2.Open("templates"))
{
SPUser user = web.SiteUsers[appUserAccount];
SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Reader);
if (!web.HasUniqueRoleAssignments)
{
web.BreakRoleInheritance(true);
}
spRoleAssignment = new SPRoleAssignment(user);
spRoleAssignment.RoleDefinitionBindings.Add(roleDef);
web.RoleAssignments.Add(spRoleAssignment);
// No need to update the web when changing the permissions
}
Try to update roles in the subSite, not in the current web from SPContext?
AFAIK each SPWeb object have it's own roles assignments.
currently I'm trying to retrieve all the groups that is in my sharepoint site. After which, I need to know which users are in the group and the level of site permission for each user. I'm using WSS 3.0 , developing in C# (visual studio 2008).
Help really needed as I'm still new in this area. Thanks in advance!
Groups can be found like:
SPSite siteCollection = new SPSite("site url");
SPWeb site = siteCollection.OpenWeb();
foreach(SPGroup group in site.Groups){
Console.WriteLine(group.Name);
foreach(SPUser u in group.Users){
//will give you users in group, you can then grab the roles of the user
}
}
To find what permissions a role has:
SPSite oSiteCollection = SPContext.Current.Site;
using(SPWeb oWebsite = oSiteCollection.AllWebs["Site_Name"])
{
SPMember oMember = oWebsite.Roles["Role_Name"];
oWebsite.Permissions[oMember].PermissionMask =
SPRights.ManageLists | SPRights.ManageListPermissions;
}
The permissions matrix can be found here
If you are looking for code to work for using client object model, you may review the following links.
For getting the groups.
http://social.technet.microsoft.com/wiki/contents/articles/24075.how-to-get-sharepoint-user-group-names-in-a-netc-client-application-using-sharepoint-client-object-model.aspx
For getting the permission levels associated with groups.
http://social.technet.microsoft.com/wiki/contents/articles/24087.how-to-get-the-permission-levels-associated-with-sharepoint-user-groups-using-client-object-model-in-netc.aspx