public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication(Guid tenantId) { Uri servicePointUri = new Uri(ResourceUrl); Uri serviceRoot = new Uri(servicePointUri, tenantId.ToString()); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, GetTokenForApplicationAsync); return activeDirectoryClient; }
public async static Task GetDirectoryObjects(List<string> objectIds, List<Group> groups, List<DirectoryRole> roles, List<User> users) { string userObjectId = ClaimsPrincipal.Current.FindFirst(Globals.ObjectIdClaimType).Value; // MULTITENANT - need to formulate GraphServiceRoot from user's tenant instead of app's tenant Uri graphServiceRoot = new Uri(ConfigHelper.GraphResourceId + "/" + ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value); ActiveDirectoryClient graphClient = new ActiveDirectoryClient(graphServiceRoot, async () => { return GraphHelper.AcquireToken(userObjectId); }); int batchCount = 0; List<Task<IBatchElementResult[]>> requests = new List<Task<IBatchElementResult[]>>(); List<IReadOnlyQueryableSetBase<IDirectoryObject>> batch = new List<IReadOnlyQueryableSetBase<IDirectoryObject>>(); IEnumerator<string> idIndex = objectIds.GetEnumerator(); IEnumerator<string> nextId = objectIds.GetEnumerator(); nextId.MoveNext(); while (idIndex.MoveNext()) { string thisId = idIndex.Current; // for delegate capture batch.Add(graphClient.DirectoryObjects.Where(o => o.ObjectId.Equals(thisId))); batchCount++; if (!nextId.MoveNext() || batchCount == 5) { requests.Add(graphClient.Context.ExecuteBatchAsync(batch.ToArray())); batchCount = 0; batch.Clear(); } } IBatchElementResult[][] responses = await Task.WhenAll<IBatchElementResult[]>(requests); foreach (IBatchElementResult[] batchResult in responses) { foreach (IBatchElementResult query in batchResult) { if (query.SuccessResult != null && query.FailureResult == null) { if (query.SuccessResult.CurrentPage.First() is Group) { Group group = query.SuccessResult.CurrentPage.First() as Group; groups.Add(group); } if (query.SuccessResult.CurrentPage.First() is DirectoryRole) { DirectoryRole role = query.SuccessResult.CurrentPage.First() as DirectoryRole; roles.Add(role); } if (query.SuccessResult.CurrentPage.First() is User) { User user = query.SuccessResult.CurrentPage.First() as User; users.Add(user); } } else { throw new Exception("Directory Object Not Found."); } } } return; }
// GET: UserProfile public async Task<ActionResult> Index() { string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; try { Uri servicePointUri = new Uri(graphResourceID); Uri serviceRoot = new Uri(servicePointUri, tenantID); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetTokenForApplication()); // use the token for querying the graph to get the user details var result = await activeDirectoryClient.Users .Where(u => u.ObjectId.Equals(userObjectID)) .ExecuteAsync(); IUser user = result.CurrentPage.ToList().First(); return View(user); } catch (AdalException) { // Return to error page. return View("Error"); } // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token catch (Exception) { return View("Relogin"); } }
private ActiveDirectoryClient GetClient() { Uri baseServiceUri = new Uri(ConfigurationManager.AppSettings["AzureGraphURL"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(new Uri(baseServiceUri, ConfigurationManager.AppSettings["O365Domain"]), async () => { return await GetAccessToken(); }); return activeDirectoryClient; }
// GET: UserProfile public async Task<ActionResult> Index() { string clientId = ConfigurationManager.AppSettings["ida:ClientID"]; string appKey = ConfigurationManager.AppSettings["ida:Password"]; string graphResourceID = "https://graph.chinacloudapi.cn"; GraphSettings graphSettings = new GraphSettings(); graphSettings.ApiVersion = "2013-11-08"; graphSettings.GraphDomainName = "graph.windows.net"; string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; try { // use the token for querying the graph Guid ClientRequestId = Guid.NewGuid(); ActiveDirectoryClient graphClient = new ActiveDirectoryClient( new Uri(graphResourceID + '/' + tenantID), async () => getTokenForGraph(tenantID, signedInUserID, userObjectID, clientId, appKey, graphResourceID)); IPagedCollection<IUser> users = await graphClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); return View((User)users.CurrentPage.First()); } // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token catch (Exception ee) { ViewBag.ErrorMessage = "AuthorizationRequired"; return View(); } }
/// <summary> /// Gets all groups for a given user /// </summary> /// <param name="azureClient">An authenticated ActiveDirectoryClient</param> /// <param name="user">A resolved User object</param> private static void GetAllGroupsForUser(ActiveDirectoryClient azureClient, IUser user) { Console.WriteLine(""); Console.WriteLine("Listing groups for " + user.DisplayName); IUserFetcher retrievedUserFetcher = (User)user; //access through the MemberOf collection IPagedCollection<IDirectoryObject> pagedCollection = retrievedUserFetcher.MemberOf.ExecuteAsync().Result; do { List<IDirectoryObject> directoryObjects = pagedCollection.CurrentPage.ToList(); foreach (IDirectoryObject directoryObject in directoryObjects) { if (directoryObject is Group) { Group group = directoryObject as Group; Console.WriteLine(" Group: {0}", group.DisplayName); //add to parent collection if you need to extract them } //removed to simplify //if (directoryObject is DirectoryRole) //{ // DirectoryRole role = directoryObject as DirectoryRole; // Console.WriteLine(" Role: {0} Description: {1}", role.DisplayName, role.Description); //} } pagedCollection = pagedCollection.GetNextPageAsync().Result; } while (pagedCollection != null && pagedCollection.MorePagesAvailable); }
public static string GetDisplayNameForADObject(Guid id, ActiveDirectoryClient adClient) { string displayName = ""; string upnOrSpn = ""; if (adClient == null || id == Guid.Empty) return displayName; try { var obj = adClient.GetObjectsByObjectIdsAsync(new[] { id.ToString() }, new string[] { }).GetAwaiter().GetResult().FirstOrDefault(); if (obj != null) { if (obj.ObjectType.Equals("user", StringComparison.InvariantCultureIgnoreCase)) { var user = adClient.Users.GetByObjectId(id.ToString()).ExecuteAsync().GetAwaiter().GetResult(); displayName = user.DisplayName; upnOrSpn = user.UserPrincipalName; } else if (obj.ObjectType.Equals("serviceprincipal", StringComparison.InvariantCultureIgnoreCase)) { var servicePrincipal = adClient.ServicePrincipals.GetByObjectId(id.ToString()).ExecuteAsync().GetAwaiter().GetResult(); displayName = servicePrincipal.AppDisplayName; upnOrSpn = servicePrincipal.ServicePrincipalNames.FirstOrDefault(); } } } catch { // Error occured. Don't get the friendly name } return displayName + (!string.IsNullOrWhiteSpace(upnOrSpn) ? (" (" + upnOrSpn + ")") : ""); }
public async Task<bool> AuthenticateAsync() { await GetConfigAsync(); // prompts the user for authentication _AuthenticationResult = await _Authenticator.Authenticate(_TenantAuthority, _ResourceUri, _AzureAuthenticationClientId, _ReturnUri); var accessToken = await GetTokenAsync(); // instantiate an ActiveDirectoryClient to query the Graph API var activeDirectoryGraphApiClient = new ActiveDirectoryClient( new Uri(new Uri(_ResourceUri), _AzureGraphApiClientId), () => Task.FromResult<string>(accessToken) ); // query the Azure Graph API for some detailed user information about the logged in user //This is done differently based on platform because if this is not awaited in iOS, it crashes //the app. Android is done this way to correct login issues that were previously occurring. if (Xamarin.Forms.Device.OS == TargetPlatform.Android) { Task.Run(() => { LogUserInfo(activeDirectoryGraphApiClient); }); } else { await Task.Run(async () => { LogUserInfo(activeDirectoryGraphApiClient); }); } return true; }
public async Task<bool> AuthenticateAsync() { await GetConfigAsync(); // prompts the user for authentication _AuthenticationResult = await _Authenticator.Authenticate(_TenantAuthority, _ResourceUri, _AzureAuthenticationClientId, _ReturnUri); var accessToken = await GetTokenAsync(); // instantiate an ActiveDirectoryClient to query the Graph API var activeDirectoryGraphApiClient = new ActiveDirectoryClient( new Uri(new Uri(_ResourceUri), _AzureGraphApiClientId), () => Task.FromResult<string>(accessToken) ); // query the Azure Graph API for some detailed user information about the logged in user var userFetcher = activeDirectoryGraphApiClient.Me.ToUser(); var user = await userFetcher.ExecuteAsync(); // record some info about the logged in user with Xamarin Insights Insights.Identify( _AuthenticationResult.UserInfo.UniqueId, new Dictionary<string, string> { { Insights.Traits.Email, user.UserPrincipalName }, { Insights.Traits.FirstName, user.GivenName }, { Insights.Traits.LastName, user.Surname }, { "Preferred Language", user.PreferredLanguage } } ); return true; }
public Group GetADGroup(ActiveDirectoryClient ADClient, string GroupNameSearchString, Logger Logger) { List<IGroup> foundGroups = null; try { Logger.Debug(string.Format("Searching/Fetching AD Group {0}", GroupNameSearchString)); foundGroups = ADClient.Groups .Where(group => group.DisplayName.StartsWith(GroupNameSearchString)) .ExecuteAsync().Result.CurrentPage.ToList(); } catch (Exception ex) { Console.WriteLine("Error when fetching group from Azure Active Directory {0} {1}", ex.Message, ex.InnerException != null ? ex.InnerException.Message : ""); Logger.Error(String.Format("Error when fetching group from Azure Active Directory {0} {1}", ex.Message, ex.InnerException != null ? ex.InnerException.Message : "")); } if (foundGroups != null && foundGroups.Count > 0) { return foundGroups.First() as Group; } else { return null; } }
public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication(string token) { Uri servicePointUri = new Uri(Configuration.GraphResourceId); Uri serviceRoot = new Uri(servicePointUri, Configuration.Tenant); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await Task.Run(() => token)); return activeDirectoryClient; }
/// <summary> /// Get Active Directory Client for Application. /// </summary> /// <returns>ActiveDirectoryClient for Application.</returns> public ActiveDirectoryClient GetActiveDirectoryClientAsApplication(IConfiguration Configuration) { Uri servicePointUri = new Uri(Configuration.ResourceURL); Uri serviceRoot = new Uri(servicePointUri, Configuration.TenantID); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await AcquireTokenAsyncForApplication(Configuration)); return activeDirectoryClient; }
/// <summary> /// Get Active Directory Client for Application. /// </summary> /// <returns>ActiveDirectoryClient for Application.</returns> public static ActiveDirectoryClient GetActiveDirectoryClient() { Uri baseServiceUri = new Uri(Constants.ResourceUrl); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(new Uri(baseServiceUri, Constants.TenantId), async () => await AcquireTokenAsync()); return activeDirectoryClient; }
/// <summary> /// Get Active Directory Client for Application. /// </summary> /// <returns>ActiveDirectoryClient for Application.</returns> public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication() { Uri servicePointUri = new Uri(ConfigManager.ReadResourceUrl()); Uri serviceRoot = new Uri(servicePointUri, ConfigManager.ReadTenantId()); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await AcquireTokenAsyncForApplication()); return activeDirectoryClient; }
/// <summary> /// Get Active Directory Client for User. /// </summary> /// <returns>ActiveDirectoryClient for User.</returns> public static ActiveDirectoryClient GetActiveDirectoryClientAsUser() { Uri servicePointUri = new Uri(Constants.ResourceUrl); Uri serviceRoot = new Uri(servicePointUri, Constants.TenantId); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await AcquireTokenAsyncForUser()); return activeDirectoryClient; }
public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication() { var tenantId = GetTenantId(); Uri authenticationUri = new Uri(GraphApiUrl + tenantId); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(authenticationUri, async () => await AcquireApplicationTokenAsync()); return activeDirectoryClient; }
public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication(Uri sharePointAdminUrl) { Uri servicePointUri = new Uri(ResourceUrl); string adminRealm = TokenHelper.GetRealmFromTargetUrl(sharePointAdminUrl); Uri serviceRoot = new Uri(servicePointUri, adminRealm); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, GetTokenForApplicationAsync); return activeDirectoryClient; }
public static async Task<string> Lookup(string keyword) { Lazy<string> authToken = new Lazy<string>(() => { var result = authContext.AcquireTokenAsync("https://graph.windows.net", clientCredential).Result; return result.AccessToken; }, true); string authenticationAuthority = string.Format( CultureInfo.InvariantCulture, "{0}/{1}", AADInstance, Tenant); authContext = new AuthenticationContext(authenticationAuthority); clientCredential = new ClientCredential(Secrets.ClientId, Secrets.AppKey); var activeDirectoryClient = new ActiveDirectoryClient(new Uri("https://graph.windows.net/microsoft.com"), () => { return Task.Run(() => { return authToken.Value; }); }); var objectIds = await FindPotentialGroupsAsync(keyword); var users = new List<IDirectoryObject>(); var tasks = new List<Task<IPagedCollection<IDirectoryObject>>>(); foreach (var objectId in objectIds) { tasks.Add(activeDirectoryClient.Groups.GetByObjectId(objectId.ToString()).Members.ExecuteAsync()); } try { Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(30)); } catch(AggregateException) { // Yay hackathon! } if (!tasks.Any(t => t.IsCompleted && !t.IsFaulted)) { return "beyond my ability to determine right now."; } foreach (var task in tasks.Where(t => t.IsCompleted && !t.IsFaulted)) { users.AddRange(task.Result.CurrentPage.Where(o => o.ObjectType == "User")); } var user = users.GroupBy(u => u.ObjectId).Select(group => new { User = group.First(), Count = group.Count() }) .OrderByDescending(x => x.Count).First().User; return ((User)user).UserPrincipalName; }
static void Main(string[] args) { #region Setup Active Directory Client //********************************************************************* // setup Active Directory Client //********************************************************************* try { activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication(); } catch (AuthenticationException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message); if (ex.InnerException != null) { //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx //InnerException Message will contain the HTTP error status codes mentioned in the link above Console.WriteLine("Error detail: {0}", ex.InnerException.Message); } Console.ResetColor(); Console.ReadKey(); return; } #endregion CleanTableStorages(); Thread t = new Thread(new ThreadStart(ThreadRetrieveUpdates)); t.Start(); while (true) { RetrieveAADInfo(); RetrieveUsers(); RetrieveGroups(); RetrieveApps(); RetrieveAdminRoles(); ParseUserMembership(); RetrieveRBACRoles(); ParseRBACRoleAssignments(); RetrieveResourceGroups(); RetrieveRMResources(); Console.WriteLine("ITALite initialization is done!"); Thread.Sleep(100000); } //InvokingITA testITACore = new InvokingITA(); //Console.WriteLine(testITACore.AccessControl(true)); //Console.WriteLine(testITACore.AccessControl(false)); //TestItaLite(); //Console.WriteLine("TestItaLite done!"); Console.Read(); }
public PSVaultAccessPolicy(KeyVaultManagement.AccessPolicyEntry s, ActiveDirectoryClient adClient) { ObjectId = s.ObjectId; DisplayName = ModelExtensions.GetDisplayNameForADObject(s.ObjectId, adClient); ApplicationId = s.ApplicationId; TenantId = s.TenantId; TenantName = s.TenantId.ToString(); PermissionsToSecrets = new List<string>(s.PermissionsToSecrets); PermissionsToKeys = new List<string>(s.PermissionsToKeys); }
private async Task<ActiveDirectoryClient> GetActiveDirectoryClient() { Uri baseServiceUri = new Uri(AADAppSettings.AADGraphResourceId); var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(new Uri(baseServiceUri, tenantId), async () => await AcquireTokenAsync()); return activeDirectoryClient; }
public MailStoreProviderSDK(string userName, string password) { _adClient = AuthenticationHelperSDK.GetGraphClientAsync(userName, password).GetResult(); _outlookClient = GetOutlookClient("Mail"); _user = _outlookClient.Me.ExecuteAsync().GetResult(); DisplayName = _user.Id; RootFolder = new MailFolderProviderSDK(_outlookClient, _user.Id); }
/// <summary> /// Get Active Directory Client for Application. /// </summary> /// <returns>ActiveDirectoryClient for Application.</returns> public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication(string tenantName, string tenantId, string clientId, string clientSecret) { using (new SPMonitoredScope(String.Format("[AzureCP] Getting access token for tenant {0} by connecting to '{1}' ", tenantName, Constants.ResourceUrl), 1000)) { Uri servicePointUri = new Uri(Constants.ResourceUrl); Uri serviceRoot = new Uri(servicePointUri, tenantId); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await AcquireTokenAsyncForApplication(tenantName, clientId, clientSecret)); return activeDirectoryClient; } }
/// <summary> /// Gets a <seealso cref="ActiveDirectoryClient"/> object /// </summary> /// <returns></returns> protected virtual ActiveDirectoryClient GetActiveDirectoryClient() { Uri _serviceEndpoint = new Uri(this.Client.ServiceInformation.ServiceResource); Uri _serviceRoot = new Uri(_serviceEndpoint, this.Client.ServiceInformation.Tenant); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(_serviceRoot, async () => { var _accountSession = await Client.AuthenticateAsync(); return _accountSession.AccessToken; }); return activeDirectoryClient; }
/// <summary> /// Get Active Directory Client for Application. /// </summary> /// <returns>ActiveDirectoryClient for Application.</returns> internal static ActiveDirectoryClient GetActiveDirectoryClient() { //This example uses a static property class to store the aquired token //during the execution of Startup.Auth.cs Uri baseServiceUri = new Uri(Constants.ResourceUrl); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( new Uri(baseServiceUri, Constants.TenantId), async () => await AcquireTokenAsync() ); return activeDirectoryClient; }
public ActiveDirectoryClient GetADClient() { if (_adClient == null) { Uri servicePointUri = new Uri("https://graph.windows.net"); var serviceRoot = new Uri(servicePointUri, string.Format("{0}.onmicrosoft.com", _generatorDefinition.TenantName)); _adClient = new ActiveDirectoryClient(serviceRoot, async () => GetToken()); } return _adClient; }
public static Models.UserProfile GetUserProfile(string name) { IDatabase cache = CacheConnectionHelper.Connection.GetDatabase(); Models.UserProfile userProfile = (Models.UserProfile)cache.Get(name); if (userProfile == null) { #region Get User Profile from AD Uri serviceRoot = new Uri(SettingsHelper.AzureAdGraphApiEndPoint); var token = AppToken.GetAppToken(); ActiveDirectoryClient adClient = new ActiveDirectoryClient( serviceRoot, async () => await AppToken.GetAppTokenAsync()); string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; Microsoft.Azure.ActiveDirectory.GraphClient.Application app = (Microsoft.Azure.ActiveDirectory.GraphClient.Application)adClient.Applications.Where( a => a.AppId == SettingsHelper.ClientId).ExecuteSingleAsync().Result; if (app == null) { throw new ApplicationException("Unable to get a reference to application in Azure AD."); } string requestUrl = string.Format("https://graph.windows.net/{0}/users/{1}?api-version=1.5", SettingsHelper.Tenant, name); HttpClient hc = new HttpClient(); hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); HttpResponseMessage hrm = hc.GetAsync(new Uri(requestUrl)).Result; if (hrm.IsSuccessStatusCode) { Models.UserProfile currentUserProfile = JsonConvert.DeserializeObject<Models.UserProfile>(hrm.Content.ReadAsStringAsync().Result); cache.Set(ClaimsPrincipal.Current.Identities.First().Name, currentUserProfile, TimeSpan.FromMinutes(SettingsHelper.CacheUserProfileMinutes)); return currentUserProfile; } else { return null; } #endregion } else { return userProfile; } }
/// <summary> /// Checks that a Graph client is available. /// </summary> /// <returns>The Graph client.</returns> internal static async Task<ActiveDirectoryClient> GetGraphClientAsync(string userName, string password) { //Check to see if this client has already been created. If so, return it. Otherwise, create a new one. if (_graphClient != null) { return _graphClient; } UserName = userName; Password = password; // Active Directory service endpoints Uri aadServiceEndpointUri = new Uri(AadServiceResourceId); try { //First, look for the authority used during the last authentication. //If that value is not populated, use CommonAuthority. string authority = String.IsNullOrEmpty(LastAuthority) ? CommonAuthority : LastAuthority; // Create an AuthenticationContext using this authority. _authenticationContext = new AuthenticationContext(authority); var token = await GetTokenHelperAsync(_authenticationContext, AadServiceResourceId); // Check the token if (string.IsNullOrEmpty(token)) { // User cancelled sign-in throw new Exception("Sign-in cancelled"); // assuming we don't want to continue } else { // Create our ActiveDirectory client. _graphClient = new ActiveDirectoryClient( new Uri(aadServiceEndpointUri, TenantId), async () => await GetTokenHelperAsync(_authenticationContext, AadServiceResourceId)); return _graphClient; } } catch (Exception) { _authenticationContext.TokenCache.Clear(); throw; } }
public async Task<bool> AuthenticateAsync() { await GetConfigAsync(); // prompts the user for authentication _AuthenticationResult = await _Authenticator.Authenticate(_TenantAuthority, _ResourceUri, _AzureAuthenticationClientId, _ReturnUri); var accessToken = await GetTokenAsync(); // instantiate an ActiveDirectoryClient to query the Graph API var activeDirectoryGraphApiClient = new ActiveDirectoryClient( new Uri(new Uri(_ResourceUri), _AzureGraphApiClientId), () => Task.FromResult<string>(accessToken) ); return true; }
public PSVault(KeyVaultManagement.Vault vault, ActiveDirectoryClient adClient) { var vaultTenantDisplayName = ModelExtensions.GetDisplayNameForTenant(vault.Properties.TenantId, adClient); VaultName = vault.Name; Location = vault.Location; ResourceId = vault.Id; ResourceGroupName = (new ResourceIdentifier(vault.Id)).ResourceGroupName; Tags = TagsConversionHelper.CreateTagHashtable(vault.Tags); Sku = vault.Properties.Sku.Name; TenantId = vault.Properties.TenantId; TenantName = vaultTenantDisplayName; VaultUri = vault.Properties.VaultUri; EnabledForDeployment = vault.Properties.EnabledForDeployment; EnabledForTemplateDeployment = vault.Properties.EnabledForTemplateDeployment; EnabledForDiskEncryption = vault.Properties.EnabledForDiskEncryption; AccessPolicies = vault.Properties.AccessPolicies.Select(s => new PSVaultAccessPolicy(s, adClient)).ToArray(); OriginalVault = vault; }
public static string GetDisplayNameForADObject(string objectId, ActiveDirectoryClient adClient) { var displayName = ""; var upnOrSpn = ""; if (adClient == null || string.IsNullOrWhiteSpace(objectId)) { return(displayName); } try { // TODO: Remove IfDef #if NETSTANDARD var obj = adClient.GetObjectsByObjectId(new List <string> { objectId }).FirstOrDefault(); if (obj != null) { if (obj.Type.Equals("user", StringComparison.InvariantCultureIgnoreCase)) { var user = adClient.FilterUsers(new ADObjectFilterOptions { Id = objectId }).FirstOrDefault(); displayName = user.DisplayName; upnOrSpn = user.UserPrincipalName; } else if (obj.Type.Equals("serviceprincipal", StringComparison.InvariantCultureIgnoreCase)) { var odataQuery = new Rest.Azure.OData.ODataQuery <Graph.RBAC.Version1_6.Models.ServicePrincipal>(s => s.ObjectId == objectId); var servicePrincipal = adClient.FilterServicePrincipals(odataQuery).FirstOrDefault(); displayName = servicePrincipal.DisplayName; upnOrSpn = servicePrincipal.ServicePrincipalNames.FirstOrDefault(); } else if (obj.Type.Equals("group", StringComparison.InvariantCultureIgnoreCase)) { var group = adClient.FilterGroups(new ADObjectFilterOptions { Id = objectId }).FirstOrDefault(); displayName = group.DisplayName; } } #else var obj = adClient.GetObjectsByObjectIdsAsync(new[] { objectId }, new string[] { }).GetAwaiter().GetResult().FirstOrDefault(); if (obj != null) { if (obj.ObjectType.Equals("user", StringComparison.InvariantCultureIgnoreCase)) { var user = adClient.Users.GetByObjectId(objectId).ExecuteAsync().GetAwaiter().GetResult(); displayName = user.DisplayName; upnOrSpn = user.UserPrincipalName; } else if (obj.ObjectType.Equals("serviceprincipal", StringComparison.InvariantCultureIgnoreCase)) { var servicePrincipal = adClient.ServicePrincipals.GetByObjectId(objectId).ExecuteAsync().GetAwaiter().GetResult(); displayName = servicePrincipal.AppDisplayName; upnOrSpn = servicePrincipal.ServicePrincipalNames.FirstOrDefault(); } else if (obj.ObjectType.Equals("group", StringComparison.InvariantCultureIgnoreCase)) { var group = adClient.Groups.GetByObjectId(objectId).ExecuteAsync().GetAwaiter().GetResult(); displayName = group.DisplayName; upnOrSpn = group.MailNickname; } } #endif } catch { // Error occured. Don't get the friendly name } return(displayName + (!string.IsNullOrWhiteSpace(upnOrSpn) ? (" (" + upnOrSpn + ")") : "")); }
/// <summary> /// Update an existing vault. Only EnabledForDeployment and AccessPolicies can be updated currently. /// </summary> /// <param name="existingVault"></param> /// <returns></returns> public PSVault UpdateVault(PSVault existingVault, PSVaultAccessPolicy[] updatedPolicies, bool updatedEnabledForDeployment, ActiveDirectoryClient adClient = null) { if (existingVault == null) { throw new ArgumentNullException("existingVault"); } if (existingVault.OriginalVault == null) { throw new ArgumentNullException("existingVault.OriginalVault"); } //Update the vault properties in the object received from server //Only access policies and EnabledForDeployment can be changed VaultProperties properties = existingVault.OriginalVault.Properties; properties.EnabledForDeployment = updatedEnabledForDeployment; properties.AccessPolicies = (updatedPolicies == null) ? new List <AccessPolicyEntry>() : updatedPolicies.Select(a => new AccessPolicyEntry() { TenantId = a.TenantId, ObjectId = a.ObjectId, PermissionsToKeys = a.PermissionsToKeys.ToArray(), PermissionsToSecrets = a.PermissionsToSecrets.ToArray() }).ToList(); var response = this.KeyVaultManagementClient.Vaults.CreateOrUpdate( resourceGroupName: existingVault.ResourceGroupName, vaultName: existingVault.VaultName, parameters: new VaultCreateOrUpdateParameters() { Location = existingVault.Location, Properties = properties } ); return(new PSVault(response.Vault, adClient)); }
public ActiveDirectoryClientWrapper(IAzureContext context) { ActiveDirectoryClient = new ActiveDirectoryClient(context); }
private static async Task <ServicePrincipalResponse> CreateAppObjectIfNotExists(string displayName, string appIdUri, ActiveDirectoryClient adClient) { var isNewApp = false; var appCreated = default(IApplication); // First check if the App exists, already var appFilter = adClient.Applications.Where(app => app.IdentifierUris.Any(iduri => iduri == appIdUri)); var foundApp = await appFilter.ExecuteAsync(); if (foundApp.CurrentPage.Count == 0) { var newApp = new Application { //AppId = Guid.NewGuid().ToString(), DisplayName = displayName, IdentifierUris = new List <string> { appIdUri } }; await adClient.Applications.AddApplicationAsync(newApp); appCreated = newApp; isNewApp = true; } else { appCreated = foundApp.CurrentPage.FirstOrDefault(); } return(new ServicePrincipalResponse { App = appCreated, IsNewApp = isNewApp }); }
private static async Task <ServicePrincipalResponse> CreateServicePrincipalIfNotExists(IApplication app, string password, ActiveDirectoryClient adClient) { var isNewSp = false; var spCreated = default(IServicePrincipal); // First check if the service principal exists, already var appIdToFilter = app.AppId; var spFilter = adClient.ServicePrincipals.Where(sp => sp.AppId == appIdToFilter); var foundSp = await spFilter.ExecuteAsync(); if (foundSp.CurrentPage.Count == 0) { spCreated = new ServicePrincipal { AccountEnabled = true, AppId = app.AppId, DisplayName = app.DisplayName, ServicePrincipalNames = new List <string> { app.AppId, app.IdentifierUris.First() }, PasswordCredentials = new List <PasswordCredential> { new PasswordCredential { StartDate = DateTime.UtcNow, EndDate = DateTime.UtcNow.AddYears(1), Value = password, KeyId = Guid.NewGuid() } } }; // Submit the creation request and return the newly created Service Principal Object await adClient.ServicePrincipals.AddServicePrincipalAsync(spCreated); isNewSp = true; } else { spCreated = foundSp.CurrentPage.First(); spCreated.PasswordCredentials.Add( new PasswordCredential { StartDate = DateTime.UtcNow, EndDate = DateTime.UtcNow.AddYears(1), Value = password, KeyId = Guid.NewGuid() } ); await spCreated.UpdateAsync(); } return(new ServicePrincipalResponse { IsNewPrincipal = isNewSp, Principal = spCreated }); }
public static IEnumerable <PSRoleAssignment> ToPSRoleAssignments(this IEnumerable <RoleAssignment> assignments, AuthorizationClient policyClient, ActiveDirectoryClient activeDirectoryClient, bool excludeAssignmentsForDeletedPrincipals = true) { List <PSRoleAssignment> psAssignments = new List <PSRoleAssignment>(); if (assignments == null || !assignments.Any()) { return(psAssignments); } List <string> objectIds = new List <string>(); objectIds.AddRange(assignments.Select(r => r.Properties.PrincipalId.ToString())); List <PSADObject> adObjects = activeDirectoryClient.GetObjectsByObjectId(objectIds); List <PSRoleDefinition> roleDefinitions; if (assignments.Count() == 1) { roleDefinitions = new List <PSRoleDefinition> { policyClient.GetRoleDefinition(assignments.Single().Properties.RoleDefinitionId) }; } else { roleDefinitions = policyClient.GetRoleDefinitions(); } foreach (RoleAssignment assignment in assignments) { assignment.Properties.RoleDefinitionId = assignment.Properties.RoleDefinitionId.GuidFromFullyQualifiedId(); PSADObject adObject = adObjects.SingleOrDefault(o => o.Id == assignment.Properties.PrincipalId) ?? new PSADObject() { Id = assignment.Properties.PrincipalId }; PSRoleDefinition roleDefinition = roleDefinitions.SingleOrDefault(r => r.Id == assignment.Properties.RoleDefinitionId) ?? new PSRoleDefinition() { Id = assignment.Properties.RoleDefinitionId }; if (adObject is PSADUser) { psAssignments.Add(new PSRoleAssignment() { RoleAssignmentId = assignment.Id, DisplayName = adObject.DisplayName, RoleDefinitionId = roleDefinition.Id, RoleDefinitionName = roleDefinition.Name, Scope = assignment.Properties.Scope, SignInName = ((PSADUser)adObject).SignInName, ObjectId = adObject.Id, ObjectType = adObject.Type }); } else if (adObject is PSADGroup) { psAssignments.Add(new PSRoleAssignment() { RoleAssignmentId = assignment.Id, DisplayName = adObject.DisplayName, RoleDefinitionId = roleDefinition.Id, RoleDefinitionName = roleDefinition.Name, Scope = assignment.Properties.Scope, ObjectId = adObject.Id, ObjectType = adObject.Type }); } else if (adObject is PSADServicePrincipal) { psAssignments.Add(new PSRoleAssignment() { RoleAssignmentId = assignment.Id, DisplayName = adObject.DisplayName, RoleDefinitionId = roleDefinition.Id, RoleDefinitionName = roleDefinition.Name, Scope = assignment.Properties.Scope, ObjectId = adObject.Id, ObjectType = adObject.Type }); } else if (!excludeAssignmentsForDeletedPrincipals) { psAssignments.Add(new PSRoleAssignment() { RoleAssignmentId = assignment.Id, DisplayName = adObject.DisplayName, RoleDefinitionId = roleDefinition.Id, RoleDefinitionName = roleDefinition.Name, Scope = assignment.Properties.Scope, ObjectId = adObject.Id, }); } // Ignore the assignment if principal does not exists and excludeAssignmentsForDeletedPrincipals is set to true } return(psAssignments); }
public static string GetDisplayNameForADObject(string objectId, ActiveDirectoryClient adClient) { string displayName = ""; string upnOrSpn = ""; if (adClient == null || string.IsNullOrWhiteSpace(objectId)) { return(displayName); } try { #if NETSTANDARD var obj = adClient.GetObjectsByObjectId(new List <string> { objectId }).FirstOrDefault(); if (obj != null) { if (obj.Type.Equals("user", StringComparison.InvariantCultureIgnoreCase)) { var user = adClient.FilterUsers(new ADObjectFilterOptions { Id = objectId }).FirstOrDefault(); displayName = user.DisplayName; upnOrSpn = user.UserPrincipalName; } else if (obj.Type.Equals("serviceprincipal", StringComparison.InvariantCultureIgnoreCase)) { var servicePrincipal = adClient.FilterServicePrincipals(new ADObjectFilterOptions { Id = objectId }).FirstOrDefault(); displayName = servicePrincipal.DisplayName; upnOrSpn = servicePrincipal.ServicePrincipalNames.FirstOrDefault(); } } #else var obj = adClient.GetObjectsByObjectIdsAsync(new[] { objectId }, new string[] { }).GetAwaiter().GetResult().FirstOrDefault(); if (obj != null) { if (obj.ObjectType.Equals("user", StringComparison.InvariantCultureIgnoreCase)) { var user = adClient.Users.GetByObjectId(objectId).ExecuteAsync().GetAwaiter().GetResult(); displayName = user.DisplayName; upnOrSpn = user.UserPrincipalName; } else if (obj.ObjectType.Equals("serviceprincipal", StringComparison.InvariantCultureIgnoreCase)) { var servicePrincipal = adClient.ServicePrincipals.GetByObjectId(objectId).ExecuteAsync().GetAwaiter().GetResult(); displayName = servicePrincipal.AppDisplayName; upnOrSpn = servicePrincipal.ServicePrincipalNames.FirstOrDefault(); } } #endif } catch { // Error occured. Don't get the friendly name } return(displayName + (!string.IsNullOrWhiteSpace(upnOrSpn) ? (" (" + upnOrSpn + ")") : "")); }
private static IEnumerable <PSRoleAssignment> ToPSRoleAssignments(this IEnumerable <RoleAssignment> assignments, List <PSRoleDefinition> roleDefinitions, AuthorizationClient policyClient, ActiveDirectoryClient activeDirectoryClient, bool excludeAssignmentsForDeletedPrincipals) { List <PSRoleAssignment> psAssignments = new List <PSRoleAssignment>(); if (assignments == null || !assignments.Any()) { return(psAssignments); } List <string> objectIds = new List <string>(); objectIds.AddRange(assignments.Select(r => r.PrincipalId.ToString())); objectIds = objectIds.Distinct().ToList(); List <PSADObject> adObjects = null; try { adObjects = activeDirectoryClient.GetObjectsByObjectId(objectIds); } catch (CloudException ce) when(IsAuthorizationDeniedException(ce)) { throw new InvalidOperationException(ProjectResources.InSufficientGraphPermission); } foreach (RoleAssignment assignment in assignments) { assignment.RoleDefinitionId = assignment.RoleDefinitionId.GuidFromFullyQualifiedId(); PSADObject adObject = adObjects.SingleOrDefault(o => o.Id == Guid.Parse(assignment.PrincipalId)) ?? new PSADObject() { Id = Guid.Parse(assignment.PrincipalId) }; PSRoleDefinition roleDefinition = roleDefinitions.SingleOrDefault(r => r.Id == assignment.RoleDefinitionId) ?? new PSRoleDefinition() { Id = assignment.RoleDefinitionId }; bool delegationFlag = assignment.CanDelegate.HasValue ? (bool)assignment.CanDelegate : false; if (adObject is PSADUser) { psAssignments.Add(new PSRoleAssignment() { RoleAssignmentId = assignment.Id, DisplayName = adObject.DisplayName, RoleDefinitionId = roleDefinition.Id, RoleDefinitionName = roleDefinition.Name, Scope = assignment.Scope, SignInName = ((PSADUser)adObject).UserPrincipalName, ObjectId = adObject.Id, ObjectType = adObject.Type, CanDelegate = delegationFlag }); } else if (adObject is PSADGroup) { psAssignments.Add(new PSRoleAssignment() { RoleAssignmentId = assignment.Id, DisplayName = adObject.DisplayName, RoleDefinitionId = roleDefinition.Id, RoleDefinitionName = roleDefinition.Name, Scope = assignment.Scope, ObjectId = adObject.Id, ObjectType = adObject.Type, CanDelegate = delegationFlag }); } else if (adObject is PSADServicePrincipal) { psAssignments.Add(new PSRoleAssignment() { RoleAssignmentId = assignment.Id, DisplayName = adObject.DisplayName, RoleDefinitionId = roleDefinition.Id, RoleDefinitionName = roleDefinition.Name, Scope = assignment.Scope, ObjectId = adObject.Id, ObjectType = adObject.Type, CanDelegate = delegationFlag }); } else if (!excludeAssignmentsForDeletedPrincipals) { psAssignments.Add(new PSRoleAssignment() { RoleAssignmentId = assignment.Id, DisplayName = adObject.DisplayName, RoleDefinitionId = roleDefinition.Id, RoleDefinitionName = roleDefinition.Name, Scope = assignment.Scope, ObjectId = adObject.Id, CanDelegate = delegationFlag }); } // Ignore the assignment if principal does not exists and excludeAssignmentsForDeletedPrincipals is set to true } return(psAssignments); }
public static IEnumerable <PSRoleAssignment> ToPSRoleAssignments(this IEnumerable <RoleAssignment> assignments, AuthorizationClient policyClient, ActiveDirectoryClient activeDirectoryClient, string scopeForRoleDefinitions, bool excludeAssignmentsForDeletedPrincipals = true) { List <PSRoleDefinition> roleDefinitions = null; try { roleDefinitions = policyClient.GetAllRoleDefinitionsAtScopeAndBelow(scopeForRoleDefinitions); } catch (CloudException ce) { if (ce.Response.StatusCode == HttpStatusCode.Unauthorized) { //Swallow unauthorized errors on RoleDefinition when displaying RoleAssignments roleDefinitions = new List <PSRoleDefinition>(); } else { throw; } } return(assignments.ToPSRoleAssignments(roleDefinitions, policyClient, activeDirectoryClient, excludeAssignmentsForDeletedPrincipals)); }
/// <summary> /// Update an existing vault. Only EnabledForDeployment and AccessPolicies can be updated currently. /// </summary> /// <param name="existingVault">the existing vault</param> /// <param name="updatedPolicies">the update access policies</param> /// <param name="updatedEnabledForDeployment">enabled for deployment</param> /// <param name="updatedEnabledForTemplateDeployment">enabled for template deployment</param> /// <param name="updatedEnabledForDiskEncryption">enabled for disk encryption</param> /// <param name="updatedNetworkAcls">updated network rule set</param> /// <param name="adClient">the active directory client</param> /// <returns>the updated vault</returns> public PSKeyVault UpdateVault( PSKeyVault existingVault, PSKeyVaultAccessPolicy[] updatedPolicies, bool?updatedEnabledForDeployment, bool?updatedEnabledForTemplateDeployment, bool?updatedEnabledForDiskEncryption, bool?updatedSoftDeleteSwitch, bool?updatedPurgeProtectionSwitch, PSKeyVaultNetworkRuleSet updatedNetworkAcls, ActiveDirectoryClient adClient = null) { if (existingVault == null) { throw new ArgumentNullException("existingVault"); } if (existingVault.OriginalVault == null) { throw new ArgumentNullException("existingVault.OriginalVault"); } //Update the vault properties in the object received from server //Only access policies and EnabledForDeployment can be changed var properties = existingVault.OriginalVault.Properties; properties.EnabledForDeployment = updatedEnabledForDeployment; properties.EnabledForTemplateDeployment = updatedEnabledForTemplateDeployment; properties.EnabledForDiskEncryption = updatedEnabledForDiskEncryption; // soft delete flags can only be applied if they enable their respective behaviors // and if different from the current corresponding properties on the vault. if (!(properties.EnableSoftDelete.HasValue && properties.EnableSoftDelete.Value) && updatedSoftDeleteSwitch.HasValue && updatedSoftDeleteSwitch.Value) { properties.EnableSoftDelete = updatedSoftDeleteSwitch; } if (!(properties.EnablePurgeProtection.HasValue && properties.EnablePurgeProtection.Value) && updatedPurgeProtectionSwitch.HasValue && updatedPurgeProtectionSwitch.Value) { properties.EnablePurgeProtection = updatedPurgeProtectionSwitch; } properties.AccessPolicies = (updatedPolicies == null) ? new List <AccessPolicyEntry>() : updatedPolicies.Select(a => new AccessPolicyEntry { TenantId = a.TenantId, ObjectId = a.ObjectId, ApplicationId = a.ApplicationId, Permissions = new Permissions { Keys = a.PermissionsToKeys.ToArray(), Secrets = a.PermissionsToSecrets.ToArray(), Certificates = a.PermissionsToCertificates.ToArray(), Storage = a.PermissionsToStorage.ToArray(), } }).ToList(); UpdateVaultNetworkRuleSetProperties(properties, updatedNetworkAcls); var response = KeyVaultManagementClient.Vaults.CreateOrUpdate( resourceGroupName: existingVault.ResourceGroupName, vaultName: existingVault.VaultName, parameters: new VaultCreateOrUpdateParameters { Location = existingVault.Location, Properties = properties, Tags = TagsConversionHelper.CreateTagDictionary(existingVault.Tags, validate: true) } ); return(new PSKeyVault(response, adClient)); }
/// <summary> /// Create a new vault /// </summary> /// <param name="parameters">vault creation parameters</param> /// <param name="adClient">the active directory client</param> /// <returns></returns> public PSKeyVault CreateNewVault(VaultCreationParameters parameters, ActiveDirectoryClient adClient = null) { if (parameters == null) { throw new ArgumentNullException("parameters"); } if (string.IsNullOrWhiteSpace(parameters.VaultName)) { throw new ArgumentNullException("parameters.VaultName"); } if (string.IsNullOrWhiteSpace(parameters.ResourceGroupName)) { throw new ArgumentNullException("parameters.ResourceGroupName"); } if (string.IsNullOrWhiteSpace(parameters.Location)) { throw new ArgumentNullException("parameters.Location"); } var properties = new VaultProperties(); if (parameters.CreateMode != CreateMode.Recover) { if (string.IsNullOrWhiteSpace(parameters.SkuFamilyName)) { throw new ArgumentNullException("parameters.SkuFamilyName"); } if (parameters.TenantId == Guid.Empty) { throw new ArgumentException("parameters.TenantId"); } properties.Sku = new Sku { Name = parameters.SkuName, }; properties.EnabledForDeployment = parameters.EnabledForDeployment; properties.EnabledForTemplateDeployment = parameters.EnabledForTemplateDeployment; properties.EnabledForDiskEncryption = parameters.EnabledForDiskEncryption; properties.EnableSoftDelete = parameters.EnableSoftDelete.HasValue && parameters.EnableSoftDelete.Value ? true : (bool?)null; properties.EnablePurgeProtection = parameters.EnablePurgeProtection.HasValue && parameters.EnablePurgeProtection.Value ? true : (bool?)null; properties.TenantId = parameters.TenantId; properties.VaultUri = ""; properties.AccessPolicies = (parameters.AccessPolicy != null) ? new[] { parameters.AccessPolicy } : new AccessPolicyEntry[] { }; properties.NetworkAcls = parameters.NetworkAcls; } else { properties.CreateMode = CreateMode.Recover; } var response = KeyVaultManagementClient.Vaults.CreateOrUpdate( resourceGroupName: parameters.ResourceGroupName, vaultName: parameters.VaultName, parameters: new VaultCreateOrUpdateParameters { Location = parameters.Location, Tags = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true), Properties = properties }); return(new PSKeyVault(response, adClient)); }
public AADGraphClient(ActiveDirectoryClient activeDirectoryClient) { this.activeDirectoryClient = activeDirectoryClient; }
public override async Task ProcessRequestAsync(HttpContext context) { try { ClientCredential credential = new ClientCredential(Constants.AzureActiveDirectory.ClientId, Constants.AzureActiveDirectory.ApplicationKey); var authContext = new AuthenticationContext(string.Format(Constants.AzureActiveDirectory.AuthorityUrl, Constants.AzureActiveDirectory.TenantId)); var code = ValidationHelper.GetString(HttpContext.Current.Request.QueryString["code"], string.Empty); AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential, string.Format(Constants.AzureActiveDirectory.GraphUrl, "")); var adClient = new ActiveDirectoryClient( new Uri(string.Format(Constants.AzureActiveDirectory.GraphUrl, result.TenantId)), async() => await GetAppTokenAsync(result.TenantId)); var adUser = (User) await adClient.Users.Where(x => x.UserPrincipalName.Equals(result.UserInfo.DisplayableId)) .Expand(x => x.MemberOf) .ExecuteSingleAsync(); var user = UserInfoProvider.GetUsers() .Where("AzureADUsername", QueryOperator.Equals, adUser.UserPrincipalName) .FirstOrDefault(); var groupsToAdd = adUser.MemberOf.OfType <Group>() .Select(x => x.DisplayName) .Where(x => Constants.AzureActiveDirectory.GroupsToSync.Contains(x)); var groupsToRemove = Constants.AzureActiveDirectory.GroupsToSync .Where(x => !groupsToAdd.Contains(x)); // check if any of the Azure Active Directory groups are matching by name any Kentico roles // if not save an error message in ErrorLog and return bool isGroupMatchRole = false; foreach (var group in groupsToAdd) { var roleInfo = RoleInfoProvider.GetRoles() .OnSite(SiteContext.CurrentSiteID) .Where("RoleDisplayName", QueryOperator.Equals, group).ToList <RoleInfo>(); if (roleInfo.Count > 0) { isGroupMatchRole = true; break; } } if (!isGroupMatchRole) { var logerr = $"Attempted login on {DateTime.Now} by user {adUser.UserPrincipalName},[{adUser.DisplayName}] memberOf {groupsToAdd.ToList<string>().Join(",")}"; EventLogProvider.LogEvent(EventType.ERROR, "Login user through Azure Active Directory", "AZUREADLOGINFAILURE", eventDescription: logerr); var returnUrlWithError = ValidationHelper.GetString(this.Context.Request.Params["state"], string.Empty); URLHelper.Redirect(URLHelper.GetAbsoluteUrl($"{returnUrlWithError}?logonresult=Failed&firstname={adUser.DisplayName}&lastname={string.Empty}&lastlogoninfo={logerr}")); return; } if (user == null) { user = new CMS.Membership.UserInfo(); user.UserName = adUser.UserPrincipalName; user.FirstName = adUser.GivenName; user.LastName = adUser.Surname; user.FullName = adUser.DisplayName; user.Email = adUser.Mail.IfEmpty(adUser.OtherMails.FirstOrDefault()); user.SetValue("AzureADUsername", adUser.UserPrincipalName); user.IsExternal = true; //None 0 User has no privilege level //Editor 1 User is able to use administration interface //Admin 2 User can use all applications except the global applications and functionality //GlobalAdmin 3 User can use all applications and functionality without any exceptions user.SiteIndependentPrivilegeLevel = CMS.Base.UserPrivilegeLevelEnum.Editor; user.Enabled = true; UserInfoProvider.SetUserInfo(user); UserInfoProvider.AddUserToSite(user.UserName, SiteContext.CurrentSiteName); foreach (var group in groupsToAdd) { UserInfoProvider.AddUserToRole(user.UserName, RoleInfoProvider.GetRoles() .OnSite(SiteContext.CurrentSiteID) .Where("RoleDisplayName", QueryOperator.Equals, group) .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName); } } else { user.FirstName = adUser.GivenName; user.LastName = adUser.Surname; user.FullName = adUser.DisplayName; user.Email = adUser.Mail.IfEmpty(adUser.OtherMails.FirstOrDefault()); user.IsExternal = true; UserInfoProvider.SetUserInfo(user); UserInfoProvider.AddUserToSite(user.UserName, SiteContext.CurrentSiteName); foreach (var group in groupsToAdd) { UserInfoProvider.AddUserToRole(user.UserName, RoleInfoProvider.GetRoles() .OnSite(SiteContext.CurrentSiteID) .Where("RoleDisplayName", QueryOperator.Equals, group) .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName); } foreach (var group in groupsToRemove) { UserInfoProvider.RemoveUserFromRole(user.UserName, RoleInfoProvider.GetRoles() .OnSite(SiteContext.CurrentSiteID) .Where("RoleDisplayName", QueryOperator.Equals, group) .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName); } } AuthenticationHelper.AuthenticateUser(user.UserName, false); MembershipActivityLogger.LogLogin(user.UserName, DocumentContext.CurrentDocument); var returnUrl = ValidationHelper.GetString(context.Request.Params["state"], string.Empty); URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl)); } catch (Exception exception) { EventLogProvider.LogException("AzureActiveDirectory", "Login", exception); } }
public static string GetDisplayNameForTenant(Guid id, ActiveDirectoryClient adClient) { return(id.ToString()); }
public static PSDenyAssignment ToPSDenyAssignment(this DenyAssignment assignment, ActiveDirectoryClient activeDirectoryClient, bool excludeAssignmentsForDeletedPrincipals = true) { var objectIds = new List <string>(); objectIds.AddRange(assignment.Principals.Where(p => Guid.Parse(p.Id) != Guid.Empty).Select(p => p.Id)); objectIds.AddRange(assignment.ExcludePrincipals.Where(ep => Guid.Parse(ep.Id) != Guid.Empty).Select(ep => ep.Id)); objectIds = objectIds.Distinct().ToList(); List <PSADObject> adObjects = null; try { adObjects = activeDirectoryClient.GetObjectsByObjectId(objectIds); } catch (CloudException ce) when(IsAuthorizationDeniedException(ce)) { throw new InvalidOperationException(ProjectResources.InSufficientGraphPermission); } var psda = new PSDenyAssignment() { Id = assignment.Id.GuidFromFullyQualifiedId(), DenyAssignmentName = assignment.DenyAssignmentName, Description = assignment.Description, Actions = new List <string>(assignment.Permissions.SelectMany(p => p.Actions)), NotActions = new List <string>(assignment.Permissions.SelectMany(p => p.NotActions)), DataActions = new List <string>(assignment.Permissions.SelectMany(p => p.DataActions)), NotDataActions = new List <string>(assignment.Permissions.SelectMany(p => p.NotDataActions)), Scope = assignment.Scope, DoNotApplyToChildScopes = assignment.DoNotApplyToChildScopes ?? false, IsSystemProtected = assignment.IsSystemProtected ?? false, }; psda.Principals = assignment.Principals.ToPSPrincipals(adObjects, excludeAssignmentsForDeletedPrincipals).ToList(); psda.ExcludePrincipals = assignment.ExcludePrincipals.ToPSPrincipals(adObjects, excludeAssignmentsForDeletedPrincipals).ToList(); return(psda); }
/// <summary> /// Create a new vault /// </summary> /// <param name="parameters"></param> /// <returns></returns> public PSVault CreateNewVault(VaultCreationParameters parameters, ActiveDirectoryClient adClient = null) { if (parameters == null) { throw new ArgumentNullException("parameters"); } if (string.IsNullOrWhiteSpace(parameters.VaultName)) { throw new ArgumentNullException("parameters.VaultName"); } if (string.IsNullOrWhiteSpace(parameters.ResourceGroupName)) { throw new ArgumentNullException("parameters.ResourceGroupName"); } if (string.IsNullOrWhiteSpace(parameters.Location)) { throw new ArgumentNullException("parameters.Location"); } if (string.IsNullOrWhiteSpace(parameters.SkuName)) { throw new ArgumentNullException("parameters.SkuName"); } if (string.IsNullOrWhiteSpace(parameters.SkuFamilyName)) { throw new ArgumentNullException("parameters.SkuFamilyName"); } if (parameters.TenantId == null || parameters.TenantId == Guid.Empty) { throw new ArgumentException("parameters.TenantId"); } if (parameters.ObjectId == null || parameters.ObjectId == Guid.Empty) { throw new ArgumentException("parameters.ObjectId"); } var response = this.KeyVaultManagementClient.Vaults.CreateOrUpdate( resourceGroupName: parameters.ResourceGroupName, vaultName: parameters.VaultName, parameters: new VaultCreateOrUpdateParameters() { Location = parameters.Location, Tags = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true), Properties = new VaultProperties() { Sku = new Sku() { Family = parameters.SkuFamilyName, Name = parameters.SkuName }, EnabledForDeployment = parameters.EnabledForDeployment, TenantId = parameters.TenantId, VaultUri = "", AccessPolicies = new AccessPolicyEntry[] { new AccessPolicyEntry { TenantId = parameters.TenantId, ObjectId = parameters.ObjectId, PermissionsToKeys = parameters.PermissionsToKeys, PermissionsToSecrets = parameters.PermissionsToSecrets } } } } ); return(new PSVault(response.Vault, adClient)); }
public static async Task GrantConsents() { // .NET AAD Graph client ActiveDirectoryClient aadClient = null; try { Uri servicePointUri = new Uri(GlobalConstants.AADGraphResourceUrl); Uri serviceRoot = new Uri(servicePointUri, GlobalConstants.GraphTenantName); // create an Active Directory Client based on a signed in user aadClient = await Task.Run(() => { return(new ActiveDirectoryClient(serviceRoot, async() => await AuthenticationHelper.AcquireAADTokenAsyncForUser())); }); // The tenant must have service principals to the MS and AAD Graph APIs in order to proceed. // These are automatically created (JIT) by Azure AD when consenting to applications that use // permissions from those APIs; therefore, ensure your bootstrap app is created with at least // 1 permission (e.g. 'Sign in and read user profile') from both AD Graph and MS Graph. // Since it takes a few seconds for the SPs to be created JIT immediately after consent, // we wait 5 seconds for the dust to settle. Console.WriteLine("Waiting 5s for resource SPs to be created..."); Thread.Sleep(5000); var MSFTGraphPrincipal = await GetServicePrincipalAsync(aadClient, GlobalConstants.MSFTGraphAppId); if (MSFTGraphPrincipal == null) { throw new Exception($"{GlobalConstants.MSFTGraphDisplayName} service principal is missing; please ensure you have consented to the bootstrap application and then try again."); } var AADGraphPrincipal = await GetServicePrincipalAsync(aadClient, GlobalConstants.AADGraphAppId); if (AADGraphPrincipal == null) { throw new Exception($"{GlobalConstants.AADGraphDisplayName} service principal is missing; please ensure you have consented to the bootstrap application and then try again."); } // Add your application permissions here. // You should add a new OAuthGrant per service principle (resource API) and application List <OAuthGrant> grants = new List <OAuthGrant>() { { new OAuthGrant { Application = new Application { AppId = "<Your AAD Application ID>", DisplayName = "<Your AAD Application Display Name>" }, ResourceServicePrincipal = AADGraphPrincipal, // what API does your AAD Application use? DelegatedPermissions = "<Your permission scopes>", // e.g. User.Read Mail.Send (separate with a space) ApplicationPermissions = new List <string> { } } }, { new OAuthGrant { Application = new Application { AppId = "<Your AAD Application ID>", DisplayName = "<Your AAD Application Display Name>" }, ResourceServicePrincipal = MSFTGraphPrincipal, // what API does your AAD Application use? DelegatedPermissions = "", ApplicationPermissions = new List <string> { "<Your permission scopes as Guids>" } //e.g. 741f803b-c850-494e-b5df-cde7c675a1ca = Read and write all users' full profiles } } }; // Ensure the tenant does have a previously created Service Principal for each application. // This ensures the tenant consents to the latest scope of permissions required by YOUR AAD application. // Note, this is an additional loop to the create loop below because it may be the case that // an ApplicationServicePrincipal has permissions belonging more than one ResourceServicePrincipal foreach (var grant in grants) { await CleanupPermissionGrantsAsync(aadClient, grant); } ; // Create a blank service principle, then grant it the required user (delegated) and application permissions foreach (var grant in grants) { // create a service principal for all apps requiring consent grant.ApplicationServicePrincipal = await CreateServicePrincipalAsync(aadClient, grant.Application); if (grant.ApplicationServicePrincipal == null) { continue; } // pre-consent the permissions for the application await AddDelegatedPermissionsGrantAsync(aadClient, grant); // pre-consent to the application permissions for the application await AddApplicationPermissionsGrantAsync(aadClient, grant); Program.WriteInfo($"\nService Principal created: {grant.ApplicationServicePrincipal.DisplayName}\n\tDelegated permissions: {grant.DelegatedPermissions}\n\tApplication permissions: {string.Join(" ", grant.ApplicationPermissions)}\n"); } } catch (Exception e) { Program.WriteError("Acquiring a token failed with the following error: {0}", Program.ExtractErrorMessage(e)); // TODO: Implement retry and back-off logic per the guidance given here: http://msdn.microsoft.com/en-us/library/dn168916.aspx Console.ReadKey(); return; } }
/// <summary> /// Configures application authentication. /// </summary> /// <param name="app">The application to configure.</param> public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = ApplicationConfiguration.ActiveDirectoryClientID, Authority = ApplicationConfiguration.ActiveDirectoryEndPoint + "common", TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { // instead of using the default validation (validating against a single issuer value, as we do in line of business apps), // we inject our own multitenant validation logic ValidateIssuer = false, }, Notifications = new OpenIdConnectAuthenticationNotifications() { RedirectToIdentityProvider = (context) => { context.ProtocolMessage.Parameters.Add("lc", Resources.Culture.LCID.ToString()); return(Task.FromResult(0)); }, AuthorizationCodeReceived = async(context) => { string userTenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string signedInUserObjectId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; // login to the user AD tenant ClientCredential webPortalcredentials = new ClientCredential(ApplicationConfiguration.ActiveDirectoryClientID, ApplicationConfiguration.ActiveDirectoryClientSecret); AuthenticationContext userAuthContext = new AuthenticationContext(ApplicationConfiguration.ActiveDirectoryEndPoint + userTenantId); AuthenticationResult userAuthResult = userAuthContext.AcquireTokenByAuthorizationCodeAsync( context.Code, new Uri( HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), webPortalcredentials, ApplicationConfiguration.ActiveDirectoryGraphEndPoint).Result; // acquire a graph token to manage the user tenant Uri serviceRoot = new Uri(new Uri(ApplicationConfiguration.ActiveDirectoryGraphEndPoint), userTenantId); ActiveDirectoryClient userAdClient = new ActiveDirectoryClient(serviceRoot, async() => await Task.FromResult(userAuthResult.AccessToken)); // add the user roles to the claims var userMemberships = userAdClient.Users.GetByObjectId(signedInUserObjectId).MemberOf.ExecuteAsync().Result; foreach (var membership in userMemberships.CurrentPage) { DirectoryRole role = membership as DirectoryRole; if (role != null) { context.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, role.DisplayName)); } } if (userTenantId != ApplicationConfiguration.ActiveDirectoryTenantId) { string partnerCenterCustomerId = string.Empty; // Check to see if this login came from the tenant of a customer of the partner var customerDetails = await ApplicationDomain.Instance.PartnerCenterClient.Customers.ById(userTenantId).GetAsync(); // indeed a customer partnerCenterCustomerId = customerDetails.Id; if (!string.IsNullOrWhiteSpace(partnerCenterCustomerId)) { // add the customer ID to the claims context.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim("PartnerCenterCustomerID", partnerCenterCustomerId)); // fire off call to retrieve this customer's subscriptions and populate the CustomerSubscriptions Repository. } } else { if (context.AuthenticationTicket.Identity.FindFirst(System.Security.Claims.ClaimTypes.Role).Value != Startup.GlobalAdminUserRole) { // this login came from the partner's tenant, only allow admins to access the site, non admins will only // see the unauthenticated experience but they can't configure the portal nor can purchase Trace.TraceInformation("Blocked log in from non admin partner user: {0}", signedInUserObjectId); throw new AuthorizationException(System.Net.HttpStatusCode.Unauthorized, Resources.NonAdminUnauthorizedMessage); } } }, AuthenticationFailed = (context) => { // redirect to the error page string errorMessage = (context.Exception.InnerException == null) ? context.Exception.Message : context.Exception.InnerException.Message; context.OwinContext.Response.Redirect($"/Home/Error?errorMessage={errorMessage}"); context.HandleResponse(); return(Task.FromResult(0)); } } }); }
public static PSRoleAssignment ToPSRoleAssignment(this RoleAssignment assignment, AuthorizationClient policyClient, ActiveDirectoryClient activeDirectoryClient, bool excludeAssignmentsForDeletedPrincipals = true) { List <PSRoleDefinition> roleDefinitions = null; try { roleDefinitions = new List <PSRoleDefinition> { policyClient.GetRoleDefinition(assignment.RoleDefinitionId) }; } catch (CloudException ce) { if (ce.Response.StatusCode == HttpStatusCode.Unauthorized) { //Swallow unauthorized errors on RoleDefinition when displaying RoleAssignments roleDefinitions = new List <PSRoleDefinition>(); } else { throw; } } IEnumerable <RoleAssignment> assignments = new List <RoleAssignment> { assignment }; return(assignments.ToPSRoleAssignments(roleDefinitions, policyClient, activeDirectoryClient, excludeAssignmentsForDeletedPrincipals).SingleOrDefault()); }
/// <summary> /// Creates PoliciesClient using WindowsAzureSubscription instance. /// </summary> /// <param name="subscription">The WindowsAzureSubscription instance</param> public AuthorizationClient(AzureContext context) { ActiveDirectoryClient = new ActiveDirectoryClient(context); AuthorizationManagementClient = AzureSession.ClientFactory.CreateClient <AuthorizationManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager); }
public async Task <IActionResult> CreateAppRole() { //IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder // .Create("3a5022f7-db04-4b70-8e3b-636e04114a92") // .WithTenantId("938e704a-f4a7-49b7-9319-2cf16eb67c58") // .WithClientSecret("21bf68f3-72ec-4f56-9a6f-0c2a5cdeb732") // .Build(); //ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication); //IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder //.Create("3a5022f7-db04-4b70-8e3b-636e04114a92") //.WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdMultipleOrgs) //.Build(); //// Create an authentication provider by passing in a client application and graph scopes. //DeviceCodeProvider authProvider = new DeviceCodeProvider(publicClientApplication, new[] { "User.Read" }); //// Create a new instance of GraphServiceClient with the authentication provider. //GraphServiceClient graphClient = new GraphServiceClient(authProvider); //var app = InteractiveAuthenticationProvider.CreateClientApplication(""); //var authProvider = new InteractiveAuthenticationProvider(app, new[] { "User.Read" }); //var graphClient = new GraphServiceClient(authProvider); //var user = await graphClient.Me.Request().GetAsync(); //return Ok(user.DisplayName); Guid _id = Guid.NewGuid(); List <String> _AllowedMemberTypes = new List <string> { "User" }; AppRole appRole = new AppRole { AllowedMemberTypes = _AllowedMemberTypes, Description = "Admins can manage roles and perform all actions.", DisplayName = "Global Admin", Id = _id, IsEnabled = true, Value = "Admin" }; try { var graphResourceId = "https://graph.windows.net"; var tenantId = "938e704a-f4a7-49b7-9319-2cf16eb67c58"; var clientId = "3a5022f7-db04-4b70-8e3b-636e04114a92"; var secretKey = "Qn_87k~JRLxaUj7B5-W6PJuk2~PVo9o24_"; var servicePointUri = new Uri(graphResourceId); var serviceRoot = new Uri(servicePointUri, tenantId); var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async() => await GetAppTokenAsync(graphResourceId, tenantId, clientId, secretKey)); IPagedCollection <IApplication> pagedCollection = await activeDirectoryClient.Applications.Where(x => x.AppId == clientId).ExecuteAsync(); var appObject = pagedCollection.CurrentPage.ToList().FirstOrDefault(); appObject.AppRoles.Add(appRole as AppRole); await appObject.UpdateAsync(); return(Ok("succeed")); } catch (Exception ex) { return(Ok(ex.Message)); } }
public MailStoreProviderBase(string userName, string password) { _adClient = AuthenticationHelper.GetGraphClientAsync(userName, password).GetResult(); }
protected async void Page_Load(object sender, EventArgs e) { try { ClientCredential credential = new ClientCredential(Constants.AzureActiveDirectory.ClientId, Constants.AzureActiveDirectory.AppKey); var authContext = new AuthenticationContext(string.Format(Constants.AzureActiveDirectory.Authority, Constants.AzureActiveDirectory.TenantId)); var code = ValidationHelper.GetString(HttpContext.Current.Request.QueryString["code"], string.Empty); AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential, string.Format(Constants.AzureActiveDirectory.GraphResourceUri, "")); var adClient = new ActiveDirectoryClient( new Uri(string.Format(Constants.AzureActiveDirectory.GraphResourceUri, result.TenantId)), async() => await GetAppTokenAsync(result.TenantId)); var adUser = (User) await adClient.Users.Where(x => x.UserPrincipalName.Equals(result.UserInfo.DisplayableId)) .Expand(x => x.MemberOf) .ExecuteSingleAsync(); var user = UserInfoProvider.GetUsers() .Where("AzureADUsername", QueryOperator.Equals, adUser.UserPrincipalName) .FirstOrDefault(); var groupsToAdd = adUser.MemberOf.OfType <Group>() .Select(x => x.DisplayName) .Where(x => Constants.AzureActiveDirectory.GroupsToSync.Contains(x)); var groupsToRemove = Constants.AzureActiveDirectory.GroupsToSync .Where(x => !groupsToAdd.Contains(x)); if (user == null) { user = new CMS.Membership.UserInfo(); user.UserName = adUser.UserPrincipalName; user.FirstName = adUser.GivenName; user.LastName = adUser.Surname; user.FullName = adUser.DisplayName; user.Email = adUser.Mail.IfEmpty(adUser.OtherMails.FirstOrDefault()); user.SetValue("AzureADUsername", adUser.UserPrincipalName); user.IsExternal = true; user.Enabled = true; UserInfoProvider.SetUserInfo(user); UserInfoProvider.AddUserToSite(user.UserName, SiteContext.CurrentSiteName); foreach (var group in groupsToAdd) { UserInfoProvider.AddUserToRole(user.UserName, RoleInfoProvider.GetRoles() .OnSite(SiteContext.CurrentSiteID) .Where("RoleDisplayName", QueryOperator.Equals, group) .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName); } } else { user.FirstName = adUser.GivenName; user.LastName = adUser.Surname; user.FullName = adUser.DisplayName; user.Email = adUser.Mail.IfEmpty(adUser.OtherMails.FirstOrDefault()); user.IsExternal = true; UserInfoProvider.SetUserInfo(user); UserInfoProvider.AddUserToSite(user.UserName, SiteContext.CurrentSiteName); foreach (var group in groupsToAdd) { UserInfoProvider.AddUserToRole(user.UserName, RoleInfoProvider.GetRoles() .OnSite(SiteContext.CurrentSiteID) .Where("RoleDisplayName", QueryOperator.Equals, group) .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName); } foreach (var group in groupsToRemove) { UserInfoProvider.RemoveUserFromRole(user.UserName, RoleInfoProvider.GetRoles() .OnSite(SiteContext.CurrentSiteID) .Where("RoleDisplayName", QueryOperator.Equals, group) .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName); } } AuthenticationHelper.AuthenticateUser(user.UserName, false); MembershipActivityLogger.LogLogin(user.UserName, DocumentContext.CurrentDocument); } catch (Exception exception) { EventLogProvider.LogException("AzureActiveDirectory", "Login", exception); } var postLoginPage = DocumentHelper.GetDocuments() .WhereEquals("NodeAliasPath", Constants.AzureActiveDirectory.PostLoginPage) .FirstOrDefault(x => x.DocumentCulture.Equals(LocalizationContext.CurrentCulture.CultureCode, StringComparison.InvariantCultureIgnoreCase)); var returnUrl = HttpContext.Current.Request.GetReturnUrl(postLoginPage.GetRelativeUrl()); URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl)); }
public async Task <ActionResult> Index() { Session["ErrorMessage"] = null; Session["ErrorCode"] = null; Session["ErrorType"] = null; if (!Request.IsAuthenticated) { return(RedirectToAction("SignIn", "Account")); } int authUser = -1; string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; try { Uri servicePointUri = new Uri(graphResourceID); Uri serviceRoot = new Uri(servicePointUri, tenantID); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async() => await GetTokenForApplication()); var result = await activeDirectoryClient.Users .Where(u => u.ObjectId.Equals(userObjectID)) .ExecuteAsync(); IUser user = result.CurrentPage.ToList().First(); if (user != null) { bool isAuthenticated = isAuth(); if (isAuthenticated == false) { UserProfile userProfile = new DataAccess().getUserProfile(user.Mail.ToLower()); //UserProfile userProfile = new DataAccess().getUserProfile("*****@*****.**"); //UserProfile userProfile = new DataAccess().getUserProfile("*****@*****.**"); if (!Models.Utils.isValidUserObject(userProfile)) { return(RedirectToAction("Update", "UserProfile")); } else if (userProfile.Active != 1) { Session["ErrorType"] = "InactiveUser"; Session["ErrorMessage"] = "Your account is disabled. <br/> Please contact HCM"; Session["ErrorCode"] = "500"; return(RedirectToAction("OpError", "ErrorHandilar")); } Session["UserProfileSession"] = userProfile; } } else { throw new Exception("Invalid opration"); } ViewData["UserProfileSession"] = (Session["UserProfileSession"] as UserProfile); List <UserRequestUiGridRender> userRequestUiGridRenders = new DataAccess().getUserHcmActiveRequests((Session["UserProfileSession"] as UserProfile).Id, 5); List <UserRequestUiGridRender> userRequestApproverUiGridRenders = new DataAccess().getHcmActiveApproverRequests((Session["UserProfileSession"] as UserProfile).Id, 5); ViewData["userRequestApproverUiGridRenders"] = userRequestApproverUiGridRenders; ViewData["userRequestUiGridRenders"] = userRequestUiGridRenders; return(View()); } catch (AdalException) { // Return to error page. return(View("Error")); } // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token catch (Exception e1) { return(RedirectToAction("SignIn", "Account")); } }
public async Task <ActionResult> AddUser() { ActiveDirectoryClient activeDirectoryClient = GraphHelper.ActiveDirectoryClient(); Dictionary <string, IEnumerable <string> > model = new Dictionary <string, IEnumerable <string> >(); List <string> users = null; var groups = await activeDirectoryClient.Groups.Where(group => group.ObjectId.Equals(Config.SecurityGroups[Config.Roles.User])).ExecuteAsync(); IGroupFetcher retrievedGroupFetcher = groups.CurrentPage.FirstOrDefault() as Group; if (retrievedGroupFetcher != null) { users = new List <string>(); IPagedCollection <IDirectoryObject> members = await retrievedGroupFetcher.Members.ExecuteAsync(); do { List <IDirectoryObject> directoryObjects = members.CurrentPage.ToList(); foreach (IDirectoryObject member in directoryObjects) { if (member is User) { User user = member as User; users.Add(string.Format("{0}, ({1})", user.DisplayName, user.UserPrincipalName)); } else if (member is Group) { Group group = member as Group; users.Add(string.Format("{0}, (Group)", group.DisplayName)); } else if (member is Contact) { Contact contact = member as Contact; users.Add(string.Format("{0}, (Contact)", contact.DisplayName)); } } members = members.GetNextPageAsync().Result; } while (members != null); } model.Add(Config.Roles.User, users); users = null; groups = await activeDirectoryClient.Groups.Where(group => group.ObjectId.Equals(Config.SecurityGroups[Config.Roles.Admin])).ExecuteAsync(); retrievedGroupFetcher = groups.CurrentPage.FirstOrDefault() as Group; users = new List <string>(); if (retrievedGroupFetcher != null) { users = new List <string>(); IPagedCollection <IDirectoryObject> members = await retrievedGroupFetcher.Members.ExecuteAsync(); do { List <IDirectoryObject> directoryObjects = members.CurrentPage.ToList(); foreach (IDirectoryObject member in directoryObjects) { if (member is User) { User user = member as User; users.Add(string.Format("{0}, ({1})", user.DisplayName, user.UserPrincipalName)); } if (member is Group) { Group group = member as Group; users.Add(string.Format("Group - {0}", group.DisplayName)); } if (member is Contact) { Contact contact = member as Contact; users.Add(string.Format("Contact - {0}", contact.DisplayName)); } } members = members.GetNextPageAsync().Result; } while (members != null); } model.Add(Config.Roles.Admin, users); users = null; groups = await activeDirectoryClient.Groups.Where(group => group.ObjectId.Equals(Config.SecurityGroups[Config.Roles.Support])).ExecuteAsync(); retrievedGroupFetcher = groups.CurrentPage.FirstOrDefault() as Group; users = new List <string>(); if (retrievedGroupFetcher != null) { users = new List <string>(); IPagedCollection <IDirectoryObject> members = await retrievedGroupFetcher.Members.ExecuteAsync(); do { List <IDirectoryObject> directoryObjects = members.CurrentPage.ToList(); foreach (IDirectoryObject member in directoryObjects) { if (member is User) { User user = member as User; users.Add(string.Format("{0}, ({1})", user.DisplayName, user.UserPrincipalName)); } if (member is Group) { Group group = member as Group; users.Add(string.Format("Group - {0}", group.DisplayName)); } if (member is Contact) { Contact contact = member as Contact; users.Add(string.Format("Contact - {0}", contact.DisplayName)); } } members = members.GetNextPageAsync().Result; } while (members != null); } model.Add(Config.Roles.Support, users); return(View(model)); }
//https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/docs/overview.md private static void CreateAzuregraphClient(string token) { ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(new Uri("https://graph.windows.net/tesla329.onmicrosoft.com"), async() => { return(await GetAccessToken()); }); var user = activeDirectoryClient.Users["*****@*****.**"]; }
public async static Task <ServicePrincipalResponse> CreateAppAndServicePrincipal(string displayName, string appIdUri, string password, string tenantId) { // // First create the Azure AD Graph API client proxy // var token = AuthenticationConfig.SessionItems.GraphAuthToken; var baseUri = new Uri(GRAPH_BASEURL); var adClient = new ActiveDirectoryClient ( new Uri(baseUri, tenantId), async() => { if (token == null) { throw new Exception("Authorization required before calling into Graph!"); } return(await Task.FromResult <string>(token)); } ); // // First create the app backing up the service principal // try { var appResponse = await CreateAppObjectIfNotExists(displayName, appIdUri, adClient); // // Now we can create the service principal to be created in the AD // var spResponse = await CreateServicePrincipalIfNotExists( appResponse.App, password, adClient ); // // Finally return the AppId // return(await Task.FromResult ( new ServicePrincipalResponse { App = appResponse.App, IsNewApp = appResponse.IsNewApp, Principal = spResponse.Principal, IsNewPrincipal = spResponse.IsNewPrincipal } )); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); if (ex.InnerException != null) { Debug.WriteLine(ex.InnerException.ToString()); } throw; } }
/// <summary> /// Checks that a Graph client is available. /// </summary> /// <returns>The Graph client.</returns> public static async Task <ActiveDirectoryClient> EnsureGraphClientCreatedAsync() { // Active Directory service endpoints const string AadServiceResourceId = "https://graph.windows.net/"; Uri AadServiceEndpointUri = new Uri("https://graph.windows.net/"); try { AuthenticationContext = new AuthenticationContext(AadAuthority); TokenCacheItem cacheItem = null; if (AuthenticationContext.TokenCache.ReadItems().Count() > 0) { // Bind the AuthenticationContext to the authority that sourced the token in the cache // this is needed for the cache to work when asking for a token from that authority // (the common endpoint never triggers cache hits) cacheItem = AuthenticationContext.TokenCache.ReadItems().First(); AuthenticationContext = new AuthenticationContext(cacheItem.Authority); } else { // Nothing was found in the cache, so let's acquire a token. var token = await AcquireTokenAsync(AuthenticationContext, AadServiceResourceId); // Check the token if (String.IsNullOrEmpty(token)) { // User cancelled sign-in return(null); } else { // If a token was acquired, the TokenCache will contain a TokenCacheItem containing // all the details of the authorization. cacheItem = AuthenticationContext.TokenCache.ReadItems().First(); } } // Store the Id of the logged-in user so that we can retrieve more user info later. _loggedInUser = cacheItem.UniqueId; // Create our ActiveDirectory client. var client = new ActiveDirectoryClient( new Uri(AadServiceEndpointUri, cacheItem.TenantId), async() => await AcquireTokenAsync(AuthenticationContext, AadServiceResourceId)); return(client); } // The following is a list of all exceptions you should consider handling in your app. // In the case of this sample, the exceptions are handled by returning null upstream. catch (DiscoveryFailedException dfe) { MessageDialogHelper.DisplayException(dfe as Exception); // Discovery failed. AuthenticationContext.TokenCache.Clear(); return(null); } catch (MissingConfigurationValueException mcve) { MessageDialogHelper.DisplayException(mcve); // Connected services not added correctly, or permissions not set correctly. AuthenticationContext.TokenCache.Clear(); return(null); } catch (AuthenticationFailedException afe) { MessageDialogHelper.DisplayException(afe); // Failed to authenticate the user AuthenticationContext.TokenCache.Clear(); return(null); } catch (ArgumentException ae) { MessageDialogHelper.DisplayException(ae as Exception); // Argument exception AuthenticationContext.TokenCache.Clear(); return(null); } }
public static void Main(string[] args) { Boolean syncParam = false; Boolean deleteParam = false; for (int i = 0; i < args.Length; i++) { if (args[i].ToLower().Equals("-sync")) { syncParam = true; } else if (args[i].ToLower().Equals("-delete")) { deleteParam = true; } } Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); AppSettingsSection amSection = (AppSettingsSection)config.Sections["AMSettings"]; ActiveDirectoryClient client = new ActiveDirectoryClient(config); client.getUserDetailsFromActiveDirectory( amSection.Settings["UserExcludeFilter"].Value, amSection.Settings["ExcludeDisableAccount"].Value ); string[] csvStr = client.createImportFile(); Console.WriteLine("################### Sync Users - Start ###################"); Console.WriteLine(""); StringBuilder importDataStr = new StringBuilder(); for (int i = 0; i < csvStr.Length; i++) { importDataStr.AppendLine(csvStr[i]); Console.WriteLine(csvStr[i]); } string response = ""; if (syncParam) { response = client.uploadToAlertMedia(importDataStr.ToString()); Console.WriteLine("*********************************************************"); Console.WriteLine(""); Console.WriteLine(response); Console.WriteLine(""); Console.WriteLine("*********************************************************"); } else { Console.WriteLine("*********************************************************"); Console.WriteLine(""); Console.WriteLine(" Above listed users have not been synced to AlertMedia. This was a dry run. To actually sync them, you need to send an args parameter (-sync)"); Console.WriteLine(""); Console.WriteLine("*********************************************************"); } Console.WriteLine(""); Console.WriteLine("################### Sync Users - End ###################"); if (syncParam) { ArrayList importedUserList = new ArrayList(); JavaScriptSerializer j = new JavaScriptSerializer(); Dictionary <string, object> a = (Dictionary <string, object>)j.Deserialize(response, typeof(Dictionary <string, object>)); StringBuilder textBoxResponse = new StringBuilder(); if (a.ContainsKey("stats")) { importedUserList = (ArrayList)a["successes"]; ArrayList failuresList = (ArrayList)a["failures"]; for (int i = 0; i < failuresList.Count; i++) { importedUserList.Add(failuresList[i]); } } Console.WriteLine("################### Delete Users - Start ###################"); Console.WriteLine(""); string[] delCsvStr = client.previewDeleteUserList(importedUserList); ArrayList deletedUserIdList = new ArrayList(); for (int i = 1; i < delCsvStr.Length; i++) { string strLine = delCsvStr[i]; Console.WriteLine(strLine); List <string> fields = SplitCSV(strLine); deletedUserIdList.Add(fields[0].Replace("\"", "")); } if (deleteParam) { client.deleteUsersFromAlertMedia(deletedUserIdList); Console.WriteLine("*********************************************************"); Console.WriteLine(""); Console.WriteLine(" All the " + deletedUserIdList.Count + " users have been deleted from AlertMedia "); Console.WriteLine(""); Console.WriteLine("*********************************************************"); } else { Console.WriteLine("*********************************************************"); Console.WriteLine(""); Console.WriteLine(deletedUserIdList.Count + " of the above listed users have not been deleted from AlertMedia. This was a dry run. To actually delete them, you need to send two args parameter (-sync -delete)"); Console.WriteLine(""); Console.WriteLine("*********************************************************"); } Console.WriteLine(""); Console.WriteLine("################### Sync Users - End ###################"); Console.ReadLine(); } }
static async Task Main(string[] args) { configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); graphResourceId = configuration["AzureAd:GraphResourceId"]; azureRmResourceId = configuration["AzureAd:AzureRmResourceId"]; authContext = new AuthenticationContext(configuration["AzureAd:Instance"]); // Prompt here so we make sure we're in the right directory var token = await authContext.AcquireTokenAsync(graphResourceId, ClientId, RedirectUri, new PlatformParameters(PromptBehavior.SelectAccount)); authResult = token; if ("f8cdef31-a31e-4b4a-93e4-5f571e91255a".Equals(token.TenantId, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Microsoft Accounts's with the common endpoint are not supported. Update appsettings.json with your tenant-specific endpoint"); return; } graphClient = new ActiveDirectoryClient(new Uri($"{graphResourceId}{token.TenantId}"), async() => (await authContext.AcquireTokenSilentAsync(graphResourceId, ClientId)).AccessToken); if (args.Length > 0) { // Read a disambiguation value environment = $" ({args[0]}) "; } var serverDisplayNamePrefix = $"{SignServerName}{environment} - "; Guid applicationId; string password = null; // Try to find a "SignService Server -" app IPagedCollection <IApplication> a; try { a = await graphClient.Applications.Where(ia => ia.DisplayName.StartsWith(serverDisplayNamePrefix)).ExecuteAsync(); } catch (Exception) { Console.WriteLine("Guest users are not supported. You must be a member user."); return; } if (a.CurrentPage.Count == 1) { applicationId = Guid.Parse(a.CurrentPage[0].ObjectId); Console.WriteLine($"Found application '{a.CurrentPage[0].DisplayName}'"); Console.WriteLine("Enter [Y/n] to continue: "); var key = Console.ReadLine().ToUpperInvariant().Trim(); if (!(key == string.Empty || key == "Y")) { Console.WriteLine("Exiting...."); return; } } else { // Ensure the Key Vault SP exists, as it might not if a key vault hasn't been created yet await EnsureServicePrincipalExists("cfa8b339-82a2-471a-a3c9-0fc0be7a4093"); var appName = $"{serverDisplayNamePrefix}{Guid.NewGuid()}"; Console.WriteLine($"Creating application '{appName}'"); // Create var newApp = await CreateApplication(appName); applicationId = newApp.Item1; password = newApp.Item2; Console.WriteLine("Created application"); } Console.WriteLine("Updating application...."); var serverApp = await ConfigureApplication(applicationId); var clientApp = await EnsureClientAppExists(serverApp.application); Console.WriteLine("Update complete."); // If password is not null, we created the app, add the user admin role assignment if (!string.IsNullOrWhiteSpace(password)) { await AddAdminRoleAssignmentToServer(serverApp.servicePrincipal); } // Prompt for consent await PromptForConsent(serverApp, clientApp); // Need to create a resource group and grant the sign service application the Read permissions await CreateOrUpdateResourceGroup(serverApp.servicePrincipal); // Print out relevant values PrintApplicationInfo(serverApp, password, clientApp); Console.WriteLine("Press any key to quit...."); Console.ReadKey(true); }