Find Admin of a spdocument library - c#

I have a document library which is not inherting the site permission (Custom permission is set).Now i want to find out who has administator permission to this library using C#.
I need to list out user id which i have admin rights.
Thanks,

There is no such thing as a List Administrator. But you can get the users and groups with manage lists permissions though:
SPList list = // get your list
IEnumerable<SPPrincipal> admins = list.RoleAssignments.Cast<SPRoleAssignment>()
.Where(ra =>
ra.RoleDefinitionBindings.Cast<SPRoleDefinition>()
.Any(r => (r.BasePermissions & SPBasePermissions.ManageLists) == SPBasePermissions.ManageLists))
.Select(ra => ra.Member);
Update:
Permissions on a SPFolder can be checked via the corresponding SPListItem. This can be retrieved via the SPFolder.Item property. Since both, the SPListItem and the SPList, inherit from the SPSecurableObject the check for the SPListItem is the same as described above.
To distinguish SPUser from SPGroup simply check the type of SPRoleAssigment.Member:
IEnumerable<SPUser> adminUsers = admins.OfType<SPUser>();
Be aware that a SPUser object can represent an AD security group. This can be checked via the SPUser.IsDomainGroup property.

Related

c# application authorization based on Windows current user

I write a small application and I need to add some authorization security tips.
Simple Example:
I have a WinForm that contain two buttons: btnAdd and btnDelete. I want that:
if the current user is in the Administrator group, both the two buttons above will be displayed
else (if not in the Administrator group (like like guess account)) only btnAdd will be displayed.
How can I do that
You should be able to construct a WindowsPrincipal object, then just check if the user is in the role you expect, and use the return value to set the button to visible or not. Something like the below
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
// using WindowsBuiltInRole.Administrator or "BUILTIN\\Administrators" should work
btnAdd.Visible = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
The updated code works, I've tested this, where I'm a local admin, since you want to test the current user, WindowsIdentity.GetCurrent() is actually cleaner.
If you need to confirm whether or not you are an admin on the machine, you can either check the group membership through MMC, but if there is any domain groups involved and you don't have access you won't be able to check this through MMC unless you have access to AD.
A sure way to verify if a user is a member of group is running the below in a command prompt window
Get members of local Administrators group:
net localgroup administrators
Get members of the domain group: this is necessary if for example, mydomain\WorkstationAdmins is a member of the local Administrators group and userId is a member of mydomain\WorkstationAdmins (thus an admin of the wokstation)
net group "WorkstationAdmins" /domain

Why UserPrincipal.Enabled returns different values?

