private void DeleteAdServicePrincipal(KeyVaultManagementController controllerAdmin, ServicePrincipal newServicePrincipal) { if (newServicePrincipal != null) { controllerAdmin.GraphClient.ServicePrincipals.Delete(newServicePrincipal.ObjectId); } }
public MyStack() { // Create an Azure Resource Group var resourceGroup = new ResourceGroup("azure-cs-aks"); // Create an AD service principal var adApp = new Application("aks", new ApplicationArgs { DisplayName = "aks" }); var adSp = new ServicePrincipal("aksSp", new ServicePrincipalArgs { ApplicationId = adApp.ApplicationId }); // Generate random password var password = new RandomPassword("password", new RandomPasswordArgs { Length = 20, Special = true }); // Create the Service Principal Password var adSpPassword = new ServicePrincipalPassword("aksSpPassword", new ServicePrincipalPasswordArgs { ServicePrincipalId = adSp.Id, Value = password.Result, EndDate = "2099-01-01T00:00:00Z" }); // Generate an SSH key var sshKey = new PrivateKey("ssh-key", new PrivateKeyArgs { Algorithm = "RSA", RsaBits = 4096 }); var cluster = new ManagedCluster("my-aks", new ManagedClusterArgs { ResourceGroupName = resourceGroup.Name, AddonProfiles = { { "KubeDashboard", new ManagedClusterAddonProfileArgs { Enabled = true } } }, AgentPoolProfiles = { new ManagedClusterAgentPoolProfileArgs { Count = 3, MaxPods = 110, Mode = "System", Name = "agentpool", OsDiskSizeGB = 30, OsType = "Linux", Type = "VirtualMachineScaleSets", VmSize = "Standard_DS2_v2", } }, DnsPrefix = "AzureNativeprovider", EnableRBAC = true, KubernetesVersion = "1.18.14", LinuxProfile = new ContainerServiceLinuxProfileArgs { AdminUsername = "******", Ssh = new ContainerServiceSshConfigurationArgs { PublicKeys = { new ContainerServiceSshPublicKeyArgs { KeyData = sshKey.PublicKeyOpenssh, } } } }, NodeResourceGroup = $"MC_azure-cs_my_aks", ServicePrincipalProfile = new ManagedClusterServicePrincipalProfileArgs { ClientId = adApp.ApplicationId, Secret = adSpPassword.Value } }); // Export the KubeConfig this.KubeConfig = Output.Tuple(resourceGroup.Name, cluster.Name).Apply(names => GetKubeConfig(names.Item1, names.Item2)); }
public List <PSADServicePrincipal> FilterServicePrincipals(ADObjectFilterOptions options) { List <PSADServicePrincipal> servicePrincipals = new List <PSADServicePrincipal>(); ServicePrincipalListResult result = new ServicePrincipalListResult(); ServicePrincipal servicePrincipal = null; if (!string.IsNullOrEmpty(options.Id)) { try { servicePrincipal = GraphClient.ServicePrincipal.Get(options.Id).ServicePrincipal; } catch { /* The user does not exist, ignore the exception. */ } if (servicePrincipal != null) { servicePrincipals.Add(servicePrincipal.ToPSADServicePrincipal()); } } else if (!string.IsNullOrEmpty(options.SPN)) { try { servicePrincipal = GraphClient.ServicePrincipal.GetByServicePrincipalName(options.SPN).ServicePrincipals.FirstOrDefault(); } catch { /* The user does not exist, ignore the exception. */ } if (servicePrincipal != null) { servicePrincipals.Add(servicePrincipal.ToPSADServicePrincipal()); } } else { if (options.Paging) { if (string.IsNullOrEmpty(options.NextLink)) { result = GraphClient.ServicePrincipal.List(options.SearchString); } else { result = GraphClient.ServicePrincipal.ListNext(options.NextLink); } servicePrincipals.AddRange(result.ServicePrincipals.Select(u => u.ToPSADServicePrincipal())); options.NextLink = result.NextLink; } else { result = GraphClient.ServicePrincipal.List(options.SearchString); servicePrincipals.AddRange(result.ServicePrincipals.Select(u => u.ToPSADServicePrincipal())); while (!string.IsNullOrEmpty(result.NextLink)) { result = GraphClient.ServicePrincipal.ListNext(result.NextLink); servicePrincipals.AddRange(result.ServicePrincipals.Select(u => u.ToPSADServicePrincipal())); } } } return(servicePrincipals); }
public async Task <ServiceBinding> BindAsync(ServiceBindingContext context, ServiceBindingRequest request) { LogContext(_log, "Bind", context); LogRequest(_log, request); // Retrieve Azure Storage account. var storageAccounts = await _azureStorageProviderClient.GetStorageAccountsByTag("cf_service_instance_id", context.InstanceId); var nrStorageAccounts = storageAccounts.Count(); if (nrStorageAccounts == 0) { var message = $"Could not find storage account with tag: cf_service_instance_id = {context.InstanceId}"; _log.LogWarning(message); throw new ArgumentException(message, nameof(context)); } if (nrStorageAccounts > 1) { var message = $"Found multiple storage accounts for tag: cf_service_instance_id = {context.InstanceId}"; _log.LogError(message); throw new ArgumentException(message, nameof(context)); } var storageAccount = storageAccounts.Single(); var storageAccountId = storageAccount.Id; // Must be in a separate method because Span is not allowed inside async methods. string GeneratePassword() { var randomNumberGenerator = new RNGCryptoServiceProvider(); var randomNr = new Span <byte>(new byte[16]); randomNumberGenerator.GetBytes(randomNr); return(Convert.ToBase64String(randomNr)); } // Create an Azure AD application. var clientSecret = GeneratePassword(); var application = new Application { DisplayName = context.BindingId, IdentifierUris = { $"https://{context.BindingId}" }, PasswordCredentials = { new PasswordCredential { StartDateTime = DateTimeOffset.UtcNow, EndDateTime = DateTimeOffset.UtcNow.AddYears(2), KeyId = Guid.NewGuid(), SecretText = clientSecret } }, SignInAudience = SignInAudience.AzureADMyOrg, Tags = { $"cf_service_id:{request.ServiceId}", $"cf_plan_id:{request.PlanId}", $"cf_binding_id:{context.BindingId}" } }; var createdApplication = await _msGraphClient.CreateApplication(application); // Create a service principal for the application in the same tenant. var servicePrincipal = new ServicePrincipal { AccountEnabled = true, AppId = createdApplication.AppId, DisplayName = createdApplication.DisplayName, Tags = { $"cf_service_id:{request.ServiceId}", $"cf_plan_id:{request.PlanId}", $"cf_binding_id:{context.BindingId}" } }; var createdServicePrincipal = await _msGraphClient.CreateServicePrincipal(servicePrincipal); var principalId = Guid.Parse(createdServicePrincipal.Id); // Assign service principal to roles Storage Blob Data Contributor and Storage Queue Data Contributor. var storageBlobDataContributorRoleId = Guid.Parse("ba92f5b4-2d11-453d-a403-e96b0029c9fe"); await GrantPrincipalAccessToStorageAccount(storageAccountId, storageBlobDataContributorRoleId, principalId); var storageQueueDataContributorRoleId = Guid.Parse("974c5e8b-45b9-4653-ba55-5f855dd0fb88"); await GrantPrincipalAccessToStorageAccount(storageAccountId, storageQueueDataContributorRoleId, principalId); // Get the access keys for the storage account. var storageAccountKeys = await _azureStorageClient.GetStorageAccountKeys(storageAccountId); return(new ServiceBinding { Credentials = JObject.FromObject(new StorageAccountCredentials { Urls = { BlobStorageUrl = $"https://{storageAccount.Name}.blob.core.windows.net", QueueStorageUrl = $"https://{storageAccount.Name}.queue.core.windows.net", TableStorageUrl = $"https://{storageAccount.Name}.table.core.windows.net", FileStorageUrl = $"https://{storageAccount.Name}.file.core.windows.net", }, SharedKeys = storageAccountKeys .Select(key => new SharedKey { Name = key.KeyName, Permissions = key.Permissions.ToString(), Value = key.Value }) .ToArray(), OAuthClientCredentials = { ClientId = createdApplication.AppId, ClientSecret = clientSecret, TokenEndpoint = $"https://login.microsoftonline.com/{_azureAuthOptions.TenantId}/oauth2/v2.0/token", Scopes = new[] { "https://management.core.windows.net/.default" }, GrantType = "client_credentials" } }) }); }
public void CreateDeleteSpCredentialTest() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { Application application = null; ServicePrincipal sp = null; try { // Create a new application without credentials application = CreateApplication(context); sp = CreateServicePrincipal(context, application.AppId); var spObjectId = sp.ObjectId; // Get Sp credentials - should be 0 var keyCreds = GetSpKeyCredential(context, spObjectId); Assert.Equal(0, keyCreds.Count); var passwordCreds = GetSpPasswordCredential(context, spObjectId); Assert.Equal(0, passwordCreds.Count); // Add a password credential string keyId = "dbf1c168-ebe9-4b93-8b14-83462734c164"; var passwordCredential1 = CreatePasswordCredential(keyId); UpdateSpPasswordCredential(context, spObjectId, passwordCredential1); // Add a keyCredential keyId = "9baef13d-5d0d-455e-9920-95acb87265e6"; var keyCredential = CreateKeyCredential(keyId); UpdateSpKeyCredential(context, spObjectId, keyCredential); // Get sp credentials keyCreds = GetSpKeyCredential(context, spObjectId); Assert.Equal(1, keyCreds.Count); Assert.True(keyCreds.Any(c => c.KeyId == keyCredential.KeyId)); passwordCreds = GetSpPasswordCredential(context, spObjectId); Assert.Equal(1, passwordCreds.Count); Assert.True(passwordCreds.Any(c => c.KeyId == passwordCredential1.KeyId)); // Append a new passwordCredential to exisitng credentials keyId = "debcca8c-4fa0-4b40-8d21-853a3213f328"; var passwordCredential2 = CreatePasswordCredential(keyId); passwordCreds.Add(passwordCredential2); UpdateSpPasswordCredential(context, spObjectId, passwordCreds); //Get var fetchedpasswordCreds2 = GetSpPasswordCredential(context, spObjectId); Assert.Equal(2, fetchedpasswordCreds2.Count); Assert.True(fetchedpasswordCreds2.Any(c => c.KeyId == passwordCredential2.KeyId)); Assert.True(fetchedpasswordCreds2.Any(c => c.KeyId == passwordCredential1.KeyId)); // Add 2 new password credentils -- older should be removed keyId = "19b89f7a-b2fd-444e-bed6-41d66df7eba5"; var passwordCredential3 = CreatePasswordCredential(keyId); keyId = "047db843-cff1-4e64-b924-8b235650a4c2"; var passwordCredential4 = CreatePasswordCredential(keyId); UpdateSpPasswordCredential(context, spObjectId, new List <PasswordCredential> { passwordCredential3, passwordCredential4 }); //Get var fetchedpasswordCreds3 = GetSpPasswordCredential(context, spObjectId); Assert.Equal(2, fetchedpasswordCreds3.Count); Assert.True(fetchedpasswordCreds3.Any(c => c.KeyId == passwordCredential3.KeyId)); Assert.True(fetchedpasswordCreds3.Any(c => c.KeyId == passwordCredential4.KeyId)); // Remove key credentials UpdateSpKeyCredential(context, spObjectId, new List <KeyCredential>()); // Get sp credentials var deletedkeyCreds = GetSpKeyCredential(context, spObjectId); Assert.Equal(0, deletedkeyCreds.Count); // Remove password credentials UpdateSpPasswordCredential(context, spObjectId, new List <PasswordCredential>()); // Get sp credentials var deletedPasswordCreds = GetSpPasswordCredential(context, spObjectId); Assert.Equal(0, deletedPasswordCreds.Count); } finally { if (sp != null) { DeleteServicePrincipal(context, sp.ObjectId); } if (application != null) { // Delete application DeleteApplication(context, application.ObjectId); } } } }
public async Task AddReaderIdentityToAccessPolicies(Guid subscriptionId, KeyVault keyVault, ServicePrincipal identity) { var accessToken = await GetAccessToken(); var token = new TokenCredentials(accessToken); var kvClient = new KeyVaultManagementClient(token) { SubscriptionId = subscriptionId.ToString() }; var vault = await kvClient.Vaults.GetAsync(keyVault.ResourceGroupName, keyVault.Name); var accessPolicies = vault.Properties.AccessPolicies; if (accessPolicies.All(ap => ap.ObjectId != identity.ObjectId.ToString())) { // This identity doesn't exist, lets add it. accessPolicies.Add(new AccessPolicyEntry( identity.TenantId, identity.ObjectId.ToString(), new Microsoft.Azure.Management.KeyVault.Models.Permissions( secrets: new[] { "Get", "List" }, certificates: new[] { "Get", "List" }))); await kvClient.Vaults.UpdateWithHttpMessagesAsync(keyVault.ResourceGroupName, keyVault.Name, new VaultPatchParameters(properties : new VaultPatchProperties(accessPolicies : accessPolicies))); } }
public List <PSADServicePrincipal> FilterServicePrincipals(ADObjectFilterOptions options) { List <PSADServicePrincipal> servicePrincipals = new List <PSADServicePrincipal>(); IPage <ServicePrincipal> result = null; ServicePrincipal servicePrincipal = null; if (!string.IsNullOrEmpty(options.Id)) { try { servicePrincipal = GraphClient.ServicePrincipals.Get(options.Id); } catch { /* The user does not exist, ignore the exception. */ } if (servicePrincipal != null) { servicePrincipals.Add(servicePrincipal.ToPSADServicePrincipal()); } } else if (!string.IsNullOrEmpty(options.SPN)) { try { var odataQuery = new Rest.Azure.OData.ODataQuery <ServicePrincipal>(s => s.ServicePrincipalNames.Contains(options.SPN)); servicePrincipal = GraphClient.ServicePrincipals.List(odataQuery.ToString()).FirstOrDefault(); } catch { /* The user does not exist, ignore the exception. */ } if (servicePrincipal != null) { servicePrincipals.Add(servicePrincipal.ToPSADServicePrincipal()); } } else { if (options.Paging) { if (string.IsNullOrEmpty(options.NextLink)) { var odataQuery = new Rest.Azure.OData.ODataQuery <ServicePrincipal>(s => s.DisplayName.StartsWith(options.SearchString)); result = GraphClient.ServicePrincipals.List(odataQuery); } else { result = GraphClient.ServicePrincipals.ListNext(options.NextLink); } servicePrincipals.AddRange(result.Select(u => u.ToPSADServicePrincipal())); options.NextLink = result.NextPageLink; } else { var odataQuery = new Rest.Azure.OData.ODataQuery <ServicePrincipal>(s => s.DisplayName.StartsWith(options.SearchString)); result = GraphClient.ServicePrincipals.List(odataQuery.ToString()); servicePrincipals.AddRange(result.Select(u => u.ToPSADServicePrincipal())); while (!string.IsNullOrEmpty(result.NextPageLink)) { result = GraphClient.ServicePrincipals.ListNext(result.NextPageLink); servicePrincipals.AddRange(result.Select(u => u.ToPSADServicePrincipal())); } } } return(servicePrincipals); }
private static void Main() { // record start DateTime of execution string currentDateTime = DateTime.Now.ToUniversalTime().ToString(); #region Setup Active Directory Client //********************************************************************* // setup Active Directory Client //********************************************************************* ActiveDirectoryClient activeDirectoryClient; 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 #region TenantDetails //********************************************************************* // Get Tenant Details // Note: update the string TenantId with your TenantId. // This can be retrieved from the login Federation Metadata end point: // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml // Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization // The returned value from the first xml node "EntityDescriptor", will have a STS URL // containing your TenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com //********************************************************************* VerifiedDomain initialDomain = new VerifiedDomain(); VerifiedDomain defaultDomain = new VerifiedDomain(); ITenantDetail tenant = null; Console.WriteLine("\n Retrieving Tenant Details"); try { List <ITenantDetail> tenantsList = activeDirectoryClient.TenantDetails .Where(tenantDetail => tenantDetail.ObjectId.Equals(Constants.TenantId)) .ExecuteAsync().Result.CurrentPage.ToList(); if (tenantsList.Count > 0) { tenant = tenantsList.First(); } } catch (Exception e) { Console.WriteLine("\nError getting TenantDetails {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } if (tenant == null) { Console.WriteLine("Tenant not found"); } else { TenantDetail tenantDetail = (TenantDetail)tenant; Console.WriteLine("Tenant Display Name: " + tenantDetail.DisplayName); // Get the Tenant's Verified Domains initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value); Console.WriteLine("Initial Domain Name: " + initialDomain.Name); defaultDomain = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]); Console.WriteLine("Default Domain Name: " + defaultDomain.Name); // Get Tenant's Tech Contacts foreach (string techContact in tenantDetail.TechnicalNotificationMails) { Console.WriteLine("Tenant Tech Contact: " + techContact); } } #endregion #region Create a new User IUser newUser = new User(); if (defaultDomain.Name != null) { newUser.DisplayName = "demo1"; newUser.UserPrincipalName = "xuhua00101" + "@" + defaultDomain.Name; newUser.AccountEnabled = true; newUser.MailNickname = "SampleAppDemoUserManager"; newUser.PasswordPolicies = "DisablePasswordExpiration"; newUser.PasswordProfile = new PasswordProfile { Password = "******", ForceChangePasswordNextLogin = true }; newUser.UsageLocation = "US"; try { //activeDirectoryClient.Users.AddUserAsync(newUser).Wait(); Console.WriteLine("\nNew User {0} was created", newUser.DisplayName); } catch (Exception e) { Console.WriteLine("\nError creating new user {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } } #endregion // IApplication APPl = new Application(); //// APPl.AppId = "12345678"; // // APPl.AppRoles = // APPl.AvailableToOtherTenants = false; // APPl.DisplayName = "vik00de"; //// APPl.IdentifierUris // APPl.Homepage = "https://ww.baidu.com"; // // APPl.IdentifierUris = "https://ww.baidu.com1"; // APPl.LogoutUrl = "https://ww.baidu.com"; // APPl.ErrorUrl = "https://ww.baidu.com1/1"; //// IList<string> ls = APPl.IdentifierUris; //APPl.IdentifierUris.Add("https://localhost/demo/" + Guid.NewGuid()); Application newApp = new Application { DisplayName = "wode" + Helper.GetRandomString(8) }; newApp.IdentifierUris.Add("https://localhost/demo1/" + Guid.NewGuid()); newApp.ReplyUrls.Add("https://localhost/demo1"); newApp.PublicClient = null; AppRole appRole = new AppRole() { Id = Guid.NewGuid(), IsEnabled = true, DisplayName = "Something", Description = "Anything", Value = "policy.write" }; appRole.AllowedMemberTypes.Add("User"); newApp.AppRoles.Add(appRole); //AzureADServicePrincipal //PasswordCredential password = new PasswordCredential //{ // StartDate = DateTime.UtcNow, // EndDate = DateTime.UtcNow.AddYears(1), // Value = "password", // KeyId = Guid.NewGuid() //}; //newApp.PasswordCredentials.Add(password); try { activeDirectoryClient.Applications.AddApplicationAsync(newApp).Wait(); Console.WriteLine("New Application created: " + newApp.DisplayName); } catch (Exception e) { string a = e.Message.ToString(); // Program.WriteError("\nError ceating Application: {0}", Program.ExtractErrorMessage(e)); } ServicePrincipal s = new ServicePrincipal(); s.Tags.Add("WindowsAzureActiveDirectoryIntegratedApp"); s.AppId = newApp.AppId; try { activeDirectoryClient.ServicePrincipals.AddServicePrincipalAsync(s).Wait(); } catch (Exception e) { string a = e.Message.ToString(); } //try //{ // activeDirectoryClient.Applications.AddApplicationAsync(appObject).Wait(); //} //catch (Exception e) { // string mess = e.Message.ToString(); // string a = ""; //} #region Create a User with a temp Password //********************************************************************************************* // Create a new User with a temp Password //********************************************************************************************* IUser userToBeAdded = new User(); userToBeAdded.DisplayName = "Sample App Demo User"; userToBeAdded.UserPrincipalName = Helper.GetRandomString(10) + "@" + defaultDomain.Name; userToBeAdded.AccountEnabled = true; userToBeAdded.MailNickname = "SampleAppDemoUser"; userToBeAdded.PasswordProfile = new PasswordProfile { Password = "******", ForceChangePasswordNextLogin = true }; userToBeAdded.UsageLocation = "US"; try { activeDirectoryClient.Users.AddUserAsync(userToBeAdded).Wait(); Console.WriteLine("\nNew User {0} was created", userToBeAdded.DisplayName); } catch (Exception e) { Console.WriteLine("\nError creating new user. {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // activeDirectoryClient.Applications.AddApplicationAsync(iApp); #endregion #region Create a new Group //********************************************************************************************* // Create a new Group //********************************************************************************************* Group californiaEmployees = new Group { DisplayName = "California Employees" + Helper.GetRandomString(8), Description = "Employees in the state of California", MailNickname = "CalEmployees", MailEnabled = false, SecurityEnabled = true }; try { activeDirectoryClient.Groups.AddGroupAsync(californiaEmployees).Wait(); Console.WriteLine("\nNew Group {0} was created", californiaEmployees.DisplayName); } catch (Exception e) { Console.WriteLine("\nError creating new Group {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } #endregion #region Search for Group using StartWith filter //********************************************************************* // Search for a group using a startsWith filter (displayName property) //********************************************************************* Group retrievedGroup = new Group(); string searchString = "California Employees"; List <IGroup> foundGroups = null; try { foundGroups = activeDirectoryClient.Groups .Where(group => group.DisplayName.StartsWith(searchString)) .ExecuteAsync().Result.CurrentPage.ToList(); } catch (Exception e) { Console.WriteLine("\nError getting Group {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } if (foundGroups != null && foundGroups.Count > 0) { retrievedGroup = foundGroups.First() as Group; } else { Console.WriteLine("Group Not Found"); } #endregion #region Assign Member to Group if (retrievedGroup.ObjectId != null) { try { retrievedGroup.Members.Add(newUser as DirectoryObject); retrievedGroup.UpdateAsync().Wait(); } catch (Exception e) { Console.WriteLine("\nError assigning member to group. {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } } #endregion #region Add User to Group //********************************************************************************************* // Add User to the "WA" Group //********************************************************************************************* if (retrievedGroup.ObjectId != null) { try { retrievedGroup.Members.Add(userToBeAdded as DirectoryObject); retrievedGroup.UpdateAsync().Wait(); } catch (Exception e) { Console.WriteLine("\nAdding user to group failed {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } } #endregion #region Get Group members if (retrievedGroup.ObjectId != null) { Console.WriteLine("\n Found Group: " + retrievedGroup.DisplayName + " " + retrievedGroup.Description); //********************************************************************* // get the groups' membership - // Note this method retrieves ALL links in one request - please use this method with care - this // may return a very large number of objects //********************************************************************* IGroupFetcher retrievedGroupFetcher = retrievedGroup; try { IPagedCollection <IDirectoryObject> members = retrievedGroupFetcher.Members.ExecuteAsync().Result; Console.WriteLine(" Members:"); do { List <IDirectoryObject> directoryObjects = members.CurrentPage.ToList(); foreach (IDirectoryObject member in directoryObjects) { if (member is User) { User user = member as User; Console.WriteLine("User DisplayName: {0} UPN: {1}", user.DisplayName, user.UserPrincipalName); } if (member is Group) { Group group = member as Group; Console.WriteLine("Group DisplayName: {0}", group.DisplayName); } if (member is Contact) { Contact contact = member as Contact; Console.WriteLine("Contact DisplayName: {0}", contact.DisplayName); } } members = members.GetNextPageAsync().Result; } while (members != null); } catch (Exception e) { Console.WriteLine("\nError getting groups' membership. {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } } #endregion //********************************************************************************************* // End of Demo Console App //********************************************************************************************* Console.WriteLine("\nCompleted at {0} \n Press Any Key to Exit.", currentDateTime); // Console.ReadKey(); Console.WriteLine(); #region Search User by UPN // search for a single user by UPN searchString = "" + "@" + initialDomain.Name; Console.WriteLine("\n Retrieving user with UPN {0}", searchString); User retrievedUser = new User(); List <IUser> retrievedUsers = null; try { retrievedUsers = activeDirectoryClient.Users .Where(user => user.UserPrincipalName.Equals(searchString)) .ExecuteAsync().Result.CurrentPage.ToList(); } catch (Exception e) { Console.WriteLine("\nError getting new user {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // should only find one user with the specified UPN if (retrievedUsers != null && retrievedUsers.Count == 1) { retrievedUser = (User)retrievedUsers.First(); } else { Console.WriteLine("User not found {0}", searchString); } #endregion Console.WriteLine("\n {0} is a member of the following Group and Roles (IDs)", retrievedUser.DisplayName); IUserFetcher retrievedUserFetcher = retrievedUser; try { 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} Description: {1}", group.DisplayName, group.Description); } 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); } catch (Exception e) { Console.WriteLine("\nError getting user's groups and roles memberships. {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } Console.WriteLine("Press any key to continue...."); Console.ReadKey(); }
public void AddToServicePrincipals(ServicePrincipal servicePrincipal) { base.AddObject("ServicePrincipals", servicePrincipal); }
public static ServicePrincipal CreateServicePrincipal(string objectReference, global::System.Collections.ObjectModel.ObservableCollection<string> servicePrincipalNames, global::System.Collections.ObjectModel.ObservableCollection<string> tags, global::System.Collections.ObjectModel.ObservableCollection<Credential> credentials, global::System.Collections.ObjectModel.ObservableCollection<AppAddress> appAddresses) { ServicePrincipal servicePrincipal = new ServicePrincipal(); servicePrincipal.ObjectReference = objectReference; if ((servicePrincipalNames == null)) { throw new global::System.ArgumentNullException("servicePrincipalNames"); } servicePrincipal.ServicePrincipalNames = servicePrincipalNames; if ((tags == null)) { throw new global::System.ArgumentNullException("tags"); } servicePrincipal.Tags = tags; if ((credentials == null)) { throw new global::System.ArgumentNullException("credentials"); } servicePrincipal.Credentials = credentials; if ((appAddresses == null)) { throw new global::System.ArgumentNullException("appAddresses"); } servicePrincipal.AppAddresses = appAddresses; return servicePrincipal; }
public async Task RegisterApplicationsAsync( string applicationName, DirectoryObject owner, IEnumerable <string> tags = null, CancellationToken cancellationToken = default ) { tags ??= new List <string>(); var serviceApplicationName = applicationName + "-service"; var clientApplicationName = applicationName + "-client"; var aksApplicationName = applicationName + "-aks"; // Service Application ///////////////////////////////////////////// // Register service application _serviceApplication = await RegisterServiceApplicationAsync( serviceApplicationName, owner, tags, cancellationToken ); // Find service principal for service application _serviceApplicationSP = await _msGraphServiceClient .GetApplicationServicePrincipalAsync(_serviceApplication, cancellationToken); // Add current user or service principal as app owner for service // application, if it is not owner already. await _msGraphServiceClient .AddAsApplicationOwnerAsync( _serviceApplication, owner, cancellationToken ); // Client Application ////////////////////////////////////////////// // Register client application _clientApplication = await RegisterClientApplicationAsync( _serviceApplication, clientApplicationName, tags, cancellationToken ); // Find service principal for client application _clientApplicationSP = await _msGraphServiceClient .GetApplicationServicePrincipalAsync(_clientApplication, cancellationToken); // Add current user or service principal as app owner for client // application, if it is not owner already. await _msGraphServiceClient .AddAsApplicationOwnerAsync( _clientApplication, owner, cancellationToken ); // Update service application to include client application as knownClientApplications _serviceApplication = await _msGraphServiceClient .AddAsKnownClientApplicationAsync( _serviceApplication, _clientApplication, cancellationToken ); // Grant admin consent for service application "user_impersonation" API permissions of client application // Grant admin consent for Microsoft Graph "User.Read" API permissions of client application await _msGraphServiceClient .GrantAdminConsentToClientApplicationAsync( _serviceApplicationSP, _clientApplicationSP, cancellationToken ); // App Registration for AKS //////////////////////////////////////// // Register aks application var registrationResult = await RegisterAKSApplicationAsync( aksApplicationName, tags, cancellationToken ); _aksApplication = registrationResult.Item1; _aksApplicationPasswordCredentialRbacSecret = registrationResult.Item2; // Find service principal for aks application _aksApplicationSP = await _msGraphServiceClient .GetApplicationServicePrincipalAsync(_aksApplication, cancellationToken); // Add current user or service principal as app owner for aks // application, if it is not owner already. await _msGraphServiceClient .AddAsApplicationOwnerAsync( _aksApplication, owner, cancellationToken ); }
public async Task AssignContributorRole(ClaimsPrincipal principal, DomainObjects.Subscription subscription, ServicePrincipal servicePrincipal) { // Contributor role: https://docs.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor var contributorRoleId = "b24988ac-6180-42a0-ab88-20f7382dd24c"; var assignmentId = Guid.NewGuid(); var url = $"https://management.azure.com/subscriptions/{subscription.SubscriptionId}/providers/Microsoft.Authorization/roleAssignments/{assignmentId}?api-version=2015-07-01"; var body = new { properties = new { roleDefinitionId = $"/subscriptions/{subscription.SubscriptionId}/providers/Microsoft.Authorization/roleDefinitions/{contributorRoleId}", principalId = servicePrincipal.Id } }; var content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"); var token = await _tokenService.GetAccessTokenAsync(principal, _adOptions.ManagementAzureScope); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var response = await _httpClient.PutAsync(url, content); response.EnsureSuccessStatusCode(); await _repository.Add(subscription); }
public void CreateLogConsumerResources() { //LambdaRole var firehoseLambdaRole = new Role(this, "FirehoseLambdaRole", new RoleProps { AssumedBy = new ServicePrincipal("lambda.amazonaws.com"), Path = "/", }); firehoseLambdaRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { "arn:aws:logs:*:*:*" }, Actions = new string[] { "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" }, })); //FirehoseDataProcessingFunction var handler = new Function(this, "FirehoseDataProcessorFunction", new FunctionProps { FunctionName = "data-processor-function", Runtime = Runtime.NODEJS_12_X, Code = Code.FromAsset("resources"), Handler = "index.handler", Role = firehoseLambdaRole, Timeout = Duration.Minutes(2) }); //FirehoseDeliveryRole & Policies var firehoseDeliveryRole = new Role(this, "FirehoseDeliveryRole", new RoleProps { AssumedBy = new ServicePrincipal("firehose.amazonaws.com"), Path = "/" }); //S3 permissions firehoseDeliveryRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { _logsBucket.BucketArn, _logsBucket.BucketArn + "/*" }, Actions = new string[] { "s3:AbortMultipartUpload", "s3:GetBucketLocation", "s3:GetObject" , "s3:ListBucket", "s3:ListBucketMultipartUploads", "s3:PutObject" }, })); //Lambda permissions firehoseDeliveryRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { handler.FunctionArn }, Actions = new string[] { "lambda:GetFunctionConfiguration", "lambda:InvokeFunction" }, })); //Log group for Firehose logs. var firehoseloggroup = new LogGroup(this, "firehoseloggroup", new LogGroupProps { LogGroupName = "central-logs-delivery-group" }); var logstream = new LogStream(this, "logstream", new LogStreamProps { LogStreamName = "central-logs-delivery-stream", LogGroup = firehoseloggroup }); firehoseDeliveryRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { firehoseloggroup.LogGroupArn }, Actions = new string[] { "logs:PutLogEvents" }, })); //FirehoseLoggingDeliveryStream - Start CfnDeliveryStream.ExtendedS3DestinationConfigurationProperty s3config = new CfnDeliveryStream.ExtendedS3DestinationConfigurationProperty(); s3config.BucketArn = _logsBucket.BucketArn; s3config.BufferingHints = new CfnDeliveryStream.BufferingHintsProperty { SizeInMBs = 50, IntervalInSeconds = 300 }; s3config.CompressionFormat = "UNCOMPRESSED"; s3config.RoleArn = firehoseDeliveryRole.RoleArn; s3config.Prefix = "CentralLogs/AWSLogs/"; s3config.ErrorOutputPrefix = "CentralLogs/AWSLogs/Error/"; var parameters = new CfnDeliveryStream.ProcessorParameterProperty(); parameters.ParameterName = "LambdaArn"; parameters.ParameterValue = handler.FunctionArn; var paramsArray1 = new CfnDeliveryStream.ProcessorParameterProperty[] { parameters }; var processorProperty = new CfnDeliveryStream.ProcessorProperty(); processorProperty.Parameters = paramsArray1; processorProperty.Type = "Lambda"; var paramsArray = new CfnDeliveryStream.ProcessorProperty[] { processorProperty }; s3config.ProcessingConfiguration = new CfnDeliveryStream.ProcessingConfigurationProperty { Enabled = true, Processors = paramsArray }; s3config.CloudWatchLoggingOptions = new CfnDeliveryStream.CloudWatchLoggingOptionsProperty { Enabled = true, LogGroupName = firehoseloggroup.LogGroupName, LogStreamName = logstream.LogStreamName }; CfnDeliveryStream firehoseDeliveryStream = new CfnDeliveryStream(this, "FirehoseLoggingDeliveryStream", new CfnDeliveryStreamProps { DeliveryStreamType = "DirectPut", ExtendedS3DestinationConfiguration = s3config }); //FirehoseLoggingDeliveryStream - End //Policy Statements for LogDestination- start var policyStmt = new PolicyStatement(new PolicyStatementProps() { Actions = new string[] { "firehose:PutRecord" }, Resources = new string[] { "*" }, Effect = Effect.ALLOW }); var policyDoc = new PolicyDocument(); policyDoc.AddStatements(new PolicyStatement[] { policyStmt }); var policyProp = new CfnRole.PolicyProperty(); policyProp.PolicyName = "logDestinationPolicy"; policyProp.PolicyDocument = policyDoc; //Policy Statements - end //AssumeRolePolicyDocument for LogDestination - start var principal = new ServicePrincipal("logs.amazonaws.com"); var assumePolicyStatement = new PolicyStatement(new PolicyStatementProps { Actions = new string[] { "sts:AssumeRole" }, Effect = Effect.ALLOW, Principals = new IPrincipal[] { principal } }); var assumePolicyDoc = new PolicyDocument(); assumePolicyDoc.AddStatements(new PolicyStatement[] { assumePolicyStatement }); //AssumeRolePolicyDocument - end var roleProps = new CfnRoleProps { Path = "/", AssumeRolePolicyDocument = assumePolicyDoc, Policies = new CfnRole.PolicyProperty[] { policyProp } }; CfnRole cfnRole = new CfnRole(this, "CfnRole", roleProps); CfnDestination logDestination = new CfnDestination(this, "LogDestination", new CfnDestinationProps { DestinationName = "Central-Log-Destination", RoleArn = cfnRole.AttrArn, TargetArn = firehoseDeliveryStream.AttrArn, DestinationPolicy = "{\"Version\" : \"2012-10-17\",\"Statement\" : [{\"Effect\" : \"Allow\", \"Principal\" : {\"AWS\" : [\"" + SourceLogAccountId + "\"]},\"Action\" : \"logs:PutSubscriptionFilter\", \"Resource\" : \"arn:aws:logs:" + this.Region + ":" + DestinationAccountId + ":destination:Central-Log-Destination\"}]}" }); logDestination.AddDependsOn(firehoseDeliveryStream); logDestination.AddDependsOn(cfnRole); Console.WriteLine(logDestination.DestinationPolicy); LogDestinationArn = logDestination.AttrArn; CfnOutput output = new CfnOutput(this, "LogDestinationARN", new CfnOutputProps { Description = "LogDestination ARN", Value = logDestination.AttrArn }); }
internal ManagedInstanceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary <string, string> tags, AzureLocation location, ManagedServiceIdentity identity, SqlSku sku, ManagedInstancePropertiesProvisioningState?provisioningState, ManagedServerCreateMode?managedInstanceCreateMode, string fullyQualifiedDomainName, string administratorLogin, string administratorLoginPassword, string subnetId, string state, ManagedInstanceLicenseType?licenseType, int?vCores, int?storageSizeInGB, string collation, string dnsZone, string dnsZonePartner, bool?publicDataEndpointEnabled, string sourceManagedInstanceId, DateTimeOffset?restorePointInOn, ManagedInstanceProxyOverride?proxyOverride, string timezoneId, string instancePoolId, string maintenanceConfigurationId, IReadOnlyList <ManagedInstancePecProperty> privateEndpointConnections, string minimalTlsVersion, BackupStorageRedundancy?currentBackupStorageRedundancy, BackupStorageRedundancy?requestedBackupStorageRedundancy, bool?zoneRedundant, string primaryUserAssignedIdentityId, string keyId, ManagedInstanceExternalAdministrator administrators, ServicePrincipal servicePrincipal) : base(id, name, resourceType, systemData, tags, location) { Identity = identity; Sku = sku; ProvisioningState = provisioningState; ManagedInstanceCreateMode = managedInstanceCreateMode; FullyQualifiedDomainName = fullyQualifiedDomainName; AdministratorLogin = administratorLogin; AdministratorLoginPassword = administratorLoginPassword; SubnetId = subnetId; State = state; LicenseType = licenseType; VCores = vCores; StorageSizeInGB = storageSizeInGB; Collation = collation; DnsZone = dnsZone; DnsZonePartner = dnsZonePartner; PublicDataEndpointEnabled = publicDataEndpointEnabled; SourceManagedInstanceId = sourceManagedInstanceId; RestorePointInOn = restorePointInOn; ProxyOverride = proxyOverride; TimezoneId = timezoneId; InstancePoolId = instancePoolId; MaintenanceConfigurationId = maintenanceConfigurationId; PrivateEndpointConnections = privateEndpointConnections; MinimalTlsVersion = minimalTlsVersion; CurrentBackupStorageRedundancy = currentBackupStorageRedundancy; RequestedBackupStorageRedundancy = requestedBackupStorageRedundancy; ZoneRedundant = zoneRedundant; PrimaryUserAssignedIdentityId = primaryUserAssignedIdentityId; KeyId = keyId; Administrators = administrators; ServicePrincipal = servicePrincipal; }
/// <summary> /// Retrieves the subscriptions /// </summary> /// <returns>Subscriptions list</returns> public async Task <List <Subscription> > GetSubscriptions() { var endpointUrl = string.Format(UriConstants.GetAllSubscriptionsUri); var client = new RestApiClient(); var result = await client.CallGetListAsync <Subscription>(endpointUrl, await ServicePrincipal.GetAccessToken()); if (result.Success) { return(result.Result.Where(s => s.State == SubscriptionState.Enabled).ToList()); } throw new ServiceCatalogException(result.Message); }
internal static ManagedInstanceData DeserializeManagedInstanceData(JsonElement element) { Optional <ManagedServiceIdentity> identity = default; Optional <SqlSku> sku = default; IDictionary <string, string> tags = default; AzureLocation location = default; ResourceIdentifier id = default; string name = default; ResourceType type = default; SystemData systemData = default; Optional <ManagedInstancePropertiesProvisioningState> provisioningState = default; Optional <ManagedServerCreateMode> managedInstanceCreateMode = default; Optional <string> fullyQualifiedDomainName = default; Optional <string> administratorLogin = default; Optional <string> administratorLoginPassword = default; Optional <string> subnetId = default; Optional <string> state = default; Optional <ManagedInstanceLicenseType> licenseType = default; Optional <int> vCores = default; Optional <int> storageSizeInGB = default; Optional <string> collation = default; Optional <string> dnsZone = default; Optional <string> dnsZonePartner = default; Optional <bool> publicDataEndpointEnabled = default; Optional <string> sourceManagedInstanceId = default; Optional <DateTimeOffset> restorePointInTime = default; Optional <ManagedInstanceProxyOverride> proxyOverride = default; Optional <string> timezoneId = default; Optional <string> instancePoolId = default; Optional <string> maintenanceConfigurationId = default; Optional <IReadOnlyList <ManagedInstancePecProperty> > privateEndpointConnections = default; Optional <string> minimalTlsVersion = default; Optional <BackupStorageRedundancy> currentBackupStorageRedundancy = default; Optional <BackupStorageRedundancy> requestedBackupStorageRedundancy = default; Optional <bool> zoneRedundant = default; Optional <string> primaryUserAssignedIdentityId = default; Optional <string> keyId = default; Optional <ManagedInstanceExternalAdministrator> administrators = default; Optional <ServicePrincipal> servicePrincipal = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("identity")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } var serializeOptions = new JsonSerializerOptions { Converters = { new ManagedServiceIdentityTypeV3Converter() } }; identity = JsonSerializer.Deserialize <ManagedServiceIdentity>(property.Value.ToString(), serializeOptions); continue; } if (property.NameEquals("sku")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } sku = SqlSku.DeserializeSqlSku(property.Value); continue; } if (property.NameEquals("tags")) { Dictionary <string, string> dictionary = new Dictionary <string, string>(); foreach (var property0 in property.Value.EnumerateObject()) { dictionary.Add(property0.Name, property0.Value.GetString()); } tags = dictionary; continue; } if (property.NameEquals("location")) { location = property.Value.GetString(); continue; } if (property.NameEquals("id")) { id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("systemData")) { systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString()); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("provisioningState")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } provisioningState = new ManagedInstancePropertiesProvisioningState(property0.Value.GetString()); continue; } if (property0.NameEquals("managedInstanceCreateMode")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } managedInstanceCreateMode = new ManagedServerCreateMode(property0.Value.GetString()); continue; } if (property0.NameEquals("fullyQualifiedDomainName")) { fullyQualifiedDomainName = property0.Value.GetString(); continue; } if (property0.NameEquals("administratorLogin")) { administratorLogin = property0.Value.GetString(); continue; } if (property0.NameEquals("administratorLoginPassword")) { administratorLoginPassword = property0.Value.GetString(); continue; } if (property0.NameEquals("subnetId")) { subnetId = property0.Value.GetString(); continue; } if (property0.NameEquals("state")) { state = property0.Value.GetString(); continue; } if (property0.NameEquals("licenseType")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } licenseType = new ManagedInstanceLicenseType(property0.Value.GetString()); continue; } if (property0.NameEquals("vCores")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } vCores = property0.Value.GetInt32(); continue; } if (property0.NameEquals("storageSizeInGB")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } storageSizeInGB = property0.Value.GetInt32(); continue; } if (property0.NameEquals("collation")) { collation = property0.Value.GetString(); continue; } if (property0.NameEquals("dnsZone")) { dnsZone = property0.Value.GetString(); continue; } if (property0.NameEquals("dnsZonePartner")) { dnsZonePartner = property0.Value.GetString(); continue; } if (property0.NameEquals("publicDataEndpointEnabled")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } publicDataEndpointEnabled = property0.Value.GetBoolean(); continue; } if (property0.NameEquals("sourceManagedInstanceId")) { sourceManagedInstanceId = property0.Value.GetString(); continue; } if (property0.NameEquals("restorePointInTime")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } restorePointInTime = property0.Value.GetDateTimeOffset("O"); continue; } if (property0.NameEquals("proxyOverride")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } proxyOverride = new ManagedInstanceProxyOverride(property0.Value.GetString()); continue; } if (property0.NameEquals("timezoneId")) { timezoneId = property0.Value.GetString(); continue; } if (property0.NameEquals("instancePoolId")) { instancePoolId = property0.Value.GetString(); continue; } if (property0.NameEquals("maintenanceConfigurationId")) { maintenanceConfigurationId = property0.Value.GetString(); continue; } if (property0.NameEquals("privateEndpointConnections")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List <ManagedInstancePecProperty> array = new List <ManagedInstancePecProperty>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(ManagedInstancePecProperty.DeserializeManagedInstancePecProperty(item)); } privateEndpointConnections = array; continue; } if (property0.NameEquals("minimalTlsVersion")) { minimalTlsVersion = property0.Value.GetString(); continue; } if (property0.NameEquals("currentBackupStorageRedundancy")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } currentBackupStorageRedundancy = new BackupStorageRedundancy(property0.Value.GetString()); continue; } if (property0.NameEquals("requestedBackupStorageRedundancy")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } requestedBackupStorageRedundancy = new BackupStorageRedundancy(property0.Value.GetString()); continue; } if (property0.NameEquals("zoneRedundant")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } zoneRedundant = property0.Value.GetBoolean(); continue; } if (property0.NameEquals("primaryUserAssignedIdentityId")) { primaryUserAssignedIdentityId = property0.Value.GetString(); continue; } if (property0.NameEquals("keyId")) { keyId = property0.Value.GetString(); continue; } if (property0.NameEquals("administrators")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } administrators = ManagedInstanceExternalAdministrator.DeserializeManagedInstanceExternalAdministrator(property0.Value); continue; } if (property0.NameEquals("servicePrincipal")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } servicePrincipal = ServicePrincipal.DeserializeServicePrincipal(property0.Value); continue; } } continue; } } return(new ManagedInstanceData(id, name, type, systemData, tags, location, identity, sku.Value, Optional.ToNullable(provisioningState), Optional.ToNullable(managedInstanceCreateMode), fullyQualifiedDomainName.Value, administratorLogin.Value, administratorLoginPassword.Value, subnetId.Value, state.Value, Optional.ToNullable(licenseType), Optional.ToNullable(vCores), Optional.ToNullable(storageSizeInGB), collation.Value, dnsZone.Value, dnsZonePartner.Value, Optional.ToNullable(publicDataEndpointEnabled), sourceManagedInstanceId.Value, Optional.ToNullable(restorePointInTime), Optional.ToNullable(proxyOverride), timezoneId.Value, instancePoolId.Value, maintenanceConfigurationId.Value, Optional.ToList(privateEndpointConnections), minimalTlsVersion.Value, Optional.ToNullable(currentBackupStorageRedundancy), Optional.ToNullable(requestedBackupStorageRedundancy), Optional.ToNullable(zoneRedundant), primaryUserAssignedIdentityId.Value, keyId.Value, administrators.Value, servicePrincipal.Value)); }
// GET: Deployments public async Task <ActionResult> DeploymentsView() { try { // Get all subscriptions for this tenant var subscriptions = await new SubscriptionController().GetSubscriptions(); var subscriptionId = subscriptions.FirstOrDefault()?.SubscriptionId; var token = await ServicePrincipal.GetAccessToken(); var client = new RestApiClient(); // Get all resource groups var resourceGroupUri = string.Format(UriConstants.GetAllResourceGroupsUri, Url.Encode(subscriptionId), ""); var resourceGroups = await client.CallGetListAsync <ResourceGroup>(resourceGroupUri, token); // Get all deployments var deployments = new List <DeploymentExtended>(); foreach (var resourceGroup in resourceGroups.Result) { var deploymentsUri = string.Format(UriConstants.GetDeploymentsByResourceGroup, subscriptionId, resourceGroup.Name); client = new RestApiClient(); var result = await client.CallGetListAsync <DeploymentExtended>(deploymentsUri, token); var deployment = result.Result; deployments.AddRange(deployment); } var email = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value; var resultDeployments = new List <DeploymentViewModel>(); using (WebAppContext context = new WebAppContext()) { var localDeployments = await context.Deployments.ToListAsync(); foreach (var localDeployment in localDeployments) { foreach (var deployment in deployments) { if (localDeployment.DeploymentName != deployment?.Name) { continue; } if (UserRoleHelper.IsAdmin(email) || email == localDeployment.Owner) { var newDeployment = new DeploymentViewModel() { TemplateName = localDeployment.TemplateName, DeploymentId = localDeployment.DeploymentId, DeploymentName = localDeployment.DeploymentName, SubscriptionId = localDeployment.SubscriptionId, SubscriptionName = localDeployment.SubscriptionName, Owner = localDeployment.Owner, TemplateVersion = localDeployment.TemplateVersion, Timestamp = localDeployment.Timestamp, ProvisioningState = deployment?.Properties?.ProvisioningState, Outputs = deployment?.Properties?.Outputs?.ToString() }; resultDeployments.Add(newDeployment); } } } } var deploymentsList = resultDeployments.OrderByDescending(d => d.Timestamp).ToList(); ViewBag.FileLogName = $"{DateTime.Today:yyyy-MM-dd}.log"; return(View(deploymentsList)); } catch (Exception ex) { ViewBag.ErrorMessage = "Error"; ViewBag.ErrorDetails = ex.Message; return(View("Error")); } }
public static UpdateAppSettingsCommand CreateAppSettingsCommand(Webapp target, ServicePrincipal servicePrincipal, IDictionary <string, string> requestedSettings, bool includeDeletion) { var webapp = new AzureWebapp(target, servicePrincipal); var settingsInTarget = webapp.GetAppSettings(); var operations = GetOperations(requestedSettings, settingsInTarget, includeDeletion); return(new UpdateAppSettingsCommand { Webapp = target, ServicePrincipal = servicePrincipal, Operations = operations }); }
public static ServicePrincipal CreateServicePrincipal(string objectId, global::System.Collections.ObjectModel.Collection<KeyCredential> keyCredentials, global::System.Collections.ObjectModel.Collection<PasswordCredential> passwordCredentials, global::System.Collections.ObjectModel.Collection<string> replyUrls, global::System.Collections.ObjectModel.Collection<string> servicePrincipalNames, global::System.Collections.ObjectModel.Collection<string> tags) { ServicePrincipal servicePrincipal = new ServicePrincipal(); servicePrincipal.objectId = objectId; if ((keyCredentials == null)) { throw new global::System.ArgumentNullException("keyCredentials"); } servicePrincipal.keyCredentials = keyCredentials; if ((passwordCredentials == null)) { throw new global::System.ArgumentNullException("passwordCredentials"); } servicePrincipal.passwordCredentials = passwordCredentials; if ((replyUrls == null)) { throw new global::System.ArgumentNullException("replyUrls"); } servicePrincipal.replyUrls = replyUrls; if ((servicePrincipalNames == null)) { throw new global::System.ArgumentNullException("servicePrincipalNames"); } servicePrincipal.servicePrincipalNames = servicePrincipalNames; if ((tags == null)) { throw new global::System.ArgumentNullException("tags"); } servicePrincipal.tags = tags; return servicePrincipal; }
public AksStack() { var config = new Pulumi.Config(); var kubernetesVersion = config.Get("kubernetesVersion") ?? "1.19.3"; var resourceGroup = new ResourceGroup("aks-rg"); var password = new RandomPassword("password", new RandomPasswordArgs { Length = 20, Special = true, }).Result; var sshPublicKey = new PrivateKey("ssh-key", new PrivateKeyArgs { Algorithm = "RSA", RsaBits = 4096, }).PublicKeyOpenssh; // Create the AD service principal for the K8s cluster. var adApp = new Application("aks"); var adSp = new ServicePrincipal("aksSp", new ServicePrincipalArgs { ApplicationId = adApp.ApplicationId }); var adSpPassword = new ServicePrincipalPassword("aksSpPassword", new ServicePrincipalPasswordArgs { ServicePrincipalId = adSp.Id, Value = password, EndDate = "2099-01-01T00:00:00Z", }); // Grant networking permissions to the SP (needed e.g. to provision Load Balancers) var assignment = new Assignment("role-assignment", new AssignmentArgs { PrincipalId = adSp.Id, Scope = resourceGroup.Id, RoleDefinitionName = "Network Contributor" }); // Create a Virtual Network for the cluster var vnet = new VirtualNetwork("vnet", new VirtualNetworkArgs { ResourceGroupName = resourceGroup.Name, AddressSpaces = { "10.2.0.0/16" }, }); // Create a Subnet for the cluster var subnet = new Subnet("subnet", new SubnetArgs { ResourceGroupName = resourceGroup.Name, VirtualNetworkName = vnet.Name, AddressPrefixes = { "10.2.1.0/24" }, }); // Now allocate an AKS cluster. var cluster = new KubernetesCluster("aksCluster", new KubernetesClusterArgs { ResourceGroupName = resourceGroup.Name, DefaultNodePool = new KubernetesClusterDefaultNodePoolArgs { Name = "aksagentpool", NodeCount = 3, VmSize = "Standard_B2s", OsDiskSizeGb = 30, VnetSubnetId = subnet.Id, }, DnsPrefix = "aksdemo", LinuxProfile = new KubernetesClusterLinuxProfileArgs { AdminUsername = "******", SshKey = new KubernetesClusterLinuxProfileSshKeyArgs { KeyData = sshPublicKey, }, }, ServicePrincipal = new KubernetesClusterServicePrincipalArgs { ClientId = adApp.ApplicationId, ClientSecret = adSpPassword.Value, }, KubernetesVersion = kubernetesVersion, RoleBasedAccessControl = new KubernetesClusterRoleBasedAccessControlArgs { Enabled = true }, NetworkProfile = new KubernetesClusterNetworkProfileArgs { NetworkPlugin = "azure", DnsServiceIp = "10.2.2.254", ServiceCidr = "10.2.2.0/24", DockerBridgeCidr = "172.17.0.1/16", }, }); this.KubeConfig = cluster.KubeConfigRaw; }
static Task <int> Main() { return(Deployment.RunAsync(() => { var resourceGroup = new ResourceGroup("aks-rg"); var password = new RandomPassword("password", new RandomPasswordArgs { Length = 20, Special = true, }).Result; var sshPublicKey = new PrivateKey("ssh-key", new PrivateKeyArgs { Algorithm = "RSA", RsaBits = 4096, }).PublicKeyOpenssh; // Create the AD service principal for the K8s cluster. var adApp = new Application("aks"); var adSp = new ServicePrincipal("aksSp", new ServicePrincipalArgs { ApplicationId = adApp.ApplicationId }); var adSpPassword = new ServicePrincipalPassword("aksSpPassword", new ServicePrincipalPasswordArgs { ServicePrincipalId = adSp.Id, Value = password, EndDate = "2099-01-01T00:00:00Z", }); // Create a Virtual Network for the cluster var vnet = new VirtualNetwork("vnet", new VirtualNetworkArgs { ResourceGroupName = resourceGroup.Name, AddressSpaces = { "10.2.0.0/16" }, }); // Create a Subnet for the cluster var subnet = new Subnet("subnet", new SubnetArgs { ResourceGroupName = resourceGroup.Name, VirtualNetworkName = vnet.Name, AddressPrefix = "10.2.1.0/24", }); // Now allocate an AKS cluster. var cluster = new KubernetesCluster("aksCluster", new KubernetesClusterArgs { ResourceGroupName = resourceGroup.Name, DefaultNodePool = new KubernetesClusterDefaultNodePoolArgs { Name = "aksagentpool", NodeCount = 3, VmSize = "Standard_B2s", OsDiskSizeGb = 30, VnetSubnetId = subnet.Id, }, DnsPrefix = "sampleaks", LinuxProfile = new KubernetesClusterLinuxProfileArgs { AdminUsername = "******", SshKey = new KubernetesClusterLinuxProfileSshKeyArgs { KeyData = sshPublicKey, }, }, ServicePrincipal = new KubernetesClusterServicePrincipalArgs { ClientId = adApp.ApplicationId, ClientSecret = adSpPassword.Value, }, KubernetesVersion = "1.15.4", RoleBasedAccessControl = new KubernetesClusterRoleBasedAccessControlArgs { Enabled = true }, NetworkProfile = new KubernetesClusterNetworkProfileArgs { NetworkPlugin = "azure", DnsServiceIp = "10.2.2.254", ServiceCidr = "10.2.2.0/24", DockerBridgeCidr = "172.17.0.1/16", }, }); return new Dictionary <string, object?> { { "kubeconfig", cluster.KubeConfigRaw }, }; })); }
public MyStack() { var env = Deployment.Instance.StackName; // Create an Azure Resource Group var resourceGroup = new ResourceGroup($"{env}-skywalker-website"); // Create an Azure Storage Account var storageAccount = new Account("storage", new AccountArgs { ResourceGroupName = resourceGroup.Name, AccountReplicationType = "LRS", AccountTier = "Standard", }); // Create a container registry. var registry = new Registry("registry", new RegistryArgs { ResourceGroupName = resourceGroup.Name, Sku = "Basic", AdminEnabled = true }); // Create a username for SQL Server. var sqlUserName = "******"; // Create a random password for SQL Server. var sqlPassword = new RandomPassword("password", new RandomPasswordArgs { Length = 20, Special = true, }).Result; // Create a Sql Server. var sqlServer = new SqlServer("sql", new SqlServerArgs { ResourceGroupName = resourceGroup.Name, AdministratorLogin = sqlUserName, AdministratorLoginPassword = sqlPassword, Version = "12.0", }); // Create a database. var database = new Database("skywalker", new DatabaseArgs { ResourceGroupName = resourceGroup.Name, ServerName = sqlServer.Name, RequestedServiceObjectiveName = "S0", }); var dbConnectionString = Output.Tuple(sqlServer.Name, database.Name, sqlPassword).Apply(x => { (var server, var dbName, string pwd) = x; return ($"Server= tcp:{server}.database.windows.net;initial catalog={dbName};user ID={sqlUserName};password={pwd};Min Pool Size=0;Max Pool Size=30;Persist Security Info=true;"); }); // Create an app service plan. var plan = new Plan($"skywalker-apps", new PlanArgs { ResourceGroupName = resourceGroup.Name, Kind = "Linux", Reserved = true, Sku = new PlanSkuArgs { Tier = "Basic", Size = "B1" } }); // Create an app service. var appService = new AppService($"skywalker-website", new AppServiceArgs { ResourceGroupName = resourceGroup.Name, AppServicePlanId = plan.Id, AppSettings = new InputMap <string> { ["WEBSITES_ENABLE_APP_SERVICE_STORAGE"] = "false", ["WEBSITE_HTTPLOGGING_RETENTION_DAYS"] = "1", ["DOCKER_REGISTRY_SERVER_URL"] = registry.LoginServer.Apply(x => $"https://{x}"), ["DOCKER_REGISTRY_SERVER_USERNAME"] = registry.AdminUsername, ["DOCKER_REGISTRY_SERVER_PASSWORD"] = registry.AdminPassword, ["DOCKER_ENABLE_CI"] = "false", ["WEBSITES_PORT"] = "80", ["ORCHARDCORE__ORCHARDCORE_DATAPROTECTION_AZURE__CONNECTIONSTRING"] = storageAccount.PrimaryConnectionString, ["ORCHARDCORE__ORCHARDCORE_MEDIA_AZURE__CONNECTIONSTRING"] = storageAccount.PrimaryConnectionString, ["ORCHARDCORE__ORCHARDCORE_MEDIA_SHELLS__CONNECTIONSTRING"] = storageAccount.PrimaryConnectionString, }, ConnectionStrings = new AppServiceConnectionStringArgs { Name = "db", Type = "SQLAzure", Value = dbConnectionString, }, Logs = new AppServiceLogsArgs { HttpLogs = new AppServiceLogsHttpLogsArgs { FileSystem = new AppServiceLogsHttpLogsFileSystemArgs { RetentionInDays = 1, RetentionInMb = 35 } } }, SiteConfig = new AppServiceSiteConfigArgs { AlwaysOn = true, LinuxFxVersion = registry.LoginServer.Apply(x => $"DOCKER|{x}/skywalker-website:latest"), }, HttpsOnly = true }); var appName = appService.Name; // Create a service principal for GitHub Actions to interact with the App Service. var adApp = new Application("skywalker-website"); var adSp = new ServicePrincipal( "skywalker-sp", new ServicePrincipalArgs { ApplicationId = adApp.ApplicationId, }); var adSpPassword = new ServicePrincipalPassword("skywalker-sp-pwd", new ServicePrincipalPasswordArgs { ServicePrincipalId = adSp.Id, Value = "!Test1234", EndDate = "2099-01-01T00:00:00Z", }); // Grant networking permissions to the SP (needed e.g. to provision Load Balancers). var assignment = new Assignment("skywalker-sp-role-assignment", new AssignmentArgs { PrincipalId = adSp.Id, Scope = resourceGroup.Id, RoleDefinitionName = "Owner" }); var azureCredentials = Output.Tuple( adApp.ApplicationId, Output.Create("!Test1234")) .Apply(x => { var currentSubscription = GetSubscription.InvokeAsync().Result; var model = new { clientId = x.Item1, clientSecret = x.Item2, subscriptionId = currentSubscription.SubscriptionId, tenantId = currentSubscription.TenantId, }; return(JsonConvert.SerializeObject(model)); }); StorageConnectionString = storageAccount.PrimaryConnectionString; DatabaseConnectionString = dbConnectionString; RegistryServer = registry.LoginServer; RegistryRepo = registry.LoginServer; RegistryUser = registry.AdminUsername; RegistryPassword = registry.AdminPassword; AzureCredentials = azureCredentials; AppName = appName; WebsiteUrl = appService.DefaultSiteHostname.Apply(x => $"https://{x}"); // Push secrets to GitHub. var variablePrefix = env.ToUpperInvariant(); var gitHubVariables = new GitHubVariables("github-variables", new GitHubVariablesArgs { Variables = new Dictionary <string, Input <string> > { [$"{variablePrefix}_DOCKER_REGISTRY"] = RegistryServer, [$"{variablePrefix}_DOCKER_REPO"] = RegistryRepo, [$"{variablePrefix}_DOCKER_USER"] = RegistryUser, [$"{variablePrefix}_DOCKER_PASSWORD"] = RegistryPassword, [$"{variablePrefix}_APP_NAME"] = AppName, [$"{variablePrefix}_AZURE_CREDENTIALS"] = azureCredentials } }); }
public AksCluster(string name, AksClusterArgs args) : base("example:component:AksCluster", name) { var adApp = new Application("app", new ApplicationArgs { DisplayName = "aks-cosmos" }, new CustomResourceOptions { Parent = this }); var adSp = new ServicePrincipal("service-principal", new ServicePrincipalArgs { ApplicationId = adApp.ApplicationId }, new CustomResourceOptions { Parent = this }); var pw = new RandomPassword("pw", new RandomPasswordArgs { Length = 20, Special = true }, new CustomResourceOptions { Parent = this }); var adSpPassword = new ServicePrincipalPassword("sp-password", new ServicePrincipalPasswordArgs { ServicePrincipalId = adSp.Id, Value = pw.Result, EndDate = "2099-01-01T00:00:00Z" }, new CustomResourceOptions { Parent = this }); var keyPair = new PrivateKey("ssh-key", new PrivateKeyArgs { Algorithm = "RSA", RsaBits = 4096 }, new CustomResourceOptions { Parent = this }); var k8sCluster = new ManagedCluster(name, new ManagedClusterArgs { ResourceGroupName = args.ResourceGroupName, AddonProfiles = { ["KubeDashboard"] = new ManagedClusterAddonProfileArgs { Enabled = true } }, AgentPoolProfiles = { new ManagedClusterAgentPoolProfileArgs { Count = args.NodeCount, VmSize = args.NodeSize, MaxPods = 110, Mode = "System", Name = "agentpool", OsDiskSizeGB = 30, OsType = "Linux", Type = "VirtualMachineScaleSets" } }, DnsPrefix = args.ResourceGroupName, EnableRBAC = true, KubernetesVersion = args.KubernetesVersion, LinuxProfile = new ContainerServiceLinuxProfileArgs { AdminUsername = "******", Ssh = new ContainerServiceSshConfigurationArgs { PublicKeys = new ContainerServiceSshPublicKeyArgs { KeyData = keyPair.PublicKeyOpenssh } } }, NodeResourceGroup = $"{name}-node-rg", ServicePrincipalProfile = new ManagedClusterServicePrincipalProfileArgs { ClientId = adApp.ApplicationId, Secret = adSpPassword.Value } }, new CustomResourceOptions { Parent = this }); this.ClusterName = k8sCluster.Name; this.KubeConfig = Output.Tuple(k8sCluster.Name, args.ResourceGroupName.ToOutput()) .Apply(pair => { var k8sClusterName = pair.Item1; var resourceGroupName = pair.Item2; return(ListManagedClusterUserCredentials.InvokeAsync(new ListManagedClusterUserCredentialsArgs { ResourceGroupName = resourceGroupName, ResourceName = k8sClusterName })); }) .Apply(x => x.Kubeconfigs[0].Value) .Apply(Convert.FromBase64String) .Apply(Encoding.UTF8.GetString); this.Provider = new K8s.Provider("k8s-provider", new K8s.ProviderArgs { KubeConfig = this.KubeConfig }, new CustomResourceOptions { Parent = this }); }
public static SitePublishProfile GetPublishProperties(AzureServicePrincipalAccount account, string resourceGroupName, AzureTargetSite azureTargetSite) { if (account.ResourceManagementEndpointBaseUri != DefaultVariables.ResourceManagementEndpoint) { Log.Info("Using override for resource management endpoint - {0}", account.ResourceManagementEndpointBaseUri); } if (account.ActiveDirectoryEndpointBaseUri != DefaultVariables.ActiveDirectoryEndpoint) { Log.Info("Using override for Azure Active Directory endpoint - {0}", account.ActiveDirectoryEndpointBaseUri); } var token = ServicePrincipal.GetAuthorizationToken(account.TenantId, account.ClientId, account.Password, account.ResourceManagementEndpointBaseUri, account.ActiveDirectoryEndpointBaseUri); var baseUri = new Uri(account.ResourceManagementEndpointBaseUri); using (var resourcesClient = new ResourceManagementClient(new TokenCredentials(token)) { SubscriptionId = account.SubscriptionNumber, BaseUri = baseUri, }) using (var webSiteClient = new WebSiteManagementClient(new Uri(account.ResourceManagementEndpointBaseUri), new TokenCredentials(token)) { SubscriptionId = account.SubscriptionNumber }) { webSiteClient.SetRetryPolicy(new Microsoft.Rest.TransientFaultHandling.RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), 3)); resourcesClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); resourcesClient.HttpClient.BaseAddress = baseUri; Log.Verbose($"Looking up site {azureTargetSite.Site} {(string.IsNullOrWhiteSpace(resourceGroupName) ? string.Empty : $"in resourceGroup {resourceGroupName}")}"); Site matchingSite; if (string.IsNullOrWhiteSpace(resourceGroupName)) { matchingSite = FindSiteByNameWithRetry(account, azureTargetSite, webSiteClient) ?? throw new CommandException(GetSiteNotFoundExceptionMessage(account, azureTargetSite)); resourceGroupName = matchingSite.ResourceGroup; } else { var site = webSiteClient.WebApps.Get(resourceGroupName, azureTargetSite.Site); Log.Verbose("Found site:"); LogSite(site); matchingSite = site ?? throw new CommandException(GetSiteNotFoundExceptionMessage(account, azureTargetSite, resourceGroupName)); } // ARM resource ID of the source app. App resource ID is of the form: // - /subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName} for production slots and // - /subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/slots/{slotName} for other slots. // We allow the slot to be defined on both the target directly (which will come through on the matchingSite.Name) or on the // step for backwards compatibility with older Azure steps. var siteAndSlotPath = matchingSite.Name; if (azureTargetSite.HasSlot) { Log.Verbose($"Using the deployment slot {azureTargetSite.Slot}"); siteAndSlotPath = $"{matchingSite.Name}/slots/{azureTargetSite.Slot}"; } // Once we know the Resource Group, we have to POST a request to the URI below to retrieve the publishing credentials var publishSettingsUri = new Uri(resourcesClient.BaseUri, $"/subscriptions/{account.SubscriptionNumber}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteAndSlotPath}/config/publishingCredentials/list?api-version=2016-08-01"); Log.Verbose($"Retrieving publishing profile from {publishSettingsUri}"); SitePublishProfile publishProperties = null; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = publishSettingsUri }; // Add the authentication headers var requestTask = resourcesClient.Credentials.ProcessHttpRequestAsync(request, new CancellationToken()) .ContinueWith(authResult => resourcesClient.HttpClient.SendAsync(request), TaskContinuationOptions.NotOnFaulted) .ContinueWith(publishSettingsResponse => { var result = publishSettingsResponse.Result.Result; if (!result.IsSuccessStatusCode) { Log.Error($"Retrieving publishing credentials failed. Publish-settings URI: {publishSettingsUri}"); throw new Exception($"Retrieving publishing credentials failed with HTTP status {(int)result.StatusCode} - {result.ReasonPhrase}"); } dynamic response = JObject.Parse(result.Content.AsString()); string publishUserName = response.properties.publishingUserName; string publishPassword = response.properties.publishingPassword; string scmUri = response.properties.scmUri; Log.Verbose($"Retrieved publishing profile. URI: {scmUri} UserName: {publishUserName}"); publishProperties = new SitePublishProfile(publishUserName, publishPassword, new Uri(scmUri)); }, TaskContinuationOptions.NotOnFaulted); requestTask.Wait(); return(publishProperties); }
/// <summary> /// This method gets the Type, DisplayName, and Alias of the security principal using the GraphServiceClient. /// </summary> /// <param name="accessPol">The current AccessPolicyEntry</param> /// <param name="graphClient">The Microsoft GraphServiceClient with permissions to obtain the DisplayName</param> /// <returns>A string array holding the Type, DisplayName, and Alias if applicable</returns> private Dictionary <string, string> getTypeAndName(AccessPolicyEntry accessPol, GraphServiceClient graphClient) { Dictionary <string, string> data = new Dictionary <string, string>(); // User try { User user = null; if (graphClient.GetType() == typeof(TestGraphClient)) { var client = (TestGraphClient)graphClient; user = (client.Users.Request().Filter($"Id eq '{accessPol.ObjectId}'").GetAsync().Result)[0]; } else { user = (graphClient.Users.Request().Filter($"Id eq '{accessPol.ObjectId}'").GetAsync().Result)[0]; } data["Type"] = "User"; data["DisplayName"] = user.DisplayName; data["Alias"] = user.UserPrincipalName; return(data); } catch { } // Group try { Group group = null; if (graphClient.GetType() == typeof(TestGraphClient)) { var client = (TestGraphClient)graphClient; group = (client.Groups.Request().Filter($"Id eq '{accessPol.ObjectId}'").GetAsync().Result)[0]; } else { group = (graphClient.Groups.Request().Filter($"Id eq '{accessPol.ObjectId}'").GetAsync().Result)[0]; } data["Type"] = "Group"; data["DisplayName"] = group.DisplayName; data["Alias"] = group.Mail; return(data); } catch { } // Application try { Application app = null; if (graphClient.GetType() == typeof(TestGraphClient)) { var client = (TestGraphClient)graphClient; app = (client.Applications.Request().Filter($"Id eq '{accessPol.ObjectId}'").GetAsync().Result)[0]; } else { app = (graphClient.Applications.Request().Filter($"Id eq '{accessPol.ObjectId}'").GetAsync().Result)[0]; } data["Type"] = "App"; data["DisplayName"] = app.DisplayName; return(data); } catch { } // Service Principal try { ServicePrincipal sp = null; if (graphClient.GetType() == typeof(TestGraphClient)) { var client = (TestGraphClient)graphClient; sp = (client.ServicePrincipals.Request().Filter($"Id eq '{accessPol.ObjectId}'").GetAsync().Result)[0]; } else { sp = (graphClient.ServicePrincipals.Request().Filter($"Id eq '{accessPol.ObjectId}'").GetAsync().Result)[0]; } data["Type"] = "Service Principal"; data["DisplayName"] = sp.DisplayName; return(data); } // "Unknown Application catch { data["Type"] = "Unknown"; return(data); } }
public async Task<List<Models.User>> GetAssignedUsers() { try { // Create the Graph Client string tenantId = ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value; ActiveDirectoryClient graphClient = new ActiveDirectoryClient(new Uri(Globals.GraphApiUrl, tenantId), async () => await GraphHelper.AcquireTokenAsApp()); // Read users from db for evaluating in memory List<Models.User> userHistory = UsersDbHelper.GetUsersForTenant(tenantId); List<Models.User> usersWithStatus = new List<Models.User>(userHistory); List<Models.User> updatedUserHistory = new List<Models.User>(userHistory); // Get the assignments for the application ServicePrincipal sp = (ServicePrincipal)graphClient.ServicePrincipals.Where(servicePrincpial => servicePrincpial.AppId.Equals(ConfigHelper.ClientId)).ExecuteAsync().Result.CurrentPage.FirstOrDefault(); IServicePrincipalFetcher spFetcher = sp; List<IAppRoleAssignment> assignments = spFetcher.AppRoleAssignedTo.ExecuteAsync().Result.CurrentPage.ToList(); // TODO: Paging // TODO: Better Error Handling // TODO: Retry Logic // TODO: Nested Groups // TODO: Paged Results on Assignments // TODO: Paged Results on Group Membership // TODO: Performance & Batch Queries // Get the groups assigned to the app first foreach (IAppRoleAssignment assignment in assignments) { if (assignment.PrincipalType == "Group") { // Get the group members IGroupFetcher gFetcher = graphClient.Groups.GetByObjectId(assignment.PrincipalId.ToString()); List<IDirectoryObject> members = gFetcher.Members.ExecuteAsync().Result.CurrentPage.ToList(); foreach (IDirectoryObject member in members) { if (member is User) { User user = (User)member; int existingUserIndex = userHistory.FindIndex(u => u.ObjectId == user.ObjectId); // If the user did not exist in the db before if (existingUserIndex == -1) { // The user is new usersWithStatus.Add(new Models.User(user) { assignmentStatus = "New" }); updatedUserHistory.Add(new Models.User(user)); } else { // The user is active, but not new usersWithStatus[usersWithStatus.FindIndex(u => u.ObjectId == user.ObjectId)] = new Models.User(user) { assignmentStatus = "Enabled" }; updatedUserHistory[existingUserIndex] = new Models.User(user); } } } } } // Get the users assigned to the app second foreach (IAppRoleAssignment assignment in assignments) { if (assignment.PrincipalType == "User") { int existingUserIndex = userHistory.FindIndex(u => u.ObjectId == assignment.PrincipalId.ToString()); int assignedUserIndex = usersWithStatus.FindIndex(u => u.ObjectId == assignment.PrincipalId.ToString()); // If we haven't seen the user before, add it if (existingUserIndex == -1 && assignedUserIndex == -1) { User user = (User)await graphClient.Users.GetByObjectId(assignment.PrincipalId.ToString()).ExecuteAsync(); usersWithStatus.Add(new Models.User(user) { assignmentStatus = "New" }); updatedUserHistory.Add(new Models.User(user)); } // If we have seen the user before but didn't already update his data as part of group assignment, update the user data. else if (existingUserIndex >= 0 && string.IsNullOrEmpty(usersWithStatus[assignedUserIndex].assignmentStatus)) { User user = (User)await graphClient.Users.GetByObjectId(assignment.PrincipalId.ToString()).ExecuteAsync(); usersWithStatus[usersWithStatus.FindIndex(u => u.ObjectId == user.ObjectId)] = new Models.User(user) { assignmentStatus = "Enabled" }; updatedUserHistory[existingUserIndex] = new Models.User(user); } } } UsersDbHelper.SaveUsersForTenant(tenantId, updatedUserHistory); return usersWithStatus; } catch (AdalException ex) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } }
public AksStack() { var resourceGroup = new ResourceGroup("aks-rg"); var randomPassword = new RandomPassword("password", new RandomPasswordArgs { Length = 20, Special = true, }).Result; var sshPublicKey = new PrivateKey("ssh-key", new PrivateKeyArgs { Algorithm = "RSA", RsaBits = 4096, }).PublicKeyOpenssh; // Create the AD service principal for the K8s cluster. var adApp = new Application("aks"); var adSp = new ServicePrincipal("aksSp", new ServicePrincipalArgs { ApplicationId = adApp.ApplicationId }); var adSpPassword = new ServicePrincipalPassword("aksSpPassword", new ServicePrincipalPasswordArgs { ServicePrincipalId = adSp.Id, Value = randomPassword, EndDate = "2099-01-01T00:00:00Z", }); // Grant networking permissions to the SP (needed e.g. to provision Load Balancers). var assignment = new Assignment("role-assignment", new AssignmentArgs { PrincipalId = adSp.Id, Scope = resourceGroup.Id, RoleDefinitionName = "Network Contributor" }); // Create a Virtual Network for the cluster. var vnet = new VirtualNetwork("vnet", new VirtualNetworkArgs { ResourceGroupName = resourceGroup.Name, AddressSpaces = { "10.2.0.0/16" }, }); // Create a Subnet for the cluster. var subnet = new Subnet("subnet", new SubnetArgs { ResourceGroupName = resourceGroup.Name, VirtualNetworkName = vnet.Name, AddressPrefix = "10.2.1.0/24", }); // Now allocate an AKS cluster. var cluster = new KubernetesCluster("aksCluster", new KubernetesClusterArgs { ResourceGroupName = resourceGroup.Name, DefaultNodePool = new KubernetesClusterDefaultNodePoolArgs { Name = "aksagentpool", NodeCount = 3, VmSize = "Standard_B2s", OsDiskSizeGb = 30, VnetSubnetId = subnet.Id }, DnsPrefix = "sampleaks", LinuxProfile = new KubernetesClusterLinuxProfileArgs { AdminUsername = "******", SshKey = new KubernetesClusterLinuxProfileSshKeyArgs { KeyData = sshPublicKey, }, }, ServicePrincipal = new KubernetesClusterServicePrincipalArgs { ClientId = adApp.ApplicationId, ClientSecret = adSpPassword.Value, }, KubernetesVersion = "1.16.9", RoleBasedAccessControl = new KubernetesClusterRoleBasedAccessControlArgs { Enabled = true }, NetworkProfile = new KubernetesClusterNetworkProfileArgs { NetworkPlugin = "azure", DnsServiceIp = "10.2.2.254", ServiceCidr = "10.2.2.0/24", DockerBridgeCidr = "172.17.0.1/16", }, }); // Create a k8s provider pointing to the kubeconfig. var k8sProvider = new Pulumi.Kubernetes.Provider("k8s", new Pulumi.Kubernetes.ProviderArgs { KubeConfig = cluster.KubeConfigRaw }); var customResourceOptions = new CustomResourceOptions { Provider = k8sProvider }; // Create a Container Registry. var registry = new Registry("acregistry", new RegistryArgs { ResourceGroupName = resourceGroup.Name, Sku = "Basic", AdminEnabled = true }); // Build & push the sample application to the registry. var applicationName = "sample-application"; var imageName = registry.LoginServer.Apply(value => $"{value}/{applicationName}"); var image = new Image(applicationName, new ImageArgs { Build = "./SampleApplication", Registry = new ImageRegistry { Server = registry.LoginServer, Username = registry.AdminUsername, Password = registry.AdminPassword }, ImageName = imageName }, new ComponentResourceOptions { Provider = k8sProvider }); // Create a k8s secret for use when pulling images from the container registry when deploying the sample application. var dockerCfg = Output.All <string>(registry.LoginServer, registry.AdminUsername, registry.AdminPassword).Apply( values => { var r = new Dictionary <string, object>(); var server = values[0]; var username = values[1]; var password = values[2]; r[server] = new { email = "*****@*****.**", username, password }; return(r); }); var dockerCfgString = dockerCfg.Apply(x => Convert.ToBase64String(Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(x)))); var dockerCfgSecretName = "dockercfg-secret"; var dockerCfgSecret = new Pulumi.Kubernetes.Core.V1.Secret(dockerCfgSecretName, new SecretArgs { Data = { { ".dockercfg", dockerCfgString } }, Type = "kubernetes.io/dockercfg", Metadata = new ObjectMetaArgs { Name = dockerCfgSecretName, } }, customResourceOptions); // Deploy the sample application to the cluster. var labels = new InputMap <string> { { "app", $"app-{applicationName}" }, }; var deployment = new Pulumi.Kubernetes.Apps.V1.Deployment(applicationName, new DeploymentArgs { Spec = new DeploymentSpecArgs { Selector = new LabelSelectorArgs { MatchLabels = labels, }, Replicas = 1, Template = new PodTemplateSpecArgs { Metadata = new ObjectMetaArgs { Labels = labels, Name = applicationName }, Spec = new PodSpecArgs { Containers = new List <ContainerArgs> { new ContainerArgs { Name = applicationName, Image = image.ImageName, } }, ImagePullSecrets = new LocalObjectReferenceArgs { Name = dockerCfgSecretName } } } } }, customResourceOptions); // Create a new service. var service = new Pulumi.Kubernetes.Core.V1.Service(applicationName, new ServiceArgs { Metadata = new ObjectMetaArgs { Name = applicationName, Labels = labels }, Spec = new ServiceSpecArgs { Type = "LoadBalancer", Selector = deployment.Spec.Apply(x => x.Template.Metadata.Labels), Ports = new ServicePortArgs { Port = 80 } } }, customResourceOptions); this.KubeConfig = cluster.KubeConfigRaw; this.DockercfgSecretName = dockerCfgSecret.Metadata.Apply(x => x.Name); }
public async Task <RedirectToRouteResult> Deploy() { try { Log.Info("Read parameters from request data."); var templateIdStr = Request.Form["TemplateId"]; int templateId; if (!int.TryParse(templateIdStr, out templateId)) { throw new ServiceCatalogException("Couldn't read template ID from request."); } Log.Info($"Template ID: {templateId}"); var subscriptionId = Request.Form["SelectedSubscriptionId"]; var location = WebConfigurationManager.AppSettings[ConfigurationConstants.DefaultLocation]; var context = new WebAppContext(); var template = context.TemplateJsons.FirstOrDefault(tj => tj.TemplateId == templateId); if (template == null) { throw new ServiceCatalogException("Couldn't locate template with specified template ID."); } Log.Info("Parse parameters from request data"); var paramsDict = new Dictionary <string, string>(); var tagsDict = new Dictionary <string, string>() { { "Deploy", "ServiceCatalog" }, }; FillParametersAndTagsDictionaries(template.TemplateJson, ref paramsDict, ref tagsDict); Log.Info($"Is Manage Template: {template.IsManageTemplate}"); var jobId = Guid.NewGuid().ToString(); if (template.IsManageTemplate) { Log.Info($"Job Id: {jobId}"); paramsDict["jobid"] = jobId; } var deploymentsId = Guid.NewGuid(); Log.Info("Start deployments - {0}", deploymentsId); var resourceGroupName = template.IsManageTemplate ? "automation-account-resource-group" : Request.Form["SelectedResourceGroupName"]; if (string.IsNullOrWhiteSpace(subscriptionId) || string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ServiceCatalogException("You should specify both Subscription and Resource Group."); } Log.Info($"Subscription ID: {subscriptionId}"); Log.Info($"Resource group name: {resourceGroupName}"); var resourceGroup = await GetOrCreateResourceGroup(resourceGroupName, subscriptionId, location, tagsDict); var parametersObj = TemplateHelper.PrepareTemplateParametersWithValues(template.TemplateJson, paramsDict); Log.Info($"Parameters: {parametersObj}"); var deployment = new Deployment { Properties = new DeploymentProperties { Mode = DeploymentMode.Incremental, Template = JObject.Parse(template.TemplateJson), Parameters = parametersObj, DebugSetting = new DebugSetting() { DetailLevel = "requestContent, responseContent" } } }; var deploymentId = Guid.NewGuid().ToString(); var subscriptions = await new SubscriptionController().GetSubscriptions(); var subscription = subscriptions.FirstOrDefault(s => s.SubscriptionId == subscriptionId); if (template.IsManageTemplate) { using (WebAppContext webAppContext = new WebAppContext()) { Job job = new Job() { Id = jobId, Owner = System.Web.HttpContext.Current.User.Identity.Name }; webAppContext.Jobs.Add(job); webAppContext.SaveChanges(); } } else { using (WebAppContext webAppContext = new WebAppContext()) { DeploymentViewModel deploymentViewModel = new DeploymentViewModel() { DeploymentName = deploymentId, TemplateVersion = template.TemplateJsonVersion, Owner = System.Web.HttpContext.Current.User.Identity.Name, TemplateName = template.TemplateName, Timestamp = DateTime.Now, SubscriptionId = subscription?.SubscriptionId, SubscriptionName = subscription?.DisplayName }; webAppContext.Deployments.Add(deploymentViewModel); webAppContext.SaveChanges(); } } // Preparing endpoint URL for deployment var endpointUrl = string.Format(UriConstants.CreateDeploymentsUri, subscriptionId, resourceGroup.Name, deploymentId); Log.Info($"Sending request to API: {endpointUrl}"); // Start deployment call async var client = new RestApiClient(); var result = await client.CallPutAsync <Deployment, Deployment>(deployment, endpointUrl, await ServicePrincipal.GetAccessToken()); Log.Info(TemplateHelper.ToJson($"Request result: {TemplateHelper.ToJson(result)}")); ViewBag.AsyncOperationUrl = result.AsyncOperationUrl; ViewBag.OperationResultUrl = endpointUrl; ViewBag.FileLogName = $"{DateTime.Today:yyyy-MM-dd}.log"; return(template.IsManageTemplate ? RedirectToAction("RunBooksView", "RunBooks") : RedirectToAction("DeploymentsView", "Deployments")); } catch (Exception exception) { ViewBag.ErrorMessage = "Error"; ViewBag.ErrorDetails = exception.Message; Log.Error(exception); return(RedirectToAction("DeploymentsView", "Deployments")); } }
public AzureWebapp(Webapp target, ServicePrincipal servicePrincipal) { _target = target; _servicePrincipal = servicePrincipal; }
/// <summary> /// Helper method for adding an object to servicePrincipals collection. /// </summary> /// <param name="group"></param> public void AddToserviceprincipals(ServicePrincipal servicePrincipal) { base.AddObject("directoryObjects", servicePrincipal); }
public VaultCreateOrUpdateParameters GetCreationParameters( Guid tenantIdGuid, IResourceGroup resourceGroup, ServicePrincipal serviceApplicationSP, User user, IDictionary <string, string> tags = null ) { tags = tags ?? new Dictionary <string, string>(); var keyVaultAccessPolicies = new List <AccessPolicyEntry> { new AccessPolicyEntry { TenantId = tenantIdGuid, ObjectId = serviceApplicationSP.Id, Permissions = new Permissions { Secrets = new List <SecretPermissions> { SecretPermissions.Get }, Certificates = new List <CertificatePermissions> { CertificatePermissions.Get, CertificatePermissions.List } } }, new AccessPolicyEntry { TenantId = tenantIdGuid, ObjectId = user.Id, Permissions = new Permissions { Keys = new List <KeyPermissions> { KeyPermissions.Get, KeyPermissions.List, KeyPermissions.Sign }, Secrets = new List <SecretPermissions> { SecretPermissions.Get, SecretPermissions.List, SecretPermissions.Set, SecretPermissions.Delete }, Certificates = new List <CertificatePermissions> { CertificatePermissions.Get, CertificatePermissions.List, CertificatePermissions.Update, CertificatePermissions.Create, CertificatePermissions.Import } } } }; keyVaultAccessPolicies.ElementAt(0).Validate(); keyVaultAccessPolicies.ElementAt(1).Validate(); var keyVaultParameters = new VaultCreateOrUpdateParameters { Location = resourceGroup.RegionName, Tags = tags, Properties = new VaultProperties { EnabledForDeployment = false, EnabledForTemplateDeployment = false, EnabledForDiskEncryption = false, TenantId = tenantIdGuid, Sku = new Sku { Name = SkuName.Premium, //Family = "A" }, AccessPolicies = keyVaultAccessPolicies } }; keyVaultParameters.Validate(); return(keyVaultParameters); }
/// <summary> /// Register Application to Azure AD /// </summary> /// <returns>registered application's clientid</returns> public string RegisterApp() { authContext = new AuthenticationContext(props.Authority); // Application Name string appName = "CRM for LINQPad"; ActiveDirectoryClient activeDirectoryClient; int i = 0; while (true) { // Instantiate ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClientAsApplication(useCurrentUser); if (CheckAzureAdPrivilege(activeDirectoryClient)) { break; } else { MessageBox.Show("Current login user does not have privilege to register an applicaiton to the Azure AD. You need to login as Company Admin so that it can reigster an applicaiton, or cancel the wizard, then enter ClientId/RedirectUri manually."); // Clear the ADAL cache. authContext.TokenCache.Clear(); useCurrentUser = false; if (i == 1) { return(null); } else { i++; } } } // Check if same name application already exists. var existingApp = activeDirectoryClient.Applications .Where(x => x.DisplayName == appName) .ExecuteAsync().Result.CurrentPage.FirstOrDefault(); // If it is already registered, then return existing clientid. if (existingApp != null && existingApp.RequiredResourceAccess.Count() == 2) { return(existingApp.AppId); } else { existingApp.DeleteAsync().Wait(); } // Instantiate Application to Azure AD. IApplication myapp = new Microsoft.Azure.ActiveDirectory.GraphClient.Application(); myapp.DisplayName = appName; var redirectUri = "http://localhost/linqpad"; myapp.ReplyUrls.Add(redirectUri); props.RedirectUri = redirectUri; myapp.PublicClient = true; // Mark this only to this tenant myapp.AvailableToOtherTenants = false; // Create the Application to Azure AD. activeDirectoryClient.Applications.AddApplicationAsync(myapp).Wait(); // Obtain the created Application. var createdApp = activeDirectoryClient.Applications .Where(x => x.DisplayName == appName) .ExecuteAsync().Result.CurrentPage.FirstOrDefault(); // Instantiate Service regarding to the application. IServicePrincipal myservice = new ServicePrincipal(); myservice.AppId = createdApp.AppId; myservice.Tags.Add("WindowsAzureActiveDirectoryIntegratedApp"); // Create the Service. activeDirectoryClient.ServicePrincipals.AddServicePrincipalAsync(myservice).Wait(); // Obtain the created Service. var createdService = activeDirectoryClient.ServicePrincipals .Where(x => x.DisplayName == appName) .ExecuteAsync().Result.CurrentPage.FirstOrDefault(); // Set permissions. // Get Microsoft.Azure.ActiveDirectory Service. var service1 = activeDirectoryClient.ServicePrincipals .Where(x => x.AppId == "00000002-0000-0000-c000-000000000000") .ExecuteAsync().Result.CurrentPage.FirstOrDefault(); // Instantiate UserProfile.Read OAuth2PermissionGrant for the Service OAuth2PermissionGrant grant0 = new OAuth2PermissionGrant(); grant0.ClientId = createdService.ObjectId; grant0.ResourceId = service1.ObjectId; grant0.ConsentType = "AllPrincipals"; grant0.Scope = "User.Read"; grant0.ExpiryTime = DateTime.Now.AddYears(1); // Create the OAuth2PermissionGrant activeDirectoryClient.Oauth2PermissionGrants.AddOAuth2PermissionGrantAsync(grant0).Wait(); // Get Microsoft.CRM Service. var service2 = activeDirectoryClient.ServicePrincipals .Where(x => x.AppId == "00000007-0000-0000-c000-000000000000") .ExecuteAsync().Result.CurrentPage.FirstOrDefault(); // Instantiate user_impersonation OAuth2PermissionGrant for the Service OAuth2PermissionGrant grant = new OAuth2PermissionGrant(); grant.ClientId = createdService.ObjectId; grant.ResourceId = service2.ObjectId; grant.ConsentType = "AllPrincipals"; grant.Scope = "user_impersonation"; grant.ExpiryTime = DateTime.Now.AddYears(1); // Create the OAuth2PermissionGrant activeDirectoryClient.Oauth2PermissionGrants.AddOAuth2PermissionGrantAsync(grant).Wait(); // Create RequiredResourceAccess // Instantiate ResourceAccess for Microsoft.Azure.ActiveDirectory/UserProfile.Read permission. ResourceAccess resourceAccess1 = new ResourceAccess(); resourceAccess1.Id = service1.Oauth2Permissions.Where(x => x.Value == "User.Read").First().Id; resourceAccess1.Type = "Scope"; // Instantiate RequiredResourceAccess and assign the ResourceAccess RequiredResourceAccess requiredresourceAccess1 = new RequiredResourceAccess(); requiredresourceAccess1.ResourceAppId = service1.AppId; requiredresourceAccess1.ResourceAccess.Add(resourceAccess1); // Instantiate ResourceAccess for Microsoft.CRM/user_impersonation.Read permission. ResourceAccess resourceAccess2 = new ResourceAccess(); resourceAccess2.Id = service2.Oauth2Permissions.Where(x => x.Value == "user_impersonation").First().Id; resourceAccess2.Type = "Scope"; // Instantiate RequiredResourceAccess and assign the ResourceAccess RequiredResourceAccess requiredResourceAccess2 = new RequiredResourceAccess(); requiredResourceAccess2.ResourceAppId = service2.AppId; requiredResourceAccess2.ResourceAccess.Add(resourceAccess2); // Add RequiredResourceAccess information to the Application createdApp.RequiredResourceAccess.Add(requiredresourceAccess1); createdApp.RequiredResourceAccess.Add(requiredResourceAccess2); // Update the Application createdApp.UpdateAsync().Wait(); // Once all Azure AD work done, clear ADAL cache again in case user logged in as different user. authContext.TokenCache.Clear(); // Return AppId (ClientId) return(createdApp.AppId); }
internal async Task <ApplicationParameters> CreateNewApp(TokenCredential tokenCredential, ApplicationParameters applicationParameters) { var graphServiceClient = GetGraphServiceClient(tokenCredential); // Get the tenant Organization?tenant = await GetTenant(graphServiceClient); // Create the app. Application application = new Application() { DisplayName = applicationParameters.ApplicationDisplayName, SignInAudience = AppParameterAudienceToMicrosoftIdentityPlatformAppAudience(applicationParameters.SignInAudience !), Description = applicationParameters.Description }; if (applicationParameters.IsWebApi) { application.Api = new ApiApplication() { RequestedAccessTokenVersion = 2, }; } if (applicationParameters.IsWebApp) { AddWebAppPlatform(applicationParameters, application); } else if (applicationParameters.IsBlazorWasm) { // In .NET Core 3.1, Blazor uses MSAL.js 1.x (web redirect URIs) // whereas in .NET 5.0, Blazor uses MSAL.js 2.x (SPA redirect URIs) if (applicationParameters.TargetFramework == "net5.0") { AddSpaPlatform(applicationParameters, application); } else { AddWebAppPlatform(applicationParameters, application, true); } } IEnumerable <IGrouping <string, ResourceAndScope> >?scopesPerResource = await AddApiPermissions( applicationParameters, graphServiceClient, application).ConfigureAwait(false); Application createdApplication = await graphServiceClient.Applications .Request() .AddAsync(application); // Creates a service principal (needed for B2C) ServicePrincipal servicePrincipal = new ServicePrincipal { AppId = createdApplication.AppId, }; // B2C does not allow user consent, and therefore we need to explicity create // a service principal and permission grants. It's also useful for Blazorwasm hosted // applications. We create it always. var createdServicePrincipal = await graphServiceClient.ServicePrincipals .Request() .AddAsync(servicePrincipal).ConfigureAwait(false); // B2C does not allow user consent, and therefore we need to explicity grant permissions if (applicationParameters.IsB2C) { await AddAdminConsentToApiPermissions( graphServiceClient, createdServicePrincipal, scopesPerResource); } // For web API, we need to know the appId of the created app to compute the Identifier URI, // and therefore we need to do it after the app is created (updating the app) if (applicationParameters.IsWebApi && createdApplication.Api != null && (createdApplication.IdentifierUris == null || !createdApplication.IdentifierUris.Any())) { await ExposeScopes(graphServiceClient, createdApplication); // Blazorwasm hosted: add permission to server web API from client SPA if (applicationParameters.IsBlazorWasm) { await AddApiPermissionFromBlazorwasmHostedSpaToServerApi( graphServiceClient, createdApplication, createdServicePrincipal, applicationParameters.IsB2C); } } // Re-reading the app to be sure to have everything. createdApplication = (await graphServiceClient.Applications .Request() .Filter($"appId eq '{createdApplication.AppId}'") .GetAsync()).First(); var effectiveApplicationParameters = GetEffectiveApplicationParameters(tenant !, createdApplication, applicationParameters); // Add password credentials if (applicationParameters.CallsMicrosoftGraph || applicationParameters.CallsDownstreamApi) { await AddPasswordCredentials( graphServiceClient, createdApplication, effectiveApplicationParameters); } return(effectiveApplicationParameters); }