Check the Sharepoint user exists in AD - sharepoint

If a user is removed from AD, the user still exists in sharepoint. Now i want to check if a user exists in AD, so is there any sharepoint object model can do this?
Thanks in advance.

If the user is in the domain user Group, it collects all users under that user group and loops the list to that try to find the current user. If a user is found, it returns true, otherwise returns false.
Check this article Check Whether User Exists in Active Directory that include some security related issues to achieve the requirement.
// Get ad users in the groups. Since MOSS does
// not support nested groups
// this will always be a collection of AD users
// and groups
foreach (SPUser user in group.Users)
{
// Check if this is a Group
if (!user.IsDomainGroup)
{
// Verify if the user name matches the user name in group
if (user.LoginName.ToUpper().Equals(upperCaseUserName))
{
// if a match is confirmed, return from the method.
// There is no need to continue
userIsInGroup = true;
return;
}
}
else {
// If the AD entity is a User Group,
// then check for users in that group
if (IsUserInADGroup(web, user.LoginName,
username, out reachedMax))
{
userIsInGroup = true;
return;
}
}
Hope this help..

Related

Accessing Azure Assigned Groups via Razor or Controllers in ASP.NET Core

My ASP.NET Core web app is using an Azure Active Directory tenant and using OpenID Connect to sign-in users. I'm able to login successfully and I'm able to view the full list of Claims on a user with the following code:
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
My security token includes the following "groups":
{
type: "groups",
value: "e8f1a447-336a-47bb-8c26-79f1183f989f"
},
{
type: "groups",
value: "38421450-61ba-457b-bec2-e908d42d6b92"
}
I'm having trouble trying to determine how to capture these groups to perform logic in my Razor views and controllers. For example, I need to hide/show a button in my Razor view depending on whether a user is in a specific group. In my controllers I may need to allow/deny an action.
What is the standard/preferred method to do this in ASP.NET Core?
When Azure AD adds applicable group claims to the token it issues for users, the value for the group claim will be the Object ID of the security group and not the name of the security group(a group’s name can be changed in the directory so it is not a reliable identifier for the group ) .You could check whether the user’s existence in the security group in controller by :
// Look for the groups claim for the 'Dev/Test' group.
const string devTestGroup = "99dbdfac-91f7-4a0f-8eb0-57bf422abf29";
Claim groupDevTestClaim = User.Claims.FirstOrDefault(
c => c.Type == "groups" &&
c.Value.Equals(devTestGroup, StringComparison.CurrentCultureIgnoreCase));
// If the app has write permissions and the user is in the Dev/Test group...
if (null != groupDevTestClaim)
{
//
// Code to add the resource goes here.
//
ViewBag.inGroup = true;
}
else
{
ViewBag.inGroup = false;
}
Then in view , you could control whether show/hide links/buttons :
#if (ViewBag.inGroup)
{
<div>show/hide button/link goes here</div>
}
In your AppSettings.json, add your group's name and GUID object ID:
"AzureAdAuthorizationGroups": {
"MyGroup": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
}
Next, hook up authorisation in your Startup.cs ConfigureServices method
services.AddAuthorization(options => {
options.AddPolicy("MyGroup", policyBuilder => policyBuilder.RequireClaim("groups", Configuration.GetValue<string>("AzureAdAuthorizationGroups:MyGroup")));
});
Finally in your view:
#if ((await AuthorizationService.AuthorizeAsync(User, "MyGroup")).Succeeded)
{
// ...
}

SPuser to find group membership

I have a code in which I have to check if a user is a part of a certain group (lets say "GroupA").
I have the user details stored in the Sharepoint variable SPUser. Now I need to check if this user is a part of GroupA and then take some action.
How can I achieve this?
Source : How to check if a user exists in a group
you can use following extension method, like this:
public static bool InGroup(this SPUser User, string GroupName)
{
return User.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == GroupName.ToLower());
}
Then call it like this:
bool inGroup = spuser.InGroup("GroupName");
If you want to check the current user then another approach can be like this:
From: Check user already exist in specified SharePoint Group
SPWeb web = SPContext.Current.Web;
SPGroupCollection webGroups = web.Groups;
foreach (SPGroup group in webGroups)
{
//Checking the group
if (group.ContainsCurrentUser)
{
// perform action
}
else
{
//perform action
}
}
For More Reference:
Tell if user exists in SharePoint Group through web service

how check if CurrentUser is member of group AD?

