public IAccessToken Authenticate( IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Action <string> promptActionr, IAzureTokenCache tokenCache, string 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 as AzureEnvironment, tenant)); } }
public void RemoveUser(IAzureAccount account, IAzureTokenCache tokenCache) { TokenCache cache = tokenCache as TokenCache; if (cache != null && account != null && !string.IsNullOrEmpty(account.Id) && !string.IsNullOrWhiteSpace(account.Type)) { switch (account.Type) { case AzureAccount.AccountType.AccessToken: account.SetProperty(AzureAccount.Property.AccessToken, null); account.SetProperty(AzureAccount.Property.GraphAccessToken, null); account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, null); break; case AzureAccount.AccountType.ServicePrincipal: try { ServicePrincipalKeyStore.DeleteKey(account.Id, account.GetTenants().FirstOrDefault()); } catch { // make best effort to remove credentials } RemoveFromTokenCache(cache, account); break; case AzureAccount.AccountType.User: RemoveFromTokenCache(cache, account); break; } } }
private IAccessToken GetManagedServiceToken(IAzureAccount account, IAzureEnvironment environment, string tenant, string resourceId) { if (environment == null) { throw new InvalidOperationException("Environment is required for MSI Login"); } if (!account.IsPropertySet(AzureAccount.Property.MSILoginUri)) { account.SetProperty(AzureAccount.Property.MSILoginUri, DefaultMSILoginUri); } if (!account.IsPropertySet(AzureAccount.Property.MSILoginUriBackup)) { account.SetProperty(AzureAccount.Property.MSILoginUriBackup, DefaultBackupMSILoginUri); } if (string.IsNullOrWhiteSpace(tenant)) { tenant = environment.AdTenant ?? "Common"; } if (account.IsPropertySet(AuthenticationFactory.AppServiceManagedIdentityFlag)) { return(new ManagedServiceAppServiceAccessToken(account, environment, GetFunctionsResourceId(resourceId, environment), tenant)); } return(new ManagedServiceAccessToken(account, environment, GetResourceId(resourceId, environment), tenant)); }
private IAccessToken AcquireAccessToken( IAzureAccount account, IAzureEnvironment environment, string tenantId, SecureString password, string promptBehavior, Action <string> promptAction, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { if (account.Type == AzureAccount.AccountType.AccessToken) { tenantId = tenantId ?? account.GetCommonTenant(); return(new SimpleAccessToken(account, tenantId)); } return(AzureSession.Instance.AuthenticationFactory.Authenticate( account, environment, tenantId, password, promptBehavior, promptAction, _cache, resourceId)); }
/// <summary> /// /// </summary> /// <param name="account"></param> /// <param name="environment"></param> /// <param name="tenant"></param> /// <param name="password"></param> /// <param name="promptBehavior"></param> /// <param name="promptAction"></param> /// <param name="tokenCache"></param> /// <param name="resourceId"></param> /// <returns></returns> public IAccessToken Authenticate( IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Action <string> promptAction, IAzureTokenCache tokenCache, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { IAccessToken token = null; PowerShellTokenCacheProvider tokenCacheProvider; if (!AzureSession.Instance.TryGetComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out tokenCacheProvider)) { throw new NullReferenceException(Resources.AuthenticationClientFactoryNotRegistered); } Task <IAccessToken> authToken; var processAuthenticator = Builder.Authenticator; var retries = 5; while (retries-- > 0) { try { while (processAuthenticator != null && processAuthenticator.TryAuthenticate(GetAuthenticationParameters(tokenCacheProvider, account, environment, tenant, password, promptBehavior, promptAction, tokenCache, resourceId), out authToken)) { token = authToken?.ConfigureAwait(true).GetAwaiter().GetResult(); if (token != null) { // token.UserId is null when getting tenant token in ADFS environment account.Id = token.UserId ?? account.Id; if (!string.IsNullOrEmpty(token.HomeAccountId)) { account.SetProperty(AzureAccount.Property.HomeAccountId, token.HomeAccountId); } break; } processAuthenticator = processAuthenticator.Next; } } catch (Exception e) { if (!IsTransientException(e) || retries == 0) { throw e; } TracingAdapter.Information(string.Format("[AuthenticationFactory] Exception caught when calling TryAuthenticate, retrying authentication - Exception message: '{0}'", e.Message)); continue; } break; } return(token); }
public ManagedServiceAccessToken(IAzureAccount account, IAzureEnvironment environment, string resourceId, string tenant = "Common") { if (account == null || string.IsNullOrEmpty(account.Id) || !account.IsPropertySet(AzureAccount.Property.MSILoginUri)) { throw new ArgumentNullException(nameof(account)); } if (string.IsNullOrWhiteSpace(tenant)) { throw new ArgumentNullException(nameof(tenant)); } if (environment == null) { throw new ArgumentNullException(nameof(environment)); } _account = account; _resourceId = GetResource(resourceId, environment); var baseUri = _account.GetProperty(AzureAccount.Property.MSILoginUri); var builder = new UriBuilder(baseUri); builder.Query = string.Format("resource={0}", Uri.EscapeDataString(_resourceId)); _requestUri = builder.Uri.ToString(); _tenant = tenant; IHttpOperationsFactory factory; if (!AzureSession.Instance.TryGetComponent(HttpClientOperationsFactory.Name, out factory)) { factory = HttpClientOperationsFactory.Create(); } _tokenGetter = factory.GetHttpOperations <ManagedServiceTokenInfo>().WithHeader("Metadata", new[] { "true" }); }
public static AzureSubscription ToAzureSubscription(this Subscription other, IAzureAccount account, IAzureEnvironment environment, string retrievedByTenant) { var subscription = new AzureSubscription() { Id = other.SubscriptionId, Name = other.DisplayName, State = other.State?.ToSerializedValue() }; subscription.SetAccount(account?.Id); subscription.SetEnvironment(environment != null ? environment.Name : EnvironmentName.AzureCloud); subscription.SetHomeTenant(other.TenantId ?? retrievedByTenant); subscription.SetTenant(retrievedByTenant); subscription.SetSubscriptionPolicies(JsonConvert.SerializeObject(other.SubscriptionPolicies)); if (!string.IsNullOrEmpty(other.AuthorizationSource)) { subscription.SetOrAppendProperty(AzureSubscription.Property.AuthorizationSource, other.AuthorizationSource); } if (other.ManagedByTenants != null && other.ManagedByTenants.Any()) { subscription.SetManagedByTenants(other.ManagedByTenants.Select(t => t.TenantId).ToArray()); } if (other.Tags != null && other.Tags.Any()) { subscription.SetOrAppendProperty(AzureSubscription.Property.Tags, JsonConvert.SerializeObject(other.Tags)); } return(subscription); }
private IEnumerable <AzureSubscription> ListAllSubscriptionsForTenant( string tenantId) { IAzureAccount account = _profile.DefaultContext.Account; IAzureEnvironment environment = _profile.DefaultContext.Environment; SecureString password = null; string promptBehavior = ShowDialog.Never; IAccessToken accessToken = null; try { accessToken = AcquireAccessToken(account, environment, tenantId, password, promptBehavior, null); } catch { // Unable to acquire token for tenant return(new List <AzureSubscription>()); } SubscriptionClient subscriptionClient = null; subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>( environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), new TokenCredentials(accessToken.AccessToken) as ServiceClientCredentials, AzureSession.Instance.ClientFactory.GetCustomHandlers()); AzureContext context = new AzureContext(_profile.DefaultContext.Subscription, account, environment, CreateTenantFromString(tenantId, accessToken.TenantId)); return(subscriptionClient.ListAllSubscriptions().Select(s => s.ToAzureSubscription(context.Account, context.Environment, accessToken.TenantId))); }
private static IEnumerable <AzureSubscription> ListAllSubscriptionsForTenant( IAzureContext defaultContext, string tenantId) { IAzureAccount account = defaultContext.Account; IAzureEnvironment environment = defaultContext.Environment; IAccessToken accessToken = null; try { accessToken = AcquireAccessToken(account, environment, tenantId); } catch (Exception e) { throw new AadAuthenticationFailedException("Could not find subscriptions", e); } SubscriptionClient subscriptionClient = null; subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>( environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), new TokenCredentials(accessToken.AccessToken) as ServiceClientCredentials, AzureSession.Instance.ClientFactory.GetCustomHandlers()); AzureContext context = new AzureContext(defaultContext.Subscription, account, environment, CreateTenantFromString(tenantId, accessToken.TenantId)); return(subscriptionClient.ListAllSubscriptions().Select(s => ToAzureSubscription(s, context))); }
public void LoginWithUsernameAndPassword() { _account = new AzureAccount() { Type = AzureAccount.AccountType.User }; Login(); }
/// <summary> /// Check if this account equals another account /// </summary> /// <param name="baseAccount">The base account for comparison</param> /// <param name="other">The accoutn to compare to</param> /// <returns>true if the elements of both accounts are equal, otherwise false</returns> public static bool IsEqual(this IAzureAccount baseAccount, IAzureAccount other) { return((baseAccount == null && other == null) || (baseAccount.CheckExtensionsEqual(other) && string.Equals(baseAccount.Credential, other.Credential, StringComparison.OrdinalIgnoreCase) && string.Equals(baseAccount.Id, other.Id, StringComparison.OrdinalIgnoreCase) && string.Equals(baseAccount.Type, other.Type, StringComparison.OrdinalIgnoreCase) && CheckEquality(baseAccount.TenantMap, other.TenantMap))); }
private AuthenticationParameters GetAuthenticationParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Action <string> promptAction, IAzureTokenCache tokenCache, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { switch (account.Type) { case AzureAccount.AccountType.User: if (password == null) { var homeAccountId = account.GetProperty(AzureAccount.Property.HomeAccountId) ?? ""; if (!string.IsNullOrEmpty(account.Id)) { return(new SilentParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId)); } if (account.IsPropertySet("UseDeviceAuth")) { return(new DeviceCodeParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId)); } else if (account.IsPropertySet(AzureAccount.Property.UsePasswordAuth)) { return(new UsernamePasswordParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, password, homeAccountId)); } return(new InteractiveParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId, promptAction)); } return(new UsernamePasswordParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, password, null)); case AzureAccount.AccountType.Certificate: case AzureAccount.AccountType.ServicePrincipal: bool?sendCertificateChain = null; var sendCertificateChainStr = account.GetProperty("sendCertificateChain"); if (!string.IsNullOrWhiteSpace(sendCertificateChainStr)) { sendCertificateChain = Boolean.Parse(sendCertificateChainStr); } password = password ?? ConvertToSecureString(account.GetProperty(AzureAccount.Property.ServicePrincipalSecret)); return(new ServicePrincipalParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, account.GetProperty(AzureAccount.Property.CertificateThumbprint), password, sendCertificateChain)); case AzureAccount.AccountType.ManagedService: return(new ManagedServiceIdentityParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account)); case AzureAccount.AccountType.AccessToken: return(new AccessTokenParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account)); default: return(null); } }
/// <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> /// <param name="tenant">The azure tenant object</param> public AzureContext(IAzureSubscription subscription, IAzureAccount account, IAzureEnvironment environment, IAzureTenant tenant, byte[] tokens) { Subscription = subscription; Account = account; Environment = environment; Tenant = tenant; TokenCache = new AzureTokenCache(); TokenCache.CacheData = tokens; }
public IAccessToken Authenticate( IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { return(Authenticate(account, environment, tenant, password, promptBehavior, AzureSession.Instance.TokenCache, resourceId)); }
public ManagedServiceIdentityParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureEnvironment environment, IAzureTokenCache tokenCache, string tenantId, string resourceId, IAzureAccount account) : base(tokenCacheProvider, environment, tokenCache, tenantId, resourceId) { Account = account; }
internal static IAccessToken AcquireAccessToken(IAzureAccount account, IAzureEnvironment environment, string tenantId) { return(AzureSession.Instance.AuthenticationFactory.Authenticate( account, environment, tenantId, null, ShowDialog.Never, null)); }
private List <AzureTenant> ListAccountTenants( IAzureAccount account, IAzureEnvironment environment, SecureString password, string promptBehavior, Action <string> promptAction) { IList <AzureTenant> result = new List <AzureTenant>(); var commonTenant = account.GetCommonTenant(); try { var commonTenantToken = AcquireAccessToken( account, environment, commonTenant, password, promptBehavior, promptAction); result = SubscriptionAndTenantClient?.ListAccountTenants(commonTenantToken, environment); } catch { WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, commonTenant)); 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 = ti; tenant.Directory = AccessTokenExtensions.GetDomain(account.Id); } else { tenant.Directory = ti; } return(tenant); }).ToList(); } if (!result.Any()) { throw; } } return(result.ToList()); }
private IEnumerable <IAzureSubscription> ListServiceManagementSubscriptions(IAzureAccount account, IAzureEnvironment environment, SecureString password, string promptBehavior, string[] tenants) { List <AzureSubscription> result = new List <AzureSubscription>(); if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement)) { return(result); } foreach (var tenant in tenants) { try { IAzureAccount tenantAccount = new AzureAccount(); CopyAccount(account, tenantAccount); var tenantToken = AzureSession.Instance.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.Instance.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(); 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); }
private string GetEndpointToken(IAzureAccount account, string targetEndpoint) { string tokenKey = AzureAccount.Property.AccessToken; if (targetEndpoint == AzureEnvironment.Endpoint.Graph) { tokenKey = AzureAccount.Property.GraphAccessToken; } return(account.GetProperty(tokenKey)); }
public override Task <IAccessToken> Authenticate(IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Task <Action <string> > promptAction, IAzureTokenCache tokenCache, string resourceId) { var audience = environment.GetEndpoint(resourceId); var context = new AuthenticationContext( AuthenticationHelpers.GetAuthority(environment, tenant), environment?.OnPremise ?? true, tokenCache as TokenCache ?? TokenCache.DefaultShared); var result = context.AcquireTokenAsync(audience, AuthenticationHelpers.PowerShellClientId, new UserPasswordCredential(account.Id, password)); return(AuthenticationResultToken.GetAccessTokenAsync(result)); }
private void RemoveFromTokenCache(TokenCache cache, IAzureAccount account) { if (cache != null && cache.Count > 0 && account != null && !string.IsNullOrWhiteSpace(account.Id) && !string.IsNullOrWhiteSpace(account.Type)) { var items = cache.ReadItems().Where((i) => MatchCacheItem(account, i)); foreach (var item in items) { cache.DeleteItem(item); } } }
private IEnumerable <IAzureSubscription> ListSubscriptionsFromServer(IAzureAccount account, IAzureEnvironment environment, SecureString password, string promptBehavior) { string[] tenants = null; try { if (!account.IsPropertySet(AzureAccount.Property.Tenants)) { tenants = LoadAccountTenants(account, environment, password, promptBehavior); } else { var storedTenants = account.GetPropertyAsArray(AzureAccount.Property.Tenants); if (account.Type == AzureAccount.AccountType.User && storedTenants.Count() == 1) { TracingAdapter.Information(Resources.AuthenticatingForSingleTenant, account.Id, storedTenants[0]); AzureSession.Instance.AuthenticationFactory.Authenticate(account, environment, storedTenants[0], password, promptBehavior); } } } catch (AadAuthenticationException aadEx) { WriteOrThrowAadExceptionMessage(aadEx); return(new AzureSubscription[0]); } try { tenants = tenants ?? account.GetTenants(); List <IAzureSubscription> rdfeSubscriptions = ListServiceManagementSubscriptions(account, environment, password, ShowDialog.Never, tenants).ToList(); // Set user ID foreach (var subscription in rdfeSubscriptions) { account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString()); } if (rdfeSubscriptions.Any()) { return(rdfeSubscriptions); } else { return(new AzureSubscription[0]); } } catch (AadAuthenticationException aadEx) { WriteOrThrowAadExceptionMessage(aadEx); return(new AzureSubscription[0]); } }
public void LoginWithServicePrincipal() { // REQUIRED: // _tenantId --> Id of the tenant that the service princinpal is registered to // _userName --> Application id of the service principal // _password --> Secret of the service principal _account = new AzureAccount() { Type = AzureAccount.AccountType.ServicePrincipal }; Login(); }
public void LoginWithCertificate() { // REQUIRED: // _tenantId --> Id of the tenant that the service principal is registered to // _applicationId --> Application id of the service principal // _certificateThumbprint --> Thumbprint of the certificate used to authenticate the service principal _account = new AzureAccount() { Type = AzureAccount.AccountType.ServicePrincipal }; Login(); }
protected override IEnumerable <string> BuildTokenUri(string baseUri, IAzureAccount account, IdentityType identityType, string resourceId) { StringBuilder query = new StringBuilder($"{baseUri}?resource={resourceId}&api-version=2017-09-01"); if (identityType == IdentityType.ClientId || identityType == IdentityType.ObjectId) { query.Append($"&clientid={Uri.EscapeDataString(account.Id)}"); } yield return(query.ToString()); }
/// <summary> /// Determine if the given account has access to the given subscription /// </summary> /// <param name="account">The account to look in</param> /// <param name="subscriptionId">The subscription to check for</param> /// <returns>True if the account has access to the subscription, otherwise false</returns> public static bool HasSubscription(this IAzureAccount account, Guid subscriptionId) { bool exists = false; var subscriptions = account.GetPropertyAsArray(AzureAccount.Property.Subscriptions); if (subscriptions != null && subscriptions.Length > 0) { exists = subscriptions.Contains(subscriptionId.ToString(), StringComparer.OrdinalIgnoreCase); } return(exists); }
public static IAzureContext WithAccount(this IAzureContext context, IAzureAccount account) { if (account != null && !string.IsNullOrWhiteSpace(account.Id) && context != null) { context.Subscription?.SetAccount(account.Id); account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, context.Subscription == null ? null : context.Subscription.Id); account.SetOrAppendProperty(AzureAccount.Property.Tenants, context.Tenant == null ? null : context.Tenant.Id); context.Account = account; } return(context); }
public static PSAzureAccount ToPSAzureAccount(this IAzureAccount account) { string subscriptionsList = account.GetProperty(AzureAccount.Property.Subscriptions); string tenantsList = account.GetProperty(AzureAccount.Property.Tenants); return(new PSAzureAccount { Id = account.Id, Type = account.Type, Subscriptions = subscriptionsList == null ? "" : subscriptionsList.Replace(",", "\r\n"), Tenants = tenantsList == null ? null : new List <string>(tenantsList.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)) }); }
/// <summary> /// Update non-null non-identity account properties from the given account /// </summary> /// <param name="account">The account to copy to (target)</param> /// <param name="other">The account to copy from (source)</param> public static void Update(this IAzureAccount account, IAzureAccount source) { if (account != null && source != null) { account.Credential = source.Credential ?? account.Credential; foreach (var item in source.TenantMap) { account.TenantMap[item.Key] = item.Value; } account.UpdateProperties(source); } }
private string GetEndpointToken(IAzureAccount account, string targetEndpoint) { string tokenKey = AzureAccount.Property.AccessToken; if (string.Equals(targetEndpoint, AzureEnvironment.Endpoint.Graph, StringComparison.OrdinalIgnoreCase)) { tokenKey = AzureAccount.Property.GraphAccessToken; } if (string.Equals(targetEndpoint, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase)) { tokenKey = AzureAccount.Property.KeyVaultAccessToken; } return(account.GetProperty(tokenKey)); }