using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.ActiveDirectory.GraphClient; using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions; using Microsoft.Azure.Management.Fluent; using Microsoft.IdentityModel.Clients.ActiveDirectory; namespace Tango.AzureUtils.ActiveDirectory { public class ActiveDirectoryManager : AzureUtilsComponentBase { private AuthenticationResult _authResult; private ActiveDirectoryClient _adClient; #region Constructors /// /// Initializes a new instance of the class. /// /// The azure instance. public ActiveDirectoryManager(IAzure azure) : base(azure) { } #endregion #region Private Methods private ActiveDirectoryClient GetActiveDirectoryClient() { if (_adClient == null) { var credentials = AzureUtilsAuthenticationFactory.GetGlobalCredentials(); _adClient = new ActiveDirectoryClient(new Uri($"https://graph.windows.net/{credentials.TenantID}"), async () => await Task.FromResult(_authResult.AccessToken)); } return _adClient; } #endregion #region Public Methods /// /// Authenticates using application credentials. /// /// The credentials. /// public async Task Authenticate(AzureUtilsCredentials credentials) { if (_authResult == null) { var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{credentials.TenantID}"); ClientCredential clientCredentials = new ClientCredential(credentials.ClientID, credentials.ClientSecret); _authResult = await authContext.AcquireTokenAsync("https://graph.windows.net/", clientCredentials); } } /// /// Authenticates using an AD account. /// /// The email. /// The password. /// public async Task Authenticate(String email, String password) { OnProgress(AzureUtilsStage.ActiveDirectory, $"Authenticating with active directory graph..."); if (_authResult == null) { var credentials = AzureUtilsAuthenticationFactory.GetGlobalCredentials(); var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{credentials.TenantID}"); authContext.TokenCache.Clear(); UserCredential userCredential = new UserPasswordCredential(email, password); _authResult = await authContext.AcquireTokenAsync("https://graph.windows.net/", "ec612854-7abc-457b-808a-5d0c5ba80c57", userCredential); } } /// /// Determines whether the specified group name exists. /// /// Name of the group. /// public async Task IsGroupExists(String groupName) { try { var client = GetActiveDirectoryClient(); var g = await client.Groups.Where(x => x.DisplayName == groupName).Take(1).ExecuteSingleAsync(); return g != null; } catch { return false; } } /// /// Adds the specified group. /// /// Name of the group. /// public async Task AddGroup(String groupName) { OnProgress(AzureUtilsStage.ActiveDirectory, $"Creating group '{groupName}'..."); var client = GetActiveDirectoryClient(); await client.Groups.AddGroupAsync(new Group() { DisplayName = groupName, MailEnabled = false, MailNickname = Guid.NewGuid().ToString().ToLower(), SecurityEnabled = true }); } /// /// Removes the specified group. /// /// Name of the group. /// public async Task RemoveGroup(String groupName) { OnProgress(AzureUtilsStage.ActiveDirectory, $"Removing group '{groupName}'..."); var client = GetActiveDirectoryClient(); var g = await client.Groups.OfType().Where(x => x.DisplayName == groupName).Take(1).ExecuteSingleAsync(); await g.DeleteAsync(); } /// /// Adds the specified user to the specified group. /// /// Name of the group. /// The user email. /// public async Task AddUserToGroup(String groupName, String userEmail) { OnProgress(AzureUtilsStage.ActiveDirectory, $"Adding environment group user '{userEmail}'..."); var client = GetActiveDirectoryClient(); List groups = new List(); var user = await client.Users.Where(x => x.UserPrincipalName == userEmail).ExecuteSingleAsync(); var g = await client.Groups.Where(x => x.DisplayName == groupName).Take(1).ExecuteSingleAsync(); var gg = g as Group; gg.Members.Add(user as DirectoryObject); await gg.UpdateAsync(); } /// /// Gets all users. /// /// public async Task> GetAllUsers() { OnProgress(AzureUtilsStage.ActiveDirectory, $"Retrieving active directory users..."); var client = GetActiveDirectoryClient(); List users = new List(); var userPages = await client.Users.OfType().ExecuteAsync(); do { List directoryObjects = userPages.CurrentPage.ToList(); foreach (User u in directoryObjects) { users.Add(u); } userPages = await userPages.GetNextPageAsync(); } while (userPages != null); return users; } public List GetUserGroups(String email) { var client = GetActiveDirectoryClient(); var user = client.Users.Where(x => x.UserPrincipalName == email).ExecuteSingleAsync().Result; var userFetcher = (IUserFetcher)user; List groups = new List(); IPagedCollection pagedCollection = userFetcher.MemberOf.ExecuteAsync().Result; do { List directoryObjects = pagedCollection.CurrentPage.ToList(); foreach (IDirectoryObject directoryObject in directoryObjects) { if (directoryObject is Group) { var group = directoryObject as Group; groups.Add(group); } } pagedCollection = pagedCollection.GetNextPageAsync().Result; } while (pagedCollection != null); return groups; } public bool IsUserMemberOf(String group, String email) { return GetUserGroups(email).Exists(x => x.DisplayName == group); } #endregion } }