private bool TryGetTenantSubscription(IAccessToken accessToken, AzureAccount account, AzureEnvironment environment, string tenantId, string subscriptionId, string subscriptionName, out AzureSubscription subscription, out AzureTenant tenant) { using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>( new TokenCloudCredentials(accessToken.AccessToken), environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager))) { Subscriptions.Models.Subscription subscriptionFromServer = null; try { if (subscriptionId != null) { subscriptionFromServer = subscriptionClient.Subscriptions.Get(subscriptionId).Subscription; } else { var subscriptions = subscriptionClient.Subscriptions.List().Subscriptions; if (subscriptions != null && subscriptions.Any()) { if (subscriptionName != null) { subscriptionFromServer = subscriptions.FirstOrDefault(s => s.DisplayName.Equals(subscriptionName, StringComparison.OrdinalIgnoreCase)); } else { if (subscriptions.Count > 1) { WriteWarningMessage(string.Format( "TenantId '{0}' contains more than one subscription. First one will be selected for further use. " + "To select another subscription, use Set-AzureRmContext.", tenantId)); } subscriptionFromServer = subscriptions.First(); } } } } catch (CloudException ex) { WriteWarningMessage(ex.Message); } if (subscriptionFromServer != null) { subscription = new AzureSubscription { Id = new Guid(subscriptionFromServer.SubscriptionId), Account = accessToken.UserId, Environment = environment.Name, Name = subscriptionFromServer.DisplayName, Properties = new Dictionary <AzureSubscription.Property, string> { { AzureSubscription.Property.Tenants, accessToken.TenantId } } }; tenant = new AzureTenant(); tenant.Id = new Guid(accessToken.TenantId); tenant.Domain = accessToken.GetDomain(); return(true); } subscription = null; if (accessToken != null && accessToken.TenantId != null) { tenant = new AzureTenant(); tenant.Id = Guid.Parse(accessToken.TenantId); if (accessToken.UserId != null) { var domain = accessToken.UserId.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries); if (domain.Length == 2) { tenant.Domain = domain[1]; } } return(true); } tenant = null; return(false); } }
private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode) { TestEnvironment rdfeEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment(); TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment(); TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment); if (currentEnvironment.UserName == null) { currentEnvironment.UserName = "******"; } SetAuthenticationFactory(mode, rdfeEnvironment, csmEnvironment); AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName }; Debug.Assert(currentEnvironment != null); environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri; if (csmEnvironment != null) { environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = csmEnvironment.BaseUri.AbsoluteUri; } if (rdfeEnvironment != null) { environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = rdfeEnvironment.BaseUri.AbsoluteUri; } if (!ProfileClient.Profile.Environments.ContainsKey(testEnvironmentName)) { ProfileClient.AddOrSetEnvironment(environment); } if (currentEnvironment.SubscriptionId != null) { testSubscription = new AzureSubscription() { Id = new Guid(currentEnvironment.SubscriptionId), Name = testSubscriptionName, Environment = testEnvironmentName, Account = currentEnvironment.UserName, Properties = new Dictionary <AzureSubscription.Property, string> { { AzureSubscription.Property.Default, "True" }, { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT") }, } }; testAccount = new AzureAccount() { Id = currentEnvironment.UserName, Type = AzureAccount.AccountType.User, Properties = new Dictionary <AzureAccount.Property, string> { { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId }, } }; ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription; ProfileClient.Profile.Accounts[testAccount.Id] = testAccount; ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account); } }
public override void ExecuteCmdlet() { Guid subscrptionIdGuid; string subscriptionName = null; string subscriptionId = null; if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription))) { if (Guid.TryParse(Subscription, out subscrptionIdGuid)) { subscriptionId = Subscription; } else { subscriptionName = Subscription; } } AzureAccount azureAccount = new AzureAccount(); switch (ParameterSetName) { case AccessTokenParameterSet: azureAccount.Type = AzureAccount.AccountType.AccessToken; azureAccount.Id = AccountId; azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken); azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken); azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken); break; case ServicePrincipalCertificateParameterSet: case ServicePrincipalParameterSet: azureAccount.Type = AzureAccount.AccountType.ServicePrincipal; break; case ManagedServiceParameterSet: azureAccount.Type = AzureAccount.AccountType.ManagedService; var builder = new UriBuilder(); builder.Scheme = "http"; builder.Host = ManagedServiceHostName; builder.Port = ManagedServicePort; builder.Path = "/oauth2/token"; string msiSecret = this.IsBound(nameof(ManagedServiceSecret)) ? ManagedServiceSecret.ConvertToString() : System.Environment.GetEnvironmentVariable(MSISecretVariable); string suppliedUri = this.IsBound(nameof(ManagedServiceHostName)) ? builder.Uri.ToString() : System.Environment.GetEnvironmentVariable(MSIEndpointVariable); if (!string.IsNullOrWhiteSpace(msiSecret)) { azureAccount.SetProperty(AzureAccount.Property.MSILoginSecret, msiSecret); } if (!string.IsNullOrWhiteSpace(suppliedUri)) { azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, suppliedUri); } else { azureAccount.SetProperty(AzureAccount.Property.MSILoginUriBackup, builder.Uri.ToString()); azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, AuthenticationFactory.DefaultMSILoginUri); } azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : string.Format("MSI@{0}", ManagedServicePort); break; default: azureAccount.Type = AzureAccount.AccountType.User; break; } SecureString password = null; if (Credential != null) { azureAccount.Id = Credential.UserName; password = Credential.Password; } if (!string.IsNullOrEmpty(ApplicationId)) { azureAccount.Id = ApplicationId; } if (!string.IsNullOrWhiteSpace(CertificateThumbprint)) { azureAccount.SetThumbprint(CertificateThumbprint); } if (!string.IsNullOrEmpty(TenantId)) { azureAccount.SetProperty(AzureAccount.Property.Tenants, new[] { TenantId }); } if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in")) { if (AzureRmProfileProvider.Instance.Profile == null) { InitializeProfileProvider(); } SetContextWithOverwritePrompt((localProfile, profileClient, name) => { WriteObject((PSAzureProfile)profileClient.Login( azureAccount, _environment, TenantId, subscriptionId, subscriptionName, password, SkipValidation, (s) => WriteWarning(s), name, !this.SkipContextPopulation.IsPresent)); }); } }
private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode) { TestEnvironment currentEnvironment = null; if (mode == AzureModule.AzureResourceManager) { currentEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment(); } else { currentEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment(); } if (currentEnvironment.UserName == null) { currentEnvironment.UserName = "******"; } SetAuthenticationFactory(mode, currentEnvironment); AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName }; Debug.Assert(currentEnvironment != null); environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = currentEnvironment.BaseUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = currentEnvironment.Endpoints.ResourceManagementUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.Graph] = currentEnvironment.Endpoints.GraphUri.AbsoluteUri; if (!ProfileClient.Profile.Environments.ContainsKey(testEnvironmentName)) { ProfileClient.AddOrSetEnvironment(environment); } if (!AzureRmProfileProvider.Instance.Profile.Environments.ContainsKey(testEnvironmentName)) { AzureRmProfileProvider.Instance.Profile.Environments[testEnvironmentName] = environment; } if (currentEnvironment.SubscriptionId != null) { testSubscription = new AzureSubscription() { Id = new Guid(currentEnvironment.SubscriptionId), Name = testSubscriptionName, Environment = testEnvironmentName, Account = currentEnvironment.UserName, Properties = new Dictionary <AzureSubscription.Property, string> { { AzureSubscription.Property.Default, "True" }, { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT") }, } }; testAccount = new AzureAccount() { Id = currentEnvironment.UserName, Type = AzureAccount.AccountType.User, Properties = new Dictionary <AzureAccount.Property, string> { { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId }, } }; ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription; ProfileClient.Profile.Accounts[testAccount.Id] = testAccount; ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account); var testTenant = new AzureTenant() { Id = Guid.NewGuid() }; if (!string.IsNullOrEmpty(currentEnvironment.Tenant)) { Guid tenant; if (Guid.TryParse(currentEnvironment.Tenant, out tenant)) { testTenant.Id = tenant; } } AzureRmProfileProvider.Instance.Profile.Context = new AzureContext(testSubscription, testAccount, environment, testTenant); } }
public override void ExecuteCmdlet() { if (DefaultProfile != null && DefaultProfile.DefaultContext == null) { WriteVerbose(string.Format("No accounts were found to disconnect from. Ending call to Disconnect-{0}Account.", ResourceManager.Common.AzureRMConstants.AzureRMPrefix)); WriteObject(null); return; } IAzureAccount azureAccount = null; switch (ParameterSetName) { case UserIdParameterSet: azureAccount = new AzureAccount { Id = Username, Type = AzureAccount.AccountType.User }; break; case ServicePrincipalParameterSet: azureAccount = new AzureAccount { Id = ApplicationId, Type = AzureAccount.AccountType.ServicePrincipal }; azureAccount.SetTenants(TenantId); break; case InputObjectParametrSet: azureAccount = InputObject; break; case ContextParameterSet: azureAccount = AzureContext.Account; break; case ContextNameParameterSet: if (MyInvocation.BoundParameters.ContainsKey(nameof(ContextName))) { var profile = DefaultProfile as AzureRmProfile; azureAccount = profile.Contexts[ContextName].Account; } else { azureAccount = DefaultContext?.Account; } break; } if (azureAccount == null || string.IsNullOrWhiteSpace(azureAccount.Id)) { WriteExceptionError(new ArgumentException("Provide a valid account or context")); } else { if (ShouldProcess(string.Format("Log out principal '{0}'", azureAccount.Id), "log out")) { if (GetContextModificationScope() == ContextModificationScope.CurrentUser) { AzureSession.Instance.AuthenticationFactory.RemoveUser(azureAccount, AzureSession.Instance.TokenCache); } if (AzureRmProfileProvider.Instance.Profile != null) { ModifyContext((localProfile, profileClient) => { var matchingContexts = localProfile.Contexts?.Values?.Where((c) => c != null && c.Account != null && string.Equals(c.Account.Id, azureAccount.Id, StringComparison.CurrentCultureIgnoreCase)); foreach (var context in matchingContexts) { profileClient.TryRemoveContext(context); } }); } WriteObject(new PSAzureRmAccount(azureAccount)); } } }
public void CanAuthenticateUsingMSIObjectId() { AzureSessionInitializer.InitializeAzureSession(); IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder(); AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder); PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory); string expectedAccessToken = Guid.NewGuid().ToString(); _output.WriteLine("Expected access token for ARM URI: {0}", expectedAccessToken); string expectedToken2 = Guid.NewGuid().ToString(); string tenant = Guid.NewGuid().ToString(); _output.WriteLine("Expected access token for graph URI: {0}", expectedToken2); string userId = Guid.NewGuid().ToString(); var account = new AzureAccount { Id = userId, Type = AzureAccount.AccountType.ManagedService }; var environment = AzureEnvironment.PublicEnvironments["AzureCloud"]; var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId; var builder = new UriBuilder(AuthenticationFactory.DefaultMSILoginUri); builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&object_id={userId}&api-version=2018-02-01"; var defaultUri = builder.Uri.ToString(); var customBuilder = new UriBuilder(AuthenticationFactory.DefaultMSILoginUri); customBuilder.Query = $"resource={Uri.EscapeDataString(environment.GraphEndpointResourceId)}&object_id={userId}&api-version=2018-02-01"; var customUri = customBuilder.Uri.ToString(); var responses = new Dictionary <string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase) { { defaultUri, new ManagedServiceTokenInfo { AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource = expectedResource } }, { customUri, new ManagedServiceTokenInfo { AccessToken = expectedToken2, ExpiresIn = 3600, Resource = environment.GraphEndpointResourceId } } }; AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true); var authFactory = new AuthenticationFactory(); IRenewableToken token = (IRenewableToken)authFactory.Authenticate(account, environment, tenant, null, null, null); _output.WriteLine($"Received access token for default Uri ${token.AccessToken}"); Assert.Equal(expectedAccessToken, token.AccessToken); Assert.Equal(3600, Math.Round(token.ExpiresOn.Subtract(DateTimeOffset.Now).TotalSeconds)); var account2 = new AzureAccount { Id = userId, Type = AzureAccount.AccountType.ManagedService }; var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, AzureEnvironment.Endpoint.GraphEndpointResourceId); _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}"); Assert.Equal(expectedToken2, token2.AccessToken); var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar"); Assert.Throws <InvalidOperationException>(() => token3.AccessToken); }
public static bool IsAzureAccountPresent() { return(!AzureAccount.GetInstance().IsEmpty()); }
public void CanAuthenticateUsingMSIDefault() { AzureSessionInitializer.InitializeAzureSession(); IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder(); AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder); PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory); var msalAccessTokenAcquirerFactory = new MsalAccessTokenAcquirerFactory(); AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => msalAccessTokenAcquirerFactory); string expectedAccessToken = Guid.NewGuid().ToString(); _output.WriteLine("Expected access token for default URI: {0}", expectedAccessToken); var mockAzureCredentialFactory = new MockAzureCredentialFactory(); MockManagedIdentityCredential mockManagedIdentityCredential = null; mockAzureCredentialFactory.CredentialFactory = (clientId) => { return(mockManagedIdentityCredential = new MockManagedIdentityCredential(clientId) { TokenFactory = () => new AccessToken(expectedAccessToken, DateTimeOffset.Now) }); }; AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => (AzureCredentialFactory)mockAzureCredentialFactory, true); string expectedToken2 = Guid.NewGuid().ToString(); string tenant = Guid.NewGuid().ToString(); _output.WriteLine("Expected access token for custom URI: {0}", expectedToken2); string userId = Constants.DefaultMsiAccountIdPrefix + "12345"; var account = new AzureAccount { Id = userId, Type = AzureAccount.AccountType.ManagedService }; var environment = AzureEnvironment.PublicEnvironments["AzureCloud"]; var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId; var builder = new UriBuilder(AuthenticationFactory.DefaultBackupMSILoginUri); //builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&api-version=2018-02-01"; //var defaultUri = builder.Uri.ToString(); //var responses = new Dictionary<string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase) //{ // {defaultUri, new ManagedServiceTokenInfo { AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource=expectedResource}}, // {"http://*****:*****@foo.com"; var account2 = new AzureAccount { Id = userId2, Type = AzureAccount.AccountType.ManagedService }; //account2.SetProperty(AzureAccount.Property.MSILoginUri, "http://myfunkyurl:10432/oauth2/token"); expectedAccessToken = expectedToken2; var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, "foo"); _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}"); Assert.Equal(expectedToken2, token2.AccessToken); Assert.Equal(userId2, mockManagedIdentityCredential.AccountId); //var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar"); //Assert.Throws<InvalidOperationException>(() => token3.AccessToken); }
public static IHDInsightSubscriptionCredentials GetAccessTokenCredentials(this IAzureHDInsightCommonCommandBase command, AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment) { ProfileClient profileClient = new ProfileClient(); AzureContext azureContext = new AzureContext { Subscription = currentSubscription, Environment = environment, Account = azureAccount }; var cloudCredentials = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(azureContext) as AccessTokenCredential; if (cloudCredentials != null) { var field = typeof(AccessTokenCredential).GetField("token", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance); var accessToken = field.GetValue(cloudCredentials) as IAccessToken; if (accessToken != null) { return(new HDInsightAccessTokenCredential() { SubscriptionId = currentSubscription.Id, AccessToken = accessToken.AccessToken }); } } return(null); }
/// <summary> /// Performs the execution of the command. /// </summary> protected override void ProcessRecord() { AuthenticationResult authResult; AzureAccount account = new AzureAccount(); #if NETSTANDARD DeviceCodeResult deviceCodeResult; #else AuthorizationResult authorizationResult; #endif IPartnerServiceClient client; PartnerEnvironment environment; Uri authority; string clientId; string resource; if (ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.Properties[AzureAccountPropertyType.ServicePrincipalSecret] = Credential.Password.ConvertToString(); account.Type = AccountType.ServicePrincipal; clientId = string.IsNullOrEmpty(ApplicationId) ? Credential.UserName : ApplicationId; } else { account.Type = AccountType.User; clientId = ApplicationId; } account.Properties[AzureAccountPropertyType.Tenant] = string.IsNullOrEmpty(TenantId) ? AuthenticationConstants.CommonEndpoint : TenantId; environment = PartnerEnvironment.PublicEnvironments[Environment]; client = new PartnerServiceClient(httpClient); authority = new Uri($"{environment.ActiveDirectoryAuthority}{account.Properties[AzureAccountPropertyType.Tenant]}"); resource = string.IsNullOrEmpty(Resource) ? environment.PartnerCenterEndpoint : Resource; if (!string.IsNullOrEmpty(RefreshToken)) { authResult = client.RefreshAccessTokenAsync( authority, resource, RefreshToken, clientId, Credential?.Password.ConvertToString()).GetAwaiter().GetResult(); } else if (account.Type == AccountType.ServicePrincipal && !Consent.ToBool()) { authResult = client.AcquireTokenAsync( authority, resource, clientId, Credential.Password.ConvertToString()).GetAwaiter().GetResult(); } #if NETSTANDARD else { deviceCodeResult = client.AcquireDeviceCodeAsync( authority, resource, clientId, Credential?.Password.ConvertToString()).GetAwaiter().GetResult(); WriteWarning(deviceCodeResult.Message); authResult = client.AcquireTokenByDeviceCodeAsync( authority, deviceCodeResult, Credential?.Password.ConvertToString()).GetAwaiter().GetResult(); }
public static IHDInsightSubscriptionCredentials GetSubscriptionCertificateCredentials(this IAzureHDInsightCommonCommandBase command, AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment) { return(new HDInsightCertificateCredential { SubscriptionId = currentSubscription.Id, Certificate = ProfileClient.DataStore.GetCertificate(currentSubscription.Account), Endpoint = environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement), }); }
public override void ExecuteCmdlet() { Guid subscriptionIdGuid; string subscriptionName = null; string subscriptionId = null; if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription))) { if (Guid.TryParse(Subscription, out subscriptionIdGuid)) { subscriptionId = Subscription; } else { subscriptionName = Subscription; } } if (ClientAssertionParameterSet.Equals(ParameterSetName, StringComparison.OrdinalIgnoreCase)) { string suppressWarningOrErrorValue = System.Environment.GetEnvironmentVariable(BreakingChangeAttributeHelper.SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME); bool.TryParse(suppressWarningOrErrorValue, out bool suppressWarningOrError); if (!suppressWarningOrError) { WriteWarning("The feature related to parameter name 'FederatedToken' is under preview."); } } var azureAccount = new AzureAccount(); switch (ParameterSetName) { case UserParameterSet: azureAccount.Type = AzureAccount.AccountType.User; if (!string.IsNullOrEmpty(AccountId)) { azureAccount.SetProperty("LoginHint", AccountId); } break; case AccessTokenParameterSet: azureAccount.Type = AzureAccount.AccountType.AccessToken; azureAccount.Id = AccountId; azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken); azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken); azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken); azureAccount.SetProperty(Constants.MicrosoftGraphAccessToken, MicrosoftGraphAccessToken); break; case ServicePrincipalCertificateParameterSet: case ServicePrincipalCertificateFileParameterSet: case ServicePrincipalParameterSet: azureAccount.Type = AzureAccount.AccountType.ServicePrincipal; break; case ClientAssertionParameterSet: azureAccount.Type = "ClientAssertion"; break; case ManagedServiceParameterSet: azureAccount.Type = AzureAccount.AccountType.ManagedService; azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : $"{Constants.DefaultMsiAccountIdPrefix}{DefaultManagedServicePort}"; break; default: //Support username + password for both Windows PowerShell and PowerShell 6+ azureAccount.Type = AzureAccount.AccountType.User; break; } SecureString password = null; if (Credential != null) { azureAccount.Id = Credential.UserName; password = Credential.Password; } if (UseDeviceAuthentication.IsPresent) { azureAccount.SetProperty("UseDeviceAuth", "true"); } if (azureAccount.Type == AzureAccount.AccountType.User && password != null) { azureAccount.SetProperty(AzureAccount.Property.UsePasswordAuth, "true"); } if (!string.IsNullOrEmpty(ApplicationId)) { azureAccount.Id = ApplicationId; } if (!string.IsNullOrWhiteSpace(CertificateThumbprint)) { azureAccount.SetThumbprint(CertificateThumbprint); } if (!string.IsNullOrWhiteSpace(CertificatePath)) { var resolvedPath = this.SessionState.Path.GetResolvedPSPathFromPSPath(CertificatePath).FirstOrDefault()?.Path; if (string.IsNullOrEmpty(resolvedPath)) { var parametersLog = $"- Invalid certificate path :'{CertificatePath}'."; throw new InvalidOperationException(parametersLog); } azureAccount.SetProperty(AzureAccount.Property.CertificatePath, resolvedPath); if (CertificatePassword != null) { azureAccount.SetProperty(AzureAccount.Property.CertificatePassword, CertificatePassword.ConvertToString()); } } if ((ParameterSetName == ServicePrincipalCertificateParameterSet || ParameterSetName == ServicePrincipalCertificateFileParameterSet) && SendCertificateChain) { azureAccount.SetProperty(AzureAccount.Property.SendCertificateChain, SendCertificateChain.ToString()); bool supressWarningOrError = false; try { supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(BreakingChangeAttributeHelper.SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME)); } catch { //if value of env variable is invalid, use default value of supressWarningOrError } if (!supressWarningOrError) { WriteWarning(Resources.PreviewFunctionMessage); } } if (!string.IsNullOrEmpty(Tenant)) { azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant); } if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && password != null) { azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString()); if (GetContextModificationScope() == ContextModificationScope.CurrentUser) { var file = AzureSession.Instance.ARMProfileFile; var directory = AzureSession.Instance.ARMProfileDirectory; WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory)); } } if (azureAccount.Type == "ClientAssertion" && FederatedToken != null) { password = SecureStringExtensions.ConvertToSecureString(FederatedToken); azureAccount.SetProperty("ClientAssertion", FederatedToken); if (GetContextModificationScope() == ContextModificationScope.CurrentUser) { var file = AzureSession.Instance.ARMProfileFile; var directory = AzureSession.Instance.ARMProfileDirectory; WriteWarning(string.Format(Resources.ClientAssertionWarning, file, directory)); } } var resourceId = PreProcessAuthScope(); if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in")) { if (AzureRmProfileProvider.Instance.Profile == null) { InitializeProfileProvider(); } if (!AzureSession.Instance.TryGetComponent(nameof(CommonUtilities), out CommonUtilities commonUtilities)) { commonUtilities = new CommonUtilities(); AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => commonUtilities); } if (!commonUtilities.IsDesktopSession() && IsUsingInteractiveAuthentication()) { WriteWarning(Resources.InteractiveAuthNotSupported); return; } SetContextWithOverwritePrompt((localProfile, profileClient, name) => { bool shouldPopulateContextList = true; if (this.IsParameterBound(c => c.SkipContextPopulation)) { shouldPopulateContextList = false; } profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message))); profileClient.DebugLog = (message) => _tasks.Enqueue(new Task(() => this.WriteDebugWithTimestamp(message))); var task = new Task <AzureRmProfile>(() => profileClient.Login( azureAccount, _environment, Tenant, subscriptionId, subscriptionName, password, SkipValidation, WriteWarningEvent, //Could not use WriteWarning directly because it may be in worker thread name, shouldPopulateContextList, MaxContextPopulation, resourceId)); task.Start(); while (!task.IsCompleted) { HandleActions(); Thread.Yield(); } HandleActions(); try { //Must not use task.Result as it wraps inner exception into AggregateException var result = (PSAzureProfile)task.GetAwaiter().GetResult(); WriteObject(result); } catch (AuthenticationFailedException ex) { if (IsUnableToOpenWebPageError(ex)) { WriteWarning(Resources.InteractiveAuthNotSupported); WriteDebug(ex.ToString()); } else { if (IsUsingInteractiveAuthentication()) { //Display only if user is using Interactive auth WriteWarning(Resources.SuggestToUseDeviceCodeAuth); } WriteDebug(ex.ToString()); throw; } } }); } }
public override void ExecuteCmdlet() { Guid subscrptionIdGuid; string subscriptionName = null; string subscriptionId = null; if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription))) { if (Guid.TryParse(Subscription, out subscrptionIdGuid)) { subscriptionId = Subscription; } else { subscriptionName = Subscription; } } var azureAccount = new AzureAccount(); switch (ParameterSetName) { case AccessTokenParameterSet: azureAccount.Type = AzureAccount.AccountType.AccessToken; azureAccount.Id = AccountId; azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken); azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken); azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken); break; case ServicePrincipalCertificateParameterSet: case ServicePrincipalParameterSet: azureAccount.Type = AzureAccount.AccountType.ServicePrincipal; break; case ManagedServiceParameterSet: azureAccount.Type = AzureAccount.AccountType.ManagedService; var builder = new UriBuilder { Scheme = "http", Host = ManagedServiceHostName, Port = ManagedServicePort, Path = "/oauth2/token" }; var envSecret = System.Environment.GetEnvironmentVariable(MSISecretVariable); var msiSecret = this.IsBound(nameof(ManagedServiceSecret)) ? ManagedServiceSecret.ConvertToString() : envSecret; var envUri = System.Environment.GetEnvironmentVariable(MSIEndpointVariable); var suppliedUri = this.IsBound(nameof(ManagedServiceHostName)) ? builder.Uri.ToString() : envUri; if (!this.IsBound(nameof(ManagedServiceHostName)) && !string.IsNullOrWhiteSpace(envUri) && !this.IsBound(nameof(ManagedServiceSecret)) && !string.IsNullOrWhiteSpace(envSecret)) { // set flag indicating this is AppService Managed Identity ad hoc mode azureAccount.SetProperty(AuthenticationFactory.AppServiceManagedIdentityFlag, "the value not used"); } if (!string.IsNullOrWhiteSpace(msiSecret)) { azureAccount.SetProperty(AzureAccount.Property.MSILoginSecret, msiSecret); } if (!string.IsNullOrWhiteSpace(suppliedUri)) { azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, suppliedUri); } else { azureAccount.SetProperty(AzureAccount.Property.MSILoginUriBackup, builder.Uri.ToString()); azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, AuthenticationFactory.DefaultMSILoginUri); } azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : string.Format("MSI@{0}", ManagedServicePort); break; default: if (ParameterSetName == UserWithCredentialParameterSet && string.Equals(SessionState?.PSVariable?.GetValue("PSEdition") as string, "Core")) { throw new InvalidOperationException(Resources.PasswordNotSupported); } azureAccount.Type = AzureAccount.AccountType.User; break; } SecureString password = null; if (Credential != null) { azureAccount.Id = Credential.UserName; password = Credential.Password; } if (UseDeviceAuthentication.IsPresent) { azureAccount.SetProperty("UseDeviceAuth", "true"); } if (!string.IsNullOrEmpty(ApplicationId)) { azureAccount.Id = ApplicationId; } if (!string.IsNullOrWhiteSpace(CertificateThumbprint)) { azureAccount.SetThumbprint(CertificateThumbprint); } if (!string.IsNullOrEmpty(Tenant)) { azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant); } if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && string.IsNullOrEmpty(CertificateThumbprint)) { azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString()); if (GetContextModificationScope() == ContextModificationScope.CurrentUser) { var file = AzureSession.Instance.ARMProfileFile; var directory = AzureSession.Instance.ARMProfileDirectory; WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory)); } } if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in")) { if (AzureRmProfileProvider.Instance.Profile == null) { InitializeProfileProvider(); } SetContextWithOverwritePrompt((localProfile, profileClient, name) => { WriteObject((PSAzureProfile)profileClient.Login( azureAccount, _environment, Tenant, subscriptionId, subscriptionName, password, SkipValidation, WriteWarning, name, !SkipContextPopulation.IsPresent, MaxContextPopulation)); }); } }
public AzureSBQueue(AzureAccount azureAccount) { cloudAccount = azureAccount; }
public static bool IsValidUserAccount(bool showErrorMessage = true, string errorMessage = "Failed Azure authentication.") { try { string _key = AzureAccount.GetInstance().GetKey(); string _endpoint = EndpointToUriConverter.azureRegionToEndpointMapping[AzureAccount.GetInstance().GetRegion()]; AzureAccountAuthentication auth = AzureAccountAuthentication.GetInstance(_endpoint, _key); string accessToken = auth.GetAccessToken(); Console.WriteLine("Token: {0}\n", accessToken); } catch { Console.WriteLine(errorMessage); if (showErrorMessage) { MessageBox.Show(errorMessage); } return(false); } return(true); }
private IEnumerable <AzureSubscription> ListServiceManagementSubscriptions(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior, string[] tenants) { List <AzureSubscription> result = new List <AzureSubscription>(); if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement)) { return(result); } foreach (var tenant in tenants) { try { var tenantAccount = new AzureAccount(); CopyAccount(account, tenantAccount); var tenantToken = AzureSession.AuthenticationFactory.Authenticate(tenantAccount, environment, tenant, password, ShowDialog.Never); if (string.Equals(tenantAccount.Id, account.Id, StringComparison.InvariantCultureIgnoreCase)) { tenantAccount = account; } tenantAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, new string[] { tenant }); using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>( new TokenCloudCredentials(tenantToken.AccessToken), environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement))) { var subscriptionListResult = subscriptionClient.Subscriptions.List(); foreach (var subscription in subscriptionListResult.Subscriptions) { // only add the subscription if it's actually in this tenant if (subscription.ActiveDirectoryTenantId == tenant) { AzureSubscription psSubscription = new AzureSubscription { Id = new Guid(subscription.SubscriptionId), Name = subscription.SubscriptionName, Environment = environment.Name }; psSubscription.SetProperty(AzureSubscription.Property.Tenants, subscription.ActiveDirectoryTenantId); psSubscription.Account = tenantAccount.Id; tenantAccount.SetOrAppendProperty(AzureAccount.Property.Subscriptions, new string[] { psSubscription.Id.ToString() }); result.Add(psSubscription); } } } AddOrSetAccount(tenantAccount); } catch (CloudException cEx) { WriteOrThrowAadExceptionMessage(cEx); } catch (AadAuthenticationException aadEx) { WriteOrThrowAadExceptionMessage(aadEx); } } return(result); }
public void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode) { TestEnvironment currentEnvironment = null; if (mode == AzureModule.AzureResourceManager) { #if !NETSTANDARD currentEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment(); #else currentEnvironment = TestEnvironmentFactory.GetTestEnvironment(); #endif } else { #if !NETSTANDARD currentEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment(); #else throw new NotSupportedException("RDFE environment is not supported in .Net Core"); #endif } if (currentEnvironment.UserName == null) { currentEnvironment.UserName = "******"; } SetAuthenticationFactory(mode, currentEnvironment); AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName }; Debug.Assert(currentEnvironment != null); environment.ActiveDirectoryAuthority = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri; environment.GalleryUrl = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri; environment.ServiceManagementUrl = currentEnvironment.BaseUri.AbsoluteUri; environment.ResourceManagerUrl = currentEnvironment.Endpoints.ResourceManagementUri.AbsoluteUri; environment.GraphUrl = currentEnvironment.Endpoints.GraphUri.AbsoluteUri; environment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = currentEnvironment.Endpoints.DataLakeAnalyticsJobAndCatalogServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix environment.AzureDataLakeStoreFileSystemEndpointSuffix = currentEnvironment.Endpoints.DataLakeStoreServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix environment.StorageEndpointSuffix = AzureEnvironmentConstants.AzureStorageEndpointSuffix; #if !NETSTANDARD if (!ProfileClient.Profile.EnvironmentTable.ContainsKey(testEnvironmentName)) { ProfileClient.AddOrSetEnvironment(environment); } #endif if (!AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().EnvironmentTable.ContainsKey(testEnvironmentName)) { AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().EnvironmentTable[testEnvironmentName] = environment; } if (currentEnvironment.SubscriptionId != null) { testSubscription = new AzureSubscription() { Id = currentEnvironment.SubscriptionId, Name = testSubscriptionName, }; testSubscription.SetEnvironment(testEnvironmentName); testSubscription.SetAccount(currentEnvironment.UserName); testSubscription.SetDefault(); testSubscription.SetStorageAccount(Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")); testAccount = new AzureAccount() { Id = currentEnvironment.UserName, Type = AzureAccount.AccountType.User, }; testAccount.SetSubscriptions(currentEnvironment.SubscriptionId); #if !NETSTANDARD ProfileClient.Profile.SubscriptionTable[testSubscription.GetId()] = testSubscription; ProfileClient.Profile.AccountTable[testAccount.Id] = testAccount; ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.GetAccount()); #endif var testTenant = new AzureTenant() { Id = Guid.NewGuid().ToString() }; if (!string.IsNullOrEmpty(currentEnvironment.Tenant)) { Guid tenant; if (Guid.TryParse(currentEnvironment.Tenant, out tenant)) { testTenant.Id = currentEnvironment.Tenant; } } AzureRmProfileProvider.Instance.Profile.DefaultContext = new AzureContext(testSubscription, testAccount, environment, testTenant); } }
public AzureContext(AzureSubscription subscription, AzureAccount account, AzureEnvironment environment) { Subscription = subscription; Account = account; Environment = environment; }
/// <summary> /// Sets current session context. /// </summary> /// <param name="subscription"></param> /// <param name="environment"></param> /// <param name="account"></param> public static void SetCurrentContext(AzureSubscription subscription, AzureEnvironment environment, AzureAccount account) { if (environment == null) { if (subscription != null && CurrentContext != null && subscription.Environment == CurrentContext.Environment.Name) { environment = CurrentContext.Environment; } else { environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud]; } if (subscription != null) { subscription.Environment = environment.Name; } } if (account == null) { if (subscription != null && CurrentContext != null && subscription.Account != null) { if (CurrentContext.Account != null && subscription.Account == CurrentContext.Account.Id) { account = CurrentContext.Account; } else { throw new ArgumentException(Resources.AccountIdDoesntMatchSubscription, "account"); } subscription.Account = account.Id; } } if (subscription != null && subscription.Environment != environment.Name) { throw new ArgumentException(Resources.EnvironmentNameDoesntMatchSubscription, "environment"); } CurrentContext = new AzureContext { Subscription = subscription, Account = account, Environment = environment }; }
protected override void ExecuteAction(string ribbonId) { if (AudioSettingService.selectedVoiceType == VoiceType.AzureVoice && AzureAccount.GetInstance().IsEmpty()) { MessageBox.Show("Invalid user account. Please log in again."); return; } //TODO: This needs to improved to stop using global variables this.StartNewUndoEntry(); PowerPointSlide currentSlide = this.GetCurrentSlide(); // If there are text in notes page for any of the selected slides if (this.GetCurrentPresentation().SelectedSlides.Any(slide => slide.NotesPageText.Trim() != "")) { ComputerVoiceRuntimeService.IsRemoveAudioEnabled = true; this.GetRibbonUi().RefreshRibbonControl("RemoveNarrationsButton"); } try { ComputerVoiceRuntimeService.EmbedSelectedSlideNotes(); } catch { MessageBox.Show("Failed to generate audio files."); return; } CustomTaskPane recorderPane = this.GetAddIn().GetActivePane(typeof(RecorderTaskPane)); if (recorderPane == null) { return; } RecorderTaskPane recorder = recorderPane.Control as RecorderTaskPane; if (recorder == null) { return; } // initialize selected slides' audio List <string[]> allAudioFiles = ComputerVoiceRuntimeService.ExtractSlideNotes(); recorder.InitializeAudioAndScript(this.GetCurrentPresentation().SelectedSlides.ToList(), allAudioFiles, true); // if current list is visible, update the pane immediately if (recorderPane.Visible) { recorder.UpdateLists(currentSlide.ID); } if (AudioSettingService.IsPreviewEnabled) { ComputerVoiceRuntimeService.PreviewAnimations(); } }
public ApiAccessLogSaver() { var tableClient = AzureAccount.DefaultAccount().CreateCloudTableClient(); _tablePersister = new TablePersister <ApiAccessLogData>(tableClient); }
public void TestGetManageUrl() { NewAzureSqlDatabaseServerContext contextCmdlet = new NewAzureSqlDatabaseServerContext(); var profile = new AzureSMProfile(); var account = new AzureAccount { Id = "mockAccount", Type = AzureAccount.AccountType.User }; var subscription = new AzureSubscription { Id = Guid.NewGuid().ToString(), Name = "mockSubscription" }; subscription.SetAccount("mockAccount"); subscription.SetEnvironment(EnvironmentName.AzureCloud); profile.AccountTable.Add(account.Id, account); profile.SubscriptionTable.Add(subscription.GetId(), subscription); profile.DefaultSubscription = subscription; contextCmdlet.Profile = profile; // Make sure that server name to Manage Url conversion is working contextCmdlet.ServerName = "server0001"; Assert.AreEqual( new Uri("https://server0001.database.windows.net"), UnitTestHelper.InvokePrivate( contextCmdlet, "GetManageUrl", NewAzureSqlDatabaseServerContext.ServerNameWithSqlAuthParamSet)); // Make sure that fully qualified server name name to Manage Url conversion is working contextCmdlet.FullyQualifiedServerName = "server0003.database.windows.net"; Assert.AreEqual( new Uri("https://server0003.database.windows.net"), UnitTestHelper.InvokePrivate( contextCmdlet, "GetManageUrl", NewAzureSqlDatabaseServerContext.FullyQualifiedServerNameWithSqlAuthParamSet)); // Make sure that Manage Url to Manage Url conversion is working properly contextCmdlet.ManageUrl = new Uri("https://server0005.database.windows.net"); Assert.AreEqual( new Uri("https://server0005.database.windows.net"), UnitTestHelper.InvokePrivate( contextCmdlet, "GetManageUrl", NewAzureSqlDatabaseServerContext.ManageUrlWithSqlAuthParamSet)); // Make sure that server name to Manage Url conversion is working contextCmdlet.ServerName = "server0001"; Assert.AreEqual( new Uri("https://server0001.database.windows.net"), UnitTestHelper.InvokePrivate( contextCmdlet, "GetManageUrl", NewAzureSqlDatabaseServerContext.ServerNameWithCertAuthParamSet)); // Make sure that fully qualified server name name to Manage Url conversion is working contextCmdlet.FullyQualifiedServerName = "server0003.database.windows.net"; Assert.AreEqual( new Uri("https://server0003.database.windows.net"), UnitTestHelper.InvokePrivate( contextCmdlet, "GetManageUrl", NewAzureSqlDatabaseServerContext.FullyQualifiedServerNameWithCertAuthParamSet)); try { UnitTestHelper.InvokePrivate( contextCmdlet, "GetManageUrl", "InvalidParamterSet"); Assert.Fail("GetManageUrl with invalid parameter set should not succeed."); } catch (InvalidOperationException ex) { Assert.AreEqual(Resources.UnknownParameterSet, ex.Message); } }
/// <summary> /// Executes the set subscription cmdlet operation. /// </summary> public override void ExecuteCmdlet() { AzureSubscription subscription = null; if (!string.IsNullOrEmpty(SubscriptionId) && string.IsNullOrEmpty(SubscriptionName)) { subscription = ProfileClient.GetSubscription(new Guid(SubscriptionId)); Environment = subscription.Environment; } else if (string.IsNullOrEmpty(SubscriptionId) && !string.IsNullOrEmpty(SubscriptionName)) { subscription = ProfileClient.GetSubscription(SubscriptionName); Environment = subscription.Environment; } else { subscription = new AzureSubscription(); subscription.Id = new Guid(SubscriptionId); subscription.Name = SubscriptionName; } AzureEnvironment environment = ProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint); if (environment == null) { var profileClient = new ProfileClient(Profile); environment = profileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint); } if (environment == null) { throw new ArgumentException("ServiceEndpoint and ResourceManagerEndpoint values do not " + "match existing environment. Please use Environment parameter."); } else { subscription.Environment = environment.Name; } if (ServiceEndpoint != null || ResourceManagerEndpoint != null) { WriteWarning("Please use Environment parameter to specify subscription environment. This " + "warning will be converted into an error in the upcoming release."); } if (Certificate != null) { ProfileClient.ImportCertificate(Certificate); subscription.Account = Certificate.Thumbprint; AzureAccount account = new AzureAccount { Id = Certificate.Thumbprint, Type = AzureAccount.AccountType.Certificate }; account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString()); ProfileClient.AddOrSetAccount(account); if (subscription.Account == null) { subscription.Account = account.Id; } } if (subscription.Account == null) { throw new ArgumentException("Certificate is required for creating a new subscription."); } if (!string.IsNullOrEmpty(CurrentStorageAccountName)) { subscription.Properties[AzureSubscription.Property.StorageAccount] = CurrentStorageAccountName; } subscription = ProfileClient.AddOrSetSubscription(subscription); if (PassThru) { WriteObject(subscription); } }
public override void ExecuteCmdlet() { if (!string.IsNullOrWhiteSpace(SubscriptionId) && !string.IsNullOrWhiteSpace(SubscriptionName)) { throw new PSInvalidOperationException(Resources.BothSubscriptionIdAndNameProvided); } Guid subscrptionIdGuid; if (!string.IsNullOrWhiteSpace(SubscriptionId) && !Guid.TryParse(SubscriptionId, out subscrptionIdGuid)) { throw new PSInvalidOperationException( string.Format(Resources.InvalidSubscriptionId, SubscriptionId)); } AzureAccount azureAccount = new AzureAccount(); if (!string.IsNullOrEmpty(AccessToken)) { if (string.IsNullOrWhiteSpace(AccountId)) { throw new PSInvalidOperationException(Resources.AccountIdRequired); } azureAccount.Type = AzureAccount.AccountType.AccessToken; azureAccount.Id = AccountId; azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken); } else if (ServicePrincipal.IsPresent) { azureAccount.Type = AzureAccount.AccountType.ServicePrincipal; } else { azureAccount.Type = AzureAccount.AccountType.User; } if (!string.IsNullOrEmpty(CertificateThumbprint)) { azureAccount.SetProperty(AzureAccount.Property.CertificateThumbprint, CertificateThumbprint); } SecureString password = null; if (Credential != null) { azureAccount.Id = Credential.UserName; password = Credential.Password; } if (!string.IsNullOrEmpty(ApplicationId)) { azureAccount.Id = ApplicationId; } if (!string.IsNullOrEmpty(TenantId)) { azureAccount.SetProperty(AzureAccount.Property.Tenants, new[] { TenantId }); } if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in")) { if (AzureRmProfileProvider.Instance.Profile == null) { AzureRmProfileProvider.Instance.Profile = new AzureRmProfile(); } var profileClient = new RMProfileClient(AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>()); WriteObject((PSAzureProfile)profileClient.Login( azureAccount, _environment, TenantId, SubscriptionId, SubscriptionName, password, (s) => WriteWarning(s))); } }
public DenunciaPreciosSaver() { var tableClient = AzureAccount.DefaultAccount().CreateCloudTableClient(); _tablePersister = new TablePersister <DenunciaPreciosData>(tableClient); }
public override void ExecuteCmdlet() { Guid subscrptionIdGuid; string subscriptionName = null; string subscriptionId = null; if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription))) { if (Guid.TryParse(Subscription, out subscrptionIdGuid)) { subscriptionId = Subscription; } else { subscriptionName = Subscription; } } var azureAccount = new AzureAccount(); switch (ParameterSetName) { case AccessTokenParameterSet: azureAccount.Type = AzureAccount.AccountType.AccessToken; azureAccount.Id = AccountId; azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken); azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken); azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken); break; case ServicePrincipalCertificateParameterSet: case ServicePrincipalParameterSet: azureAccount.Type = AzureAccount.AccountType.ServicePrincipal; break; case ManagedServiceParameterSet: azureAccount.Type = AzureAccount.AccountType.ManagedService; var builder = new UriBuilder { Scheme = "http", Host = ManagedServiceHostName, Port = ManagedServicePort, Path = "/oauth2/token" }; var envSecret = System.Environment.GetEnvironmentVariable(MSISecretVariable); var msiSecret = this.IsBound(nameof(ManagedServiceSecret)) ? ManagedServiceSecret.ConvertToString() : envSecret; var envUri = System.Environment.GetEnvironmentVariable(MSIEndpointVariable); var suppliedUri = this.IsBound(nameof(ManagedServiceHostName)) ? builder.Uri.ToString() : envUri; if (!this.IsBound(nameof(ManagedServiceHostName)) && !string.IsNullOrWhiteSpace(envUri) && !this.IsBound(nameof(ManagedServiceSecret)) && !string.IsNullOrWhiteSpace(envSecret)) { // set flag indicating this is AppService Managed Identity ad hoc mode azureAccount.SetProperty(AuthenticationFactory.AppServiceManagedIdentityFlag, "the value not used"); } if (!string.IsNullOrWhiteSpace(msiSecret)) { azureAccount.SetProperty(AzureAccount.Property.MSILoginSecret, msiSecret); } if (!string.IsNullOrWhiteSpace(suppliedUri)) { azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, suppliedUri); } else { azureAccount.SetProperty(AzureAccount.Property.MSILoginUriBackup, builder.Uri.ToString()); azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, AuthenticationFactory.DefaultMSILoginUri); } azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : string.Format("MSI@{0}", ManagedServicePort); break; default: //Support username + password for both Windows PowerShell and PowerShell 6+ azureAccount.Type = AzureAccount.AccountType.User; break; } SecureString password = null; if (Credential != null) { azureAccount.Id = Credential.UserName; password = Credential.Password; } if (UseDeviceAuthentication.IsPresent) { azureAccount.SetProperty("UseDeviceAuth", "true"); } if (azureAccount.Type == AzureAccount.AccountType.User && password != null) { azureAccount.SetProperty(AzureAccount.Property.UsePasswordAuth, "true"); } if (!string.IsNullOrEmpty(ApplicationId)) { azureAccount.Id = ApplicationId; } if (!string.IsNullOrWhiteSpace(CertificateThumbprint)) { azureAccount.SetThumbprint(CertificateThumbprint); } if (!string.IsNullOrEmpty(Tenant)) { azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant); } if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && string.IsNullOrEmpty(CertificateThumbprint)) { azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString()); if (GetContextModificationScope() == ContextModificationScope.CurrentUser) { var file = AzureSession.Instance.ARMProfileFile; var directory = AzureSession.Instance.ARMProfileDirectory; WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory)); } } if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in")) { if (AzureRmProfileProvider.Instance.Profile == null) { InitializeProfileProvider(); } SetContextWithOverwritePrompt((localProfile, profileClient, name) => { bool shouldPopulateContextList = true; if (this.IsParameterBound(c => c.SkipContextPopulation)) { shouldPopulateContextList = false; } profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message))); var task = new Task <AzureRmProfile>(() => profileClient.Login( azureAccount, _environment, Tenant, subscriptionId, subscriptionName, password, SkipValidation, WriteWarning, name, shouldPopulateContextList, MaxContextPopulation)); task.Start(); while (!task.IsCompleted) { HandleActions(); Thread.Yield(); } HandleActions(); try { var result = (PSAzureProfile)(task.ConfigureAwait(false).GetAwaiter().GetResult()); WriteObject(result); } catch (AuthenticationFailedException ex) { if (IsUnableToOpenWebPageError(ex)) { WriteWarning(Resources.InteractiveAuthNotSupported); WriteDebug(ex.ToString()); } else { WriteWarning(Resources.SuggestToUseDeviceCodeAuth); WriteDebug(ex.ToString()); throw; } } }); } }
/// <summary> /// Initializes AzureSMProfile using passed in account and optional password. /// </summary> /// <param name="environment">Environment object.</param> /// <param name="subscriptionId">Subscription Id</param> /// <param name="account">Azure account with AD username and tenant.</param> /// <param name="password">AD password (optional).</param> /// <param name="storageAccount">Storage account name (optional).</param> /// <returns></returns> public void InitializeProfile(AzureEnvironment environment, Guid subscriptionId, AzureAccount account, SecureString password, string storageAccount) { if (environment == null) { throw new ArgumentNullException("environment"); } if (account == null) { throw new ArgumentNullException("account"); } // Add environment if not public if (!AzureEnvironment.PublicEnvironments.ContainsKey(environment.Name)) { AddOrSetEnvironment(environment); } // Add account var azureAccount = AddAccountAndLoadSubscriptions(account, environment, password); // Add subscription if (!azureAccount.HasSubscription(subscriptionId)) { throw new ArgumentException(string.Format(Resources.SubscriptionIdNotFoundMessage, subscriptionId)); } var azureSubscription = GetSubscription(subscriptionId); if (!string.IsNullOrEmpty(storageAccount)) { azureSubscription.Properties[AzureSubscription.Property.StorageAccount] = storageAccount; } AddOrSetSubscription(azureSubscription); }
public AzureRMProfile Login( AzureAccount account, AzureEnvironment environment, string tenantId, string subscriptionId, string subscriptionName, SecureString password) { AzureSubscription newSubscription = null; AzureTenant newTenant = null; ShowDialog promptBehavior = (password == null && account.Type != AzureAccount.AccountType.AccessToken && !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) ? ShowDialog.Always : ShowDialog.Never; // (tenant and subscription are present) OR // (tenant is present and subscription is not provided) if (!string.IsNullOrEmpty(tenantId)) { var token = AcquireAccessToken(account, environment, tenantId, password, promptBehavior); if (TryGetTenantSubscription(token, account, environment, tenantId, subscriptionId, subscriptionName, out newSubscription, out newTenant)) { account.SetProperty(AzureAccount.Property.Tenants, new[] { newTenant.Id.ToString() }); } } // (tenant is not provided and subscription is present) OR // (tenant is not provided and subscription is not provided) else { var tenants = ListAccountTenants(account, environment, password, promptBehavior).Select(s => s.Id.ToString()).ToArray(); account.SetProperty(AzureAccount.Property.Tenants, null); string accountId = null; for (int i = 0; i < tenants.Count(); i++) { var tenant = tenants[i]; AzureTenant tempTenant; AzureSubscription tempSubscription; IAccessToken token = null; try { token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto); if (accountId == null) { accountId = account.Id; account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant); } else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase)) { account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant); } else { // if account ID is different from the first tenant account id we need to ignore current tenant WriteWarningMessage(string.Format( Microsoft.Azure.Commands.Profile.Properties.Resources.AccountIdMismatch, account.Id, tenant, accountId)); account.Id = accountId; token = null; } } catch { WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, tenant)); } if (token != null && newTenant == null && TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant)) { newTenant = tempTenant; newSubscription = tempSubscription; } } } if (newSubscription == null) { if (subscriptionId != null) { throw new PSInvalidOperationException(String.Format(Properties.Resources.SubscriptionIdNotFound, account.Id, subscriptionId)); } else if (subscriptionName != null) { throw new PSInvalidOperationException(String.Format(Properties.Resources.SubscriptionNameNotFound, account.Id, subscriptionName)); } _profile.Context = new AzureContext(account, environment, newTenant); } else { _profile.Context = new AzureContext(newSubscription, account, environment, newTenant); } _profile.Context.TokenCache = TokenCache.DefaultShared.Serialize(); return(_profile); }
private void CopyAccount(AzureAccount sourceAccount, AzureAccount targetAccount) { targetAccount.Id = sourceAccount.Id; targetAccount.Type = sourceAccount.Type; }
public void SavingProfileWorks() { string expected = @"{ ""Environments"": { ""testCloud"": { ""Name"": ""testCloud"", ""OnPremise"": false, ""Endpoints"": { ""ActiveDirectory"": ""http://contoso.com"" } } }, ""Context"": { ""Account"": { ""Id"": ""*****@*****.**"", ""Type"": 1, ""Properties"": { ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"" } }, ""Subscription"": { ""Id"": ""00000000-0000-0000-0000-000000000000"", ""Name"": ""Contoso Test Subscription"", ""Environment"": ""testCloud"", ""Account"": ""*****@*****.**"", ""State"": ""Enabled"", ""Properties"": { ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"" } }, ""Environment"": { ""Name"": ""testCloud"", ""OnPremise"": false, ""Endpoints"": { ""ActiveDirectory"": ""http://contoso.com"" } }, ""Tenant"": { ""Id"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"", ""Domain"": ""contoso.com"" }, ""TokenCache"": ""AQIDBAUGCAkA"" } }"; var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile); var dataStore = new MockDataStore(); AzureSession.DataStore = dataStore; AzureRMProfile profile = new AzureRMProfile(path); var tenantId = new Guid("3c0ff8a7-e8bb-40e8-ae66-271343379af6"); var environment = new AzureEnvironment { Name = "testCloud", Endpoints = { { AzureEnvironment.Endpoint.ActiveDirectory, "http://contoso.com" } } }; var account = new AzureAccount { Id = "*****@*****.**", Type = AzureAccount.AccountType.User, Properties = { { AzureAccount.Property.Tenants, tenantId.ToString() } } }; var sub = new AzureSubscription { Account = account.Id, Environment = environment.Name, Id = new Guid(), Name = "Contoso Test Subscription", State = "Enabled", Properties = { { AzureSubscription.Property.Tenants, tenantId.ToString() } } }; var tenant = new AzureTenant { Id = tenantId, Domain = "contoso.com" }; profile.Context = new AzureContext(sub, account, environment, tenant); profile.Environments[environment.Name] = environment; profile.Context.TokenCache = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 }; profile.Save(); string actual = dataStore.ReadFileAsText(path); Assert.Equal(expected, actual); }