SharePoint WebPart Permissions - security

Hi I am using the SharePoint namespace for a webpart and I encounter some permission errors when I try to use the System account. Is there a way I can use a defined user instead of the system account?
Right now I have:
SPUserToken sysToken = SPContext.Current.Site.SystemAccount.UserToken;
using (SPSite site = new SPSite(_SPSite, sysToken))
I want to be able to use an account on the domain instead of the System account, thanks for any advice.

You may need to use RunWithElevatedPermissions to get access to the System account to work, as per the following blog post:
http://solutionizing.net/2009/01/06/elegant-spsite-elevation/

You can use the SPUserCollection
SPContext.Current.Site.RootWeb.AllUsers
to get all of the users on the site, and get the SPUser from there. Once you have the SPUser you can get the UserToken.

What are you trying to do? If you don't use a token, the web will be opened with the same permissions as the current user
/* runs as user requesting the web part */
SPSite site = SPContext.Current.Web.site
or you can wrap it in the RunWithElevatedPrivileges delegate
/* runs with admin privileges */
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Web.Site.Url))
{
//do stuff
}
}
);

Related

SharePoint 2010 Access Denied - Logged in user doesn't have permission to view the mebership of this sharepoint group

I have a scenario in my custom visual web part where I need to check for logged in User is a member of sharepoint group(sharepoint groups or users are stored in a sharepoint list). Actually if logged in users exists in the list, he will be given Edit access in my custom web part.
Since I have created a group name "SharePoint_Owners" with group settings as 'Who can View Membership of this group' to 'Group Members', Site is throwing error as 'Access denied' as logged in user doesn't have permission to view. I get error when my code executes this,
SPGroup oGroup = oWebsite.SiteGroups[strgroup];///strgroup is a group name
foreach (SPUser oUser in oGroup.Users) { }
Site throws this error when I try to open page which consists my webpart.
Can any one suggest me how do i proceed? is there a way to resolve this programmatically without actually giving View permission to "Everyone" for each group??
I thought RunWithElevatedPrivileges does my work but have no luck!
please help
Try this:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
string siteURL = SPContext.Current.Site.Url;
using (SPSite safeSite = new SPSite(siteURL))
{
using (SPWeb safeWeb = safeSite.OpenWeb())
{
SPGroup group = safeWeb.Groups["SharePoint_Owners"];
bool isMember = safeWeb.IsCurrentUserMemberOfGroup(group.ID);
}
}
});

impersonate as different user inside the webpart code

I use the sharepoint lists as a database.
I want to somehow impersonate as different user inside the webpart code
and than as this user I will have both write and edit permission to the list.
My goal is to be able to have full premission only through the webpart code.
I am using MOSS 2007.
SPSecurity.RunWithElevatedPrivilieges() will execute your code as the system account, i.e. the account under which the application pool runs, which might or might not be what you want to do. For example, if you have a workflow attached to the list which is supposed to trigger when new items are added to the list, it will not fire if you insert a new list item under the credentials of the system account (this was a security fix introduced in SharePoint 2007 SP 1). In that case you will have to perform the insert operation under a different account that has the correct permissions on the list.
You can get the UserToken for any user using the following code:
SPUserToken userToken = null;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
{
userToken = web.AllUsers["domain\\username"].UserToken;
}
}
});
Replace the "domain\username" with the correct windows account name. Then you can pass this user token to one of the overloads of the SPSite object constructor to execute the code under this user's credentials like so:
using (SPSite site = new SPSite(SPContext.Current.Site.ID, userToken))
{
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
{
// This code will execute under the credentials of the userToken user
}
}
Hope this helps.
You are looking for SPSecurity.RunWithElevatedPrivileges Method.

Sharepoint UserProfileService

