public async Task<AdApplication> AssureAzureAdAppAndPrincipal(GraphClient cl, Guid tenantId) { AdApplication app = null; ServicePrincipal principal = null; app = await cl.GetApplicationAsync(); if (app != null) principal = await cl.GetServicePrincipalAsync(app.AppId); if (app == null || principal == null) { var r = System.Windows.MessageBox.Show("An application has to be created in your Azure AD. Do you want to continue?", "Please confirm...", System.Windows.MessageBoxButton.OKCancel); if (r == System.Windows.MessageBoxResult.OK) { if (app == null) app = await cl.CreateApplicationAsync(); if (principal == null) { principal = await cl.CreateServicePrincipalAsync(app.AppId); await Task.Factory.StartNew(() => System.Threading.Thread.Sleep(30)); //sleep for 30 secconds so principal is available } } else return null; } return app; }
public async Task<bool> Connect(AutomationAccountInfo accountInfo, TimeSpan credValidity) { try { ProgressStatus = "Configuring..."; var mp = AssureConfigManagementPack(); var client = new GraphClient(accountInfo.TenantId); client.AuthorizationCodeRequired += client_AuthorizationCodeRequired; ProgressStatus = "Configuring service principal..."; var app = await AssureAzureAdAppAndPrincipal(client, accountInfo.TenantId); if (app == null) return false; await RenewServiceCredential(client, mp, app, credValidity); ProgressStatus = "Setting service principal permissions..."; var principal = await client.GetServicePrincipalAsync(app.AppId); await _configClient.SetServicePrincipalPermission(accountInfo, principal.ObjectId); ProgressStatus = "Saving changes..."; Settings.TenantId = accountInfo.TenantId; Settings.SubscriptionId = accountInfo.SubscriptionId; Settings.ResourceGroupName = accountInfo.ResourceGroupName; Settings.AutomationAccountName = accountInfo.AutomationAccountName; if (string.IsNullOrEmpty(Settings.DefaultRunOn)) Settings.DefaultRunOn = "Azure"; //EnableWorkflows(); CommitSettings(); return true; } catch (Exception e) { ShowError(e); return false; } }