private Tuple<IAccessToken, string> GetToken(IAuthenticationFactory authFactory, AzureContext context, AzureEnvironment.Endpoint resourceIdEndpoint) { if (context.Account == null) throw new ArgumentException(KeyVaultProperties.Resources.ArmAccountNotFound); if (context.Account.Type != AzureAccount.AccountType.User && context.Account.Type != AzureAccount.AccountType.ServicePrincipal ) throw new ArgumentException(string.Format(KeyVaultProperties.Resources.UnsupportedAccountType, context.Account.Type)); if (context.Subscription != null && context.Account != null) TenantId = context.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants) .Intersect(context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants)) .FirstOrDefault(); if (string.IsNullOrWhiteSpace(TenantId) && context.Tenant != null && context.Tenant.Id != Guid.Empty) TenantId = context.Tenant.Id.ToString(); if (string.IsNullOrWhiteSpace(TenantId)) throw new ArgumentException(KeyVaultProperties.Resources.NoTenantInContext); try { var accesstoken = authFactory.Authenticate(context.Account, context.Environment, TenantId, null, ShowDialog.Auto, resourceIdEndpoint); return Tuple.Create(accesstoken, context.Environment.Endpoints[resourceIdEndpoint]); } catch (Exception ex) { throw new ArgumentException(KeyVaultProperties.Resources.InvalidSubscriptionState, ex); } }
public IAccessToken Authenticate( AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, TokenCache tokenCache, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { var configuration = GetAdalConfiguration(environment, tenant, resourceId, tokenCache); TracingAdapter.Information(Resources.AdalAuthConfigurationTrace, configuration.AdDomain, configuration.AdEndpoint, configuration.ClientId, configuration.ClientRedirectUri, configuration.ResourceClientUri, configuration.ValidateAuthority); IAccessToken token; if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) { var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint); token = TokenProvider.GetAccessTokenWithCertificate(configuration, account.Id, thumbprint, account.Type); } else { token = TokenProvider.GetAccessToken(configuration, promptBehavior, account.Id, password, account.Type); } account.Id = token.UserId; return token; }
public override void ExecuteCmdlet() { var newEnvironment = new AzureEnvironment { Name = Name, OnPremise = EnableADFSAuthentication }; newEnvironment.Endpoints[AzureEnvironment.Endpoint.PublishSettingsFileUrl] = PublishSettingsFileUrl; newEnvironment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = ServiceEndpoint; newEnvironment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = ResourceManagerEndpoint; newEnvironment.Endpoints[AzureEnvironment.Endpoint.ManagementPortalUrl] = ManagementPortalUrl; newEnvironment.Endpoints[AzureEnvironment.Endpoint.StorageEndpointSuffix] = StorageEndpoint; newEnvironment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = ActiveDirectoryEndpoint; newEnvironment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId] = ActiveDirectoryServiceEndpointResourceId; newEnvironment.Endpoints[AzureEnvironment.Endpoint.Gallery] = GalleryEndpoint; newEnvironment.Endpoints[AzureEnvironment.Endpoint.Graph] = GraphEndpoint; newEnvironment.Endpoints[AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix] = AzureKeyVaultDnsSuffix; newEnvironment.Endpoints[AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId] = AzureKeyVaultServiceEndpointResourceId; ProfileClient.AddOrSetEnvironment(newEnvironment); List<object> args = new List<object> { "Name", newEnvironment.Name }; foreach (AzureEnvironment.Endpoint property in Enum.GetValues(typeof(AzureEnvironment.Endpoint))) { args.AddRange(new object[] { property, newEnvironment.GetEndpoint(property) }); } WriteObject(base.ConstructPSObject(null, args.ToArray())); }
public IAccessToken Authenticate( AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, IdentityModel.Clients.ActiveDirectory.TokenCache tokenCache, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { if (account.Id == null) { account.Id = "test"; } if (TokenProvider == null) { return new MockAccessToken() { AccessToken = account.Id, LoginType = LoginType.OrgId, UserId = account.Id }; } else { return TokenProvider(account, environment, tenant); } }
public static IHDInsightSubscriptionCredentials GetSubscriptionCertificateCredentials(this IAzureHDInsightCommonCommandBase command, AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment) { return new HDInsightCertificateCredential { SubscriptionId = currentSubscription.Id, Certificate = AzureSession.DataStore.GetCertificate(currentSubscription.Account), Endpoint = environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement), }; }
public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { var configuration = GetAdalConfiguration(environment, tenant, resourceId); TracingAdapter.Information(Resources.AdalAuthConfigurationTrace, configuration.AdDomain, configuration.AdEndpoint, configuration.ClientId, configuration.ClientRedirectUri, configuration.ResourceClientUri, configuration.ValidateAuthority); var token = TokenProvider.GetAccessToken(configuration, promptBehavior, account.Id, password, account.Type); account.Id = token.UserId; return token; }
public IAccessToken Authenticate( AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { return Authenticate(account, environment, tenant, password, promptBehavior, AzureSession.TokenCache, resourceId); }
public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { if (account.Id == null) { account.Id = "test"; } return TokenProvider(account, environment, tenant); }
public DataServiceCredential(IAuthenticationFactory authFactory, AzureContext context, AzureEnvironment.Endpoint resourceIdEndpoint) { if (authFactory == null) throw new ArgumentNullException("authFactory"); if (context == null) throw new ArgumentNullException("context"); var bundle = GetToken(authFactory, context, resourceIdEndpoint); this.token = bundle.Item1; }
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) ? 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); TryGetTenantSubscription(token, account, environment, tenantId, subscriptionId, subscriptionName, out newSubscription, out newTenant); } // (tenant is not provided and subscription is present) OR // (tenant is not provided and subscription is not provided) else { foreach (var tenant in ListAccountTenants(account, environment, password, promptBehavior)) { AzureTenant tempTenant; AzureSubscription tempSubscription; var token = AcquireAccessToken(account, environment, tenant.Id.ToString(), password, ShowDialog.Auto); if (newTenant == null && TryGetTenantSubscription(token, account, environment, tenant.Id.ToString(), subscriptionId, subscriptionName, out tempSubscription, out tempTenant) && newTenant == null) { 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, subscriptionId)); } else { throw new PSInvalidOperationException(String.Format(Properties.Resources.NoSubscriptionFound, account.Id)); } } _profile.Context = new AzureContext(newSubscription, account, environment, newTenant); _profile.Context.TokenCache = TokenCache.DefaultShared.Serialize(); return _profile; }
public void ProfileSaveDoesNotSerializeContext() { var dataStore = new MockDataStore(); var currentProfile = new AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)); AzureSession.DataStore = dataStore; var client = new ProfileClient(currentProfile); var tenant = Guid.NewGuid().ToString(); 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, tenant } } }; var sub = new AzureSubscription { Account = account.Id, Environment = environment.Name, Id = new Guid(), Name = "Contoso Test Subscription", Properties = { { AzureSubscription.Property.Tenants, tenant } } }; client.AddOrSetEnvironment(environment); client.AddOrSetAccount(account); client.AddOrSetSubscription(sub); currentProfile.Save(); var profileFile = currentProfile.ProfilePath; string profileContents = dataStore.ReadFileAsText(profileFile); var readProfile = JsonConvert.DeserializeObject<Dictionary<string, object>>(profileContents); Assert.False(readProfile.ContainsKey("Context")); AzureProfile parsedProfile = new AzureProfile(); var serializer = new JsonProfileSerializer(); Assert.True(serializer.Deserialize(profileContents, parsedProfile)); Assert.NotNull(parsedProfile); Assert.NotNull(parsedProfile.Environments); Assert.True(parsedProfile.Environments.ContainsKey(environment.Name)); Assert.NotNull(parsedProfile.Accounts); Assert.True(parsedProfile.Accounts.ContainsKey(account.Id)); Assert.NotNull(parsedProfile.Subscriptions); Assert.True(parsedProfile.Subscriptions.ContainsKey(sub.Id)); }
public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { if (account.Id == null) { account.Id = "test"; } var token = new MockAccessToken { UserId = account.Id, LoginType = LoginType.OrgId, AccessToken = "123" }; return token; }
public static IHDInsightSubscriptionCredentials GetAccessTokenCredentials(this IAzureHDInsightCommonCommandBase command, AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment) { ProfileClient profileClient = new ProfileClient(new AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile))); AzureContext azureContext = new AzureContext(currentSubscription, azureAccount, environment); 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; }
public override void ExecuteCmdlet() { var newEnvironment = new AzureEnvironment { Name = Name }; if (ProfileClient.Profile.Environments.ContainsKey(Name)) { newEnvironment = ProfileClient.Profile.Environments[Name]; } SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.PublishSettingsFileUrl, PublishSettingsFileUrl); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ServiceManagement, ServiceEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ResourceManager, ResourceManagerEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ManagementPortalUrl, ManagementPortalUrl); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.StorageEndpointSuffix, StorageEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectory, ActiveDirectoryEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, ActiveDirectoryServiceEndpointResourceId); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Gallery, GalleryEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Graph, GraphEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix, AzureKeyVaultDnsSuffix); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, AzureKeyVaultServiceEndpointResourceId); ProfileClient.AddOrSetEnvironment(newEnvironment); WriteObject(newEnvironment); }
public static IHDInsightSubscriptionCredentials GetSubscriptionCredentials( this IAzureHDInsightCommonCommandBase command, AzureSubscription currentSubscription, AzureEnvironment environment, AzureProfile profile) { var accountId = currentSubscription.Account; Debug.Assert(profile.Accounts.ContainsKey(accountId)); if (profile.Accounts[accountId].Type == AzureAccount.AccountType.Certificate) { return GetSubscriptionCertificateCredentials(command, currentSubscription, profile.Accounts[accountId], environment); } else if (profile.Accounts[accountId].Type == AzureAccount.AccountType.User) { return GetAccessTokenCredentials(command, currentSubscription, profile.Accounts[accountId], environment); } else if (profile.Accounts[accountId].Type == AzureAccount.AccountType.ServicePrincipal) { return GetAccessTokenCredentials(command, currentSubscription, profile.Accounts[accountId], environment); } throw new NotSupportedException(); }
/// <summary> /// Initializes a new Azure environment from the given internal representation. /// </summary> /// <param name="environment">The internal representation of the environment.</param> public PSAzureEnvironment(AzureEnvironment environment) { Name = environment.Name; EnableAdfsAuthentication = environment.OnPremise; if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)) { ActiveDirectoryServiceEndpointResourceId = environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.AdTenant)) { AdTenant = environment.Endpoints[AzureEnvironment.Endpoint.AdTenant]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.Gallery)) { GalleryUrl = environment.Endpoints[AzureEnvironment.Endpoint.Gallery]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ManagementPortalUrl)) { ManagementPortalUrl = environment.Endpoints[AzureEnvironment.Endpoint.ManagementPortalUrl]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement)) { ServiceManagementUrl = environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.PublishSettingsFileUrl)) { PublishSettingsFileUrl = environment.Endpoints[AzureEnvironment.Endpoint.PublishSettingsFileUrl]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager)) { ResourceManagerUrl = environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix)) { SqlDatabaseDnsSuffix = environment.Endpoints[AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.StorageEndpointSuffix)) { StorageEndpointSuffix = environment.Endpoints[AzureEnvironment.Endpoint.StorageEndpointSuffix]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ActiveDirectory)) { ActiveDirectoryAuthority = environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.Graph)) { GraphUrl = environment.Endpoints[AzureEnvironment.Endpoint.Graph]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.TrafficManagerDnsSuffix)) { TrafficManagerDnsSuffix = environment.Endpoints[AzureEnvironment.Endpoint.TrafficManagerDnsSuffix]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix)) { AzureKeyVaultDnsSuffix = environment.Endpoints[AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix)) { AzureDataLakeStoreFileSystemEndpointSuffix = environment.Endpoints[AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix)) { AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = environment.Endpoints[AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix]; } if (environment.IsEndpointSet(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId)) { AzureKeyVaultServiceEndpointResourceId = environment.Endpoints[AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId]; } }
private IEnumerable<AzureSubscription> ListSubscriptionsForTenant(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior, string tenantId) { IAccessToken accessToken = null; try { accessToken = AcquireAccessToken(account, environment, tenantId, password, promptBehavior); } catch { WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, tenantId)); return new List<AzureSubscription>(); } using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<SubscriptionClient>( new TokenCloudCredentials(accessToken.AccessToken), environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager))) { var subscriptions = subscriptionClient.Subscriptions.List(); if (subscriptions != null && subscriptions.Subscriptions != null) { return subscriptions.Subscriptions.Select( (s) => s.ToAzureSubscription(new AzureContext(_profile.Context.Subscription, account, environment, CreateTenantFromString(tenantId, accessToken.TenantId)))); } return new List<AzureSubscription>(); } }
private List<AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior) { List<AzureTenant> result = new List<AzureTenant>(); try { var commonTenantToken = AcquireAccessToken(account, environment, AuthenticationFactory.CommonAdTenant, password, promptBehavior); using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<SubscriptionClient>( new TokenCloudCredentials(commonTenantToken.AccessToken), environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager))) { //TODO: Fix subscription client to not require subscriptionId result = account.MergeTenants(subscriptionClient.Tenants.List().TenantIds, commonTenantToken); } } catch { WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, AuthenticationFactory.CommonAdTenant)); if (account.IsPropertySet(AzureAccount.Property.Tenants)) { result = account.GetPropertyAsArray(AzureAccount.Property.Tenants) .Select( ti => { var tenant = new AzureTenant(); Guid guid; if(Guid.TryParse(ti, out guid)) { tenant.Id = guid; tenant.Domain = AccessTokenExtensions.GetDomain(account.Id); } else { tenant.Domain = ti; } return tenant; }).ToList(); } } return result; }
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.SetOrAppendProperty(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 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 ?? new List<Microsoft.Azure.Subscriptions.Models.Subscription>()) .Where(s => "enabled".Equals(s.State, StringComparison.OrdinalIgnoreCase) || "warned".Equals(s.State, StringComparison.OrdinalIgnoreCase)); if (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 active 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 IAccessToken AcquireAccessToken(AzureAccount account, AzureEnvironment environment, string tenantId, SecureString password, ShowDialog promptBehavior) { if (account.Type == AzureAccount.AccountType.AccessToken) { tenantId = tenantId ?? "Common"; return new SimpleAccessToken(account, tenantId); } return AzureSession.AuthenticationFactory.Authenticate( account, environment, tenantId, password, promptBehavior, TokenCache.DefaultShared); }
private AzureEnvironment MergeEnvironmentProperties(AzureEnvironment environment1, AzureEnvironment environment2) { if (environment1 == null || environment2 == null) { throw new ArgumentNullException("environment1"); } if (!string.Equals(environment1.Name, environment2.Name, StringComparison.InvariantCultureIgnoreCase)) { throw new ArgumentException("Environment names do not match."); } AzureEnvironment mergedEnvironment = new AzureEnvironment { Name = environment1.Name }; // Merge all properties foreach (AzureEnvironment.Endpoint property in Enum.GetValues(typeof(AzureEnvironment.Endpoint))) { string propertyValue = environment1.GetEndpoint(property) ?? environment2.GetEndpoint(property); if (propertyValue != null) { mergedEnvironment.Endpoints[property] = propertyValue; } } return mergedEnvironment; }
public AzureEnvironment AddOrSetEnvironment(AzureEnvironment environment) { if (environment == null) { throw new ArgumentNullException("environment", Resources.EnvironmentNeedsToBeSpecified); } if (AzureEnvironment.PublicEnvironments.ContainsKey(environment.Name)) { throw new InvalidOperationException( string.Format(Resources.ChangingDefaultEnvironmentNotSupported, "environment")); } if (_profile.Environments.ContainsKey(environment.Name)) { _profile.Environments[environment.Name] = MergeEnvironmentProperties(environment, _profile.Environments[environment.Name]); } else { _profile.Environments[environment.Name] = environment; } return _profile.Environments[environment.Name]; }
public string GetEndpointSuffix(AzureEnvironment.Endpoint endpointSuffix) { if (Endpoints.ContainsKey(endpointSuffix)) { return Endpoints[endpointSuffix]; } return null; }
public bool IsEndpointSet(AzureEnvironment.Endpoint endpoint) { return Endpoints.IsPropertySet(endpoint); }
/// <summary> /// Creates new instance of AzureContext. /// </summary> /// <param name="subscription">The azure subscription object</param> /// <param name="account">The azure account object</param> /// <param name="environment">The azure environment object</param> public AzureContext(AzureSubscription subscription, AzureAccount account, AzureEnvironment environment) : this(subscription, account, environment, null) { }
/// <summary> /// Creates new instance of AzureContext. /// </summary> /// <param name="account">The azure account object</param> /// <param name="environment">The azure environment object</param> /// <param name="tenant">The azure tenant object</param> public AzureContext(AzureAccount account, AzureEnvironment environment, AzureTenant tenant) : this(null, account, environment, tenant) { }
public override void ExecuteCmdlet() { if ((Name == "AzureCloud") || (Name == "AzureChinaCloud")) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotChangeBuiltinEnvironment, Name)); } var newEnvironment = new AzureEnvironment { Name = Name, OnPremise = EnableAdfsAuthentication }; if (ProfileClient.Profile.Environments.ContainsKey(Name)) { newEnvironment = ProfileClient.Profile.Environments[Name]; } SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.PublishSettingsFileUrl, PublishSettingsFileUrl); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ServiceManagement, ServiceEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ResourceManager, ResourceManagerEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ManagementPortalUrl, ManagementPortalUrl); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.StorageEndpointSuffix, StorageEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectory, ActiveDirectoryEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, ActiveDirectoryServiceEndpointResourceId); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Gallery, GalleryEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Graph, GraphEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix, AzureKeyVaultDnsSuffix); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, AzureKeyVaultServiceEndpointResourceId); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.TrafficManagerDnsSuffix, TrafficManagerDnsSuffix); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix, SqlDatabaseDnsSuffix); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AdTenant, AdTenant); ProfileClient.AddOrSetEnvironment(newEnvironment); WriteObject((PSAzureEnvironment)newEnvironment); }
public bool IsEndpointSetToValue(AzureEnvironment.Endpoint endpoint, string url) { if (url == null && !Endpoints.IsPropertySet(endpoint)) { return true; } if (url != null && Endpoints.IsPropertySet(endpoint)) { return GetEndpoint(endpoint) .Trim(new[] { '/' }) .Equals(url.Trim(new[] { '/' }), StringComparison.InvariantCultureIgnoreCase); } return false; }
private void SetMockData() { azureSubscription1 = new AzureSubscription { Id = new Guid("56E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"), Name = "LocalSub1", Environment = "Test", Account = "test", Properties = new Dictionary<AzureSubscription.Property, string> { { AzureSubscription.Property.Default, "True" } } }; azureSubscription2 = new AzureSubscription { Id = new Guid("66E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"), Name = "LocalSub2", Environment = "Test", Account = "test" }; azureEnvironment = new AzureEnvironment { Name = "Test", Endpoints = new Dictionary<AzureEnvironment.Endpoint, string> { { AzureEnvironment.Endpoint.ServiceManagement, "https://umapi.rdfetest.dnsdemo4.com:8443/" }, { AzureEnvironment.Endpoint.ManagementPortalUrl, "https://windows.azure-test.net" }, { AzureEnvironment.Endpoint.AdTenant, "https://login.windows-ppe.net/" }, { AzureEnvironment.Endpoint.ActiveDirectory, "https://login.windows-ppe.net/" }, { AzureEnvironment.Endpoint.Gallery, "https://current.gallery.azure-test.net" }, { AzureEnvironment.Endpoint.ResourceManager, "https://api-current.resources.windows-int.net/" }, { AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix, "vault-int.azure-int.net" }, { AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, "https://vault-int.azure-int.net/" }, } }; azureAccount = new AzureAccount { Id = "test", Type = AzureAccount.AccountType.User, Properties = new Dictionary<AzureAccount.Property, string> { { AzureAccount.Property.Subscriptions, azureSubscription1.Id + "," + azureSubscription2.Id } } }; }
private void SetEndpointIfProvided(AzureEnvironment newEnvironment, AzureEnvironment.Endpoint endpoint, string property) { if (!string.IsNullOrEmpty(property)) { newEnvironment.Endpoints[endpoint] = property; } }
static async Task MainAsync() { // Set Environment - Choose between Azure public cloud, china cloud and US govt. cloud _environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud]; // Get the credentials TokenCloudCredentials cloudCreds = GetCredsFromServicePrincipal(); var tokenCreds = new TokenCredentials(cloudCreds.Token); var loggingHandler = new LoggingHandler(new HttpClientHandler()); // Create our own HttpClient so we can do logging var httpClient = new HttpClient(loggingHandler); // Use the creds to create the clients we need _resourceGroupClient = new ResourceManagementClient(cloudCreds, _environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), httpClient); _websiteClient = new WebSiteManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds, loggingHandler); _websiteClient.SubscriptionId = cloudCreds.SubscriptionId; await ListResourceGroupsAndSites(); // Note: site names are globally unique, so you may need to change it to avoid conflicts await CreateSite("MyResourceGroup", "MyAppServicePlan", "SampleSiteFromAPI", "West US"); // Upload certificate to resource group await UpdateLoadCertificate("MyResourceGroup", "CertificateName", "West US", "PathToPfxFile", "CertificatePassword"); }