I've got a sharepoint site and a custom aspx portal, both under Windows Authentication.
With the same machine, it happens that my sharepoint site returning me my current login, while my custom aspx returning me my domain admin account instead.
Is there anyway that I could ensure both logins are the same? Otherwise, is there anyway to consume SPUserProfileService from a custom aspx portal?
Mainly, I need to have the custom aspx portal to get sharepoint logon id. Nevertheless, i could still trigger AccessDenied.aspx in sharepoint to prompt for logins.
When you say "Custom ASPX Portal", is it still hosted on the SharePoint Site?
In that case, how do you get the user? You can use SPContext.Current.Web.CurrentUser to get the user.
It seems that you are connecting from your custom aspx to SharePoint using your Domain Admin Account.
Could you please describe more about your custom aspx portal and the way you are reading the username?
However, you can check my article (Even though it is for FBA users, you may find the code snippet useful):
Possible ways to get logged in User Name & Handling Changes in FBA Users' Names if Membership Provider Name Changed
public string GetFlatUserName()
{
//First, be sure that the user is not anonymous user:
if (SPContext.Current == null || SPContext.Current.Web.CurrentUser == null)
return "Anonymous";
//Second, parse it:
else
{
string flatUserName = this.Page.User.Identity.Name;
if (flatUserName.Contains("\\"))
{
flatUserName = flatUserName.Substring(flatUserName.IndexOf("\\") + 1);
}
else if (flatUserName.Contains("|"))
{
flatUserName = flatUserName.Substring(flatUserName.IndexOf("|") + 1);
}
return flatUserName;
}
}

Cannot access site groups with user with manage hierarchy permissions

I have a custom form that lists the site groups and the users in each group.
the form has twi drop down lists: one to display the site's group and the other to display the users in that group.
when I log to the form with the administrator user it works fine.
But if I log in with a user with manage hierarchy permission level, it omly displays the info of the domain groups and if I try to access a sharepoint group I get an access denied error.
I use run with elevated permissions in my code
I really don't know what to do in this
thanks.
Two common mistakes when using RunWithElevatedPrivileges is:
Using the SPContext.Current.Web (or Site etc) won't change the identity of the web object, it is already in memory.
Declaring the SPWeb outside the delegate, with similar results of mistake 1
That said, try something like:
Guid siteId = SPContext.Current.Site.Id;
SPSecurity.RunWithElevatedPrivileges(() =>
using (SPSite elevatedSite = new SPSite(siteId))
using (SPWeb elevatedWeb = elevatedSite.RootWeb)
{
//impl
});

console application - object model - database persmission

I'm trying to run a console application that uses the SharePoint Object Model.
I'm getting the error Cannot open database "dbname" requested by the login. The login failed. Login failed for user 'DOMAIN\userid'.
Some place I have read that the user must have permission to the Content DB.
I can not find an article that explains what permissions to setup. I need this as ammunition to go to my Sys Admin guy to get the permission setup.
Where is there an article that explains that? I have searched google but with no luck.
RunWithElevatedPrivileges doesn't help because it just changes the thread user to the process identity - in a console application, this has no effect because they're the same. The "elevation" in an impersonated web context works because the process identity is the application pool account, which has db_owner on its content database.
If I ask that the account I'm using be given Full Control, under the Policies for Web Application, should that work?
Not according to Ishai Sagi: Object model code and stsadm fail with "Access Denied". In short, it seems db_owner permissions on the content database are required for a user to run object model code (including STSADM) without a web context.
Are you running the console application on the server itself? I assume so.
In this case it is likely to be a permissions issue with the account you are using (RDP?) on the server. The database error side of things can be misleading as you will need to be permissioned within SharePoint itself, which will then give permissions to the database.
I would get your sys admins to create a service account for you to use that can be granted the correct rights. (site collection administrator is often needed, but it depends on the code inside the console app. most do assume site collection admin rights though). you may get more mileage from looking at the application instructions (or if it is your own code just go for site collection admin)
Running a console app is a bit of a major though, so you may have better luck if you give the sysadmins the application to run and instructions... though I doubt you are running this on the prod box.
your user propably don't have permissions to access those lists or webs. You can run your code with elevated privilegies, but it can sometimes give you unexpected results.
Example of how elevated privilegies is used can be found here
Or you can set user unser who's account console app runs as site collection administrator.
Your code updated to run with elevated privilegies can look like this:
private static void DisplayAllLists(string site, string webToOpen)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using ( SPSite siteCollection = new SPSite(site) )
{
try
{
using (SPWeb web = siteCollection.OpenWeb(webToOpen))
{
SPListCollection lists = web.Lists;
foreach (SPList list in lists)
{
Console.WriteLine(string.Format("List Title: {0}", list.Title));
}
}
}
}
finally
{
siteCollection.RootWeb.Dispose();
Console.ReadLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: "+ex.Message);
}
}
Note: This code was written from top of my head, so maybe something is missing..you will have to try it

Resources