I am trying to determine if a user account in AD is enabled. For this I use the following code:
string domain = "my domain";
string group = "my security group";
string ou = "my OU";
//init context
using (var cnt= new PrincipalContext(ContextType.Domain, domain))
{
//find the necessary security group
using (GroupPrincipal mainGroup
= GroupPrincipal.FindByIdentity(cnt, IdentityType.Guid, group))
{
if (mainGroup != null)
{
//get the group's members
foreach (var user in mainGroup.GetMembers()
.OfType<UserPrincipal>()
.Where(u => u.DistinguishedName.Contains(ou)))
{
//ensure that all the info about the account is loaded
//by using FindByIdentity as opposed to GetMembers
var tmpUser= UserPrincipal.FindByIdentity(cnt,
user.SamAccountName);
//actually I could use `user` variable,
//as it gave the same result as `tmpUser`.
//print the account info
Console.WriteLine(tmpUser.Name + "\t" +
tmpUser.Enabled.HasValue + "\t" +
tmpUser.Enabled.Value);
}
}
}
}
The problem is, when I run this code under an administrative account, I get the real result, while when I run it under a non-priviledged account, user.Enabled returns false for some of the accounts, while it should be true.
The only similar q&a I managed to find are
UserPrincipal.Enabled returns False for accounts that are in fact enabled?
Everything in Active Directory via C#.NET 3.5 (Using System.DirectoryServices.AccountManagement)
which do not help here.
Why is that so? What are my options to get this info under a non-priviledged account?
Here is another approach: How to determine if user account is enabled or disabled:
private bool IsActive(DirectoryEntry de)
{
if (de.NativeGuid == null)
return false;
int flags = (int)de.Properties["userAccountControl"].Value;
if (!Convert.ToBoolean(flags & 0x0002))
return true;
else
return false;
}
Same approach is described in Active Directory Objects and C#.
However when running under an unpriviledged user account, userAccountControl attribute is null and it's not possible to determine the state of the account.
The workaround here is to use PrincipalContext Constructor, specifying the credentials of a user with enough priviledges to access AD.
It stays unclear to me, why the unpriviledged user had access to AD at all, and couldn't get values of some certain account attributes. Probably this has nothing to do with C#, and should be configured in AD...
You'll need to delegate permissions in Active Directory for the accounts that will be performing the AD queries. This is what I had to do for my applications to work (though we are performing other administrative tasks on user accounts).
Check Here for instructions on how to delegate permissions(or see blockquote below).
You may referred the following procedure to run the delegation:
Start the delegation of control wizard by performing the following steps:
Open Active Directory Users and Computers.
In the console tree, double click the domain node.
In the details menu, right click the organizational unit, click delegate control, and click next.
Select the users or group to which you want to delegate common administrative tasks. To do so, perform the following steps:
On the Users or Groups page, click Add.
In the select Users, computers or Groups, write the names of the users and groups to which you have to delegate control of the organizational unit, click OK. And click next.
Assign common tasks to delegate. To do so perform the following common tasks.
On the tasks to delgate page, click delegate the following common tasks.
On the tasks to delegate page, select the tasks you want to delegate, and click OK. Click Finish
For Example: To delegate administrator to move user/computer objects, you can use advance mode in AD User and Computer and run delegation. It should have write privilege in both OU for the object moving. For writing new values, the administrators account should have delegated values on the user account (Full privilege in specific OU as well.
Something else worth looking into is if the accounts have the userAccountControl attribute. I've heard that accounts missing this attribute may not report correctly. In most scenarios this attribute should be set to NormalAccount.

Sharepoint 2010, Determine access to SPListItem based on a Current User

i am using a CAML Queryy to get all the list items that are cotains a ContentType, but i also need to know if the Current user, has permissions to see that file.
That part i do not know how can i check it.
i use this exmpla as reference of how to get the items related to a content type.
https://sharepoint.stackexchange.com/questions/14566/how-to-find-all-documents-of-a-certain-content-type
Thanks.
Per default in SharePoint our code runs impersonated as the user executing the web request. Thus the items returned by the CAML query are already security trimmed. Meaning, the result set only contains items the current user is allowed to "see".
Under some circumstances you are required to execute the CAML query with system priveliges. To do so the SPSite object has to be opend with the system account token:
using (SPSite elevatedSite = new SPSite("http://server-url", SPUserToken.SystemAccount))
{
// open web; list;
// execute caml query with system account priveliges.
}
In that case you could check / ensure permissions on a certain list item with the method DoesUserHavePermissions:
SPListItem item = //...
if (item.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser, SPBasePermissions.ViewListItems))
{
// futher actions if user has permission goes here.
}
Important to note is that you have to call the overload of the DoesUserHavePermissions with the SPUser argument. The overload without will use the "current user" of the site. Which is the system account since the site was opened with the system account token.

Querying LDAP for Usergroup of Specific User

I have to check usergroups of LDAP Active Directory for a specific user in C#. Mean I pass this username to a method and it returns me list of group from that user belongs. Can You Please help me in this. Im Searching alot But Everytime get new error.
LDAP Path: 192.168.1.4
Domain Name: Arslan
UserName: ArslanP
Password: testad
Since you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
Basically, add a reference to the assembly System.DirectoryServices.AccountManagement, and then you can define a domain context and easily find users and/or groups in AD:
using System.DirectoryServices.AccountManagement;
public List<GroupPrincipal> GetGroupsForUser(string username)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();
// set up domain context - if you do a lot of requests, you might
// want to create that outside the method and pass it in as a parameter
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find user by name
UserPrincipal user = UserPrincipal.FindByIdentity(username);
// get the user's groups
if(user != null)
{
foreach(GroupPrincipal gp in user.GetAuthorizationGroups())
{
result.Add(gp);
}
}
return result;
}
The new S.DS.AM makes it really easy to play around with users and groups in AD:
This related question may help you:
Get List of Users From Active Directory In A Given AD Group
It asks the reverse question, which is how to qet a list of users when you know the group, but other answers may be of use to you as well.
See also the answer to this question:
How to get all the AD groups for a particular user?

Sharepoint - Retrieving user group and permission rights programmatically

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

Categories

Resources