How can I query graph.windows.net for accounts in our Azure AD that do have the email property set? I am asking for the query string, or even better a C# statement using ActiveDirectoryClient.
It doesn't seem possible to use $filter=email neq '' or other similar $filter construct to exclude users that don't have the email property set.
You can iterate all the Azure AD users and check if the users have a mail:
ActiveDirectoryClient activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
List<IUser> users = activeDirectoryClient.Users.ExecuteAsync().Result.CurrentPage.ToList();
var mailUsers = new List<IUser>();
foreach (IUser user in users)
{
if(user.Mail != null)
{
mailUsers.Add(user);
}
}
Please check the sample application at
https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console
Related
I am trying to run the sample at:
https://github.com/Azure-Samples/ms-identity-dotnetcore-b2c-account-management
And am receiving this error:
Enter command, then press ENTER: 7
Create a user with the custom attributes 'FavouriteSeason' (string) and 'LovesPets' (boolean)
Have you created the custom attributes 'FavouriteSeason' (string) and 'LovesPets' (boolean) in your tenant?
Code: Request_BadRequest
Message: One or more property values specified are invalid.
Inner error:
AdditionalData:
date: 2020-06-30T23:24:26
request-id: dad23cee-984b-439c-a943-9e1bc6be4c9b
ClientRequestId: dad23cee-984b-439c-a943-9e1bc6be4c9b
I have created the custom attributes and can clear see them in the tenant...it even returns their ids. I've setup the Graph access level appropriately (I believe).
Any ideas? Thank you!
In Code, you need to update Tenant id, client id, client secret and also give B2cExtensionAppClientId= “your application display name” in appsettings.json
You have to create two custom attributes in the B2C portal
I. FavouriteSeason (string)
II. LovesPets (boolean)
Use below code to create the user with the custom attribute
try
{
//Create user
var result = await graphClient.Users
.Request()
.AddAsync(new User
{
GivenName = "Casey",
Surname = "Jensen",
DisplayName = "Casey Jensen",
Identities = new List<ObjectIdentity>
{
new ObjectIdentity()
{
SignInType = "emailAddress",
Issuer ="AADCxPb2c.onmicrosoft.com",
IssuerAssignedId = "x#AADCxPb2c.onmicrosoft.com",
}
},
PasswordProfile = new PasswordProfile()
{
Password = b2c_ms_graph.Helpers.PasswordHelper.GenerateNewPassword(4, 8, 4)
},
PasswordPolicies = "DisablePasswordExpiration",
AdditionalData = extensionInstance
}) ;
Console.WriteLine(result);
string userId = result.Id;
Console.WriteLine(result.Id);
Console.WriteLine($"Created the new user. Now get the created user with object ID '{userId}'...");
Can find it on your registered App on Azure AD B2C:
Click on "API Permissions" on left panel.
Then Chose "APIs my organization uses".
You can find the value under name "b2c-extensions-app. Do not modify. Used by AADB2C for storing user data.".
We protect action with authorize attribute with specific role name this way
[Authorize(Roles="members, admin")]
suppose users and roles are mapped in db table. so when user login then how could i attach role with logged in user using identity.
here i am posting url and sample which show how people do the same in mvc4 with custom form authentication. just see the code and i hope surely understand what i am trying to do with asp.net mvc 5 using identity.
https://www.codeproject.com/Articles/408306/Understanding-and-Implementing-ASP-NET-Custom-Form
see this above url for custom form authentication with asp.net mvc 4
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//let us take out the username now
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
//let us extract the roles from our own custom cookie
string roles = DBHelper.GetUserRoles(username);
//Let us set the Pricipal with our user specific details
e.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
}
catch (Exception)
{
//somehting went wrong
}
}
}
}
i am working with asp.net mvc 5 & identity system. please help and guide me. thanks
You have to get logged in user id first
var UserName= await User.Identity.GetUserId()
then you can assign any role to that logged in user like
var _context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
UserManager.AddToRole("UserName", "UserRole");
I have successfully been able to share a OneDrive for Business file with a group using the Sharepoint CMOS API.
Like this:
context.Load(listItem, l => l.HasUniqueRoleAssignments);
context.ExecuteQuery();
if (!listItem.HasUniqueRoleAssignments)
{
listItem.BreakRoleInheritance(true, false);
}
var group = context.Web.SiteGroups.GetByName(groupName);
context.Load(context.Site.RootWeb, w => w.RoleDefinitions);
context.ExecuteQuery();
var roleTypeKind = readOnly ? RoleType.Reader : RoleType.Editor;
var role = context.Site.RootWeb.RoleDefinitions.FirstOrDefault(rd => rd.RoleTypeKind == roleTypeKind);
var roleDefCollection = new RoleDefinitionBindingCollection(context) { role };
listItem.RoleAssignments.Add(group, roleDefCollection);
context.ExecuteQuery();
But the problem is that group belongs to SiteGroups which is really local to one user. So if I have an Azure AD Group I cannot access it using the Sharepoint API.
I can find an Azure AD group using the GraphClient API like this:
var azuregroup = activeDirectoryClient.Groups
.Where(g=> g.DisplayName.Equals("groupname"))
.ExecuteAsync().Result.CurrentPage.ToList().First() as Group;
But how do I grant that group access to the file using an/any API ? It should be possible since it is possible in the OneDrive for Business UI.
It is not possible doing this
listItem.RoleAssignments.Add(azuregroup, roleDefCollection);
because the first parameter to Add has to be a Principal which the azuregroup is not.
Hope anybody can help - I have searched the internet for countless hours.
I have an account that has been persisted in a database using the User Principal Name (UPN) format: jdoe#domain.gobalx.com
I am working in a SharePoint environment that is Claims authenticated using the UPN format.
My problem is I need to get a UserProfile object for the persisted UPN account. I have tried the following but it doesn't work:
string upnAccount = "jdoe#domain.globalx.com";
SPServiceContext ctx = SPServiceContext.GetContext(SPContext.Current.Site);
UserProfileManager upm = new UserProfileManager(ctx);
UserProfile user = upm.GetUserProfile(upnAccount);
I keep getting: Microsoft.Office.Server.UserProfiles.UserNotFoundException: An error was encountered while retrieving the user profile
Does this mean that I have to convert the UPN account into a claim, and if so does anyone have an example on how to do that?
UserProfileManager UPM = null;
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
ServerContext serverContext = ServerContext.GetContext(site);
UPM = new UserProfileManager(serverContext);
foreach (UserProfile profile in UPM)
{
an = profile["AccountName"].Value;
title = profile["Title"].Value;
}
}
}
U can try this for get All userprofile. In foreach loop u can check for your fields and get perticular user details
In some cases under SharePoint sites with federated authentication there are no user profiles automatically created until you haven't setup synchronization. For this issue you may check if there already exists user profile for jdoe#domain.globalx.com via Central Admin.
Also your code must be run under impersonation, check the log for exception and try to use SPSecurity.RunWithElevatedPrivileges.
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;
}