This code is not suitable:
web.IsCurrentUserMemberOfGroup(web.Groups["Namegruop"].ID);
You need to distinguish between AD security group membership and SharePoint group membership.
In order to check AD security membership you can use System.Security.Principal.WindowsPrincipal.IsInRole. You do not need to use the SharePoint API:
using(WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal p = new WindowsPrincipal(identity);
if (p.IsInRole("DOMAIN\\GroupName")) // Alternative overloads with SecurityIdentifier available
{
// ...
}
}
To check if the current user is member of a SharePoint group you can use the SharePoint API:
SPWeb web = // ...
SPGroup group = web.SiteGroups["GroupName"];
if (group.ContainsCurrentUser)
{
// ...
}

In SharePoint, is it possible to programmatically get the current list of users associated with the "nt authority/authenticated users" group?

In SharePoint, I'd like to find out all of the users who have been given access to a site.
If the user is directly granted permissions, granted permissions via a SharePoint group, or granted permissions via a domain group; then I'm able to get the necessary information.
However, if the user is granted permissions via the "authenticated users" group, I am not sure how to find the list of users associated with that group.
Is this possible?
This is more of a .Net question than a Sharepoint question. Yes, you can do this - use the AD APIs to query your domain controller for a list of all users. Here is some code to get you started on programmatic AD access:
http://www.codeproject.com/KB/system/everythingInAD.aspx
You could try to do a query for all objects in AD that are Users.
Please note that this will not list any users outside of AD that might have access to the Sharepoint content. Also, if you have multiple domains, be sure to query all of the AD domains that might have access to the Sharepoint server.
Kyle, thanks for the response.
Using that information, I came up with the following to get all of the users in all of the domains:
private List<Principal> GetAllAuthenticatedUsers()
{
List<Principal> users = new List<string>();
foreach (string domain in GetAllDomains())
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, domain);
// Create search condition for all enabled users
PrincipalSearcher searcher = new PrincipalSearcher();
UserPrincipal user = new UserPrincipal(context);
user.Enabled = true;
user.Name = "*";
searcher.QueryFilter = user;
// Get the users
System.DirectoryServices.AccountManagement.PrincipalSearchResult<Principal> results = searcher.FindAll();
foreach (Principal principal in results)
{
users.Add(principal);
}
}
catch
{
}
}
return users;
}
private static List<string> GetAllDomains()
{
List<string> domains = new List<string>();
using (Forest forest = Forest.GetCurrentForest())
{
foreach (Domain domain in forest.Domains)
{
domains.Add(domain.Name);
}
}
return domains;
}

How can I list all SPUser objects in a SPGroup?

I need to retrieve all SPUser's from a SPGroup. Unfortunately, the group may contain Active Directory groups, so a simple SPGroup.Users is not enough (I'd just get a single SPUser for the AD group, with the IsDomainGroup property set to true).
Does anyone have a good idea how can I obtain a list of all SPUser's, descending into any Active Directory groups contained in a SPGroup? Is there an alternative to SPGroup.ContainsCurrentUser that takes a SPUser parameter?
Based on a blog post I found, I have written the following code:
private static List<SPUser> ListUsers(SPWeb web, SPPrincipal group)
{
try
{
web.Site.CatchAccessDeniedException = false;
var users = new List<SPUser>();
foreach(SPUser user in web.SiteUsers)
{
using(var userContextSite = new SPSite(web.Site.ID, user.UserToken))
{
try
{
using (var userContextWeb = userContextSite.OpenWeb(web.ID))
{
try
{
if (userContextWeb.SiteGroups[group.Name]
.ContainsCurrentUser)
users.Add(user);
}
catch (SPException)
{
// group not found, continue
}
}
}
catch(UnauthorizedAccessException)
{
// user does not have right to open this web, continue
}
}
}
return users;
}
finally
{
web.Site.CatchAccessDeniedException = true;
}
}
I don't like the fact that I have to impersonate every single user, and this code will only find AD users that have already been imported into SharePoint (so an SPUser exists for them), but that's good enough for me.
Unfortunately, it may be the case that not every member of the AD group has a corresponding SPUser object in the site (yet).
In this scenario, I'd enumerate all the members of the active directory group, and force them into the site with the SPWeb's EnsureUser() method, which returns an SPUser, and creates a new one if it doesn't already exist in the site.
For guidance on enumerating active directory members, see Get List of Users From Active Directory In A Given AD Group.

Resources