using Microsoft.Azure.ActiveDirectory.GraphClient; using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions; using Microsoft.IdentityModel.Clients.ActiveDirectory; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tango.Web.ActiveDirectory { public class ActiveDirectoryManager { private String _service_root = $"https://login.microsoftonline.com/{WebConfig.TENANT_ID}"; public AuthenticationResult ValidateUserCredentials(String email, String password) { var authContext = new AuthenticationContext(_service_root); authContext.TokenCache.Clear(); UserCredential userCredential = new UserPasswordCredential(email, password); AuthenticationResult authResult = authContext.AcquireTokenAsync("https://graph.windows.net/", WebConfig.CLIENT_ID, userCredential).Result; return authResult; } private AuthenticationResult GetAppAuthenticationResult() { var authContext = new AuthenticationContext(_service_root); ClientCredential clientCredentials = new ClientCredential(WebConfig.CLIENT_ID, WebConfig.APP_SECRET); AuthenticationResult authResult = authContext.AcquireTokenAsync("https://graph.windows.net/", clientCredentials).Result; return authResult; } //public List GetUserGroups(String email) //{ // var authResult = GetAppAuthenticationResult(); // ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(new Uri($"https://graph.windows.net/{WebConfig.TENANT_ID}"), async () => await Task.FromResult(authResult.AccessToken)); // var user = activeDirectoryClient.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); //} //public bool CanUserAccessCurrentEnvironment(String email) //{ // var groups = GetUserGroups(email); // return groups.Exists(x => x.DisplayName == WebConfig.ENVIRONMENT_GROUP); //} } }