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, tenant));
            }

            return(new ManagedServiceAccessToken(account, environment, GetResourceId(resourceId, environment), tenant));
        }
        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(AzureAccount.Property.SendCertificateChain);
                if (!string.IsNullOrWhiteSpace(sendCertificateChainStr))
                {
                    sendCertificateChain = Boolean.Parse(sendCertificateChainStr);
                }
                password = password ?? ConvertToSecureString(account.GetProperty(AzureAccount.Property.ServicePrincipalSecret));
                var certificatePassword = ConvertToSecureString(account.GetProperty(AzureAccount.Property.CertificatePassword));
                return(new ServicePrincipalParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, account.GetProperty(AzureAccount.Property.CertificateThumbprint), account.GetProperty(AzureAccount.Property.CertificatePath),
                                                      certificatePassword, 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);
            }
        }
        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 idType = GetIdentityType(account);

            foreach (var uri in BuildTokenUri(_account.GetProperty(AzureAccount.Property.MSILoginUri), account, idType, _resourceId))
            {
                RequestUris.Enqueue(uri);
            }

            if (account.IsPropertySet(AzureAccount.Property.MSILoginUriBackup))
            {
                foreach (var uri in BuildTokenUri(_account.GetProperty(AzureAccount.Property.MSILoginUriBackup), account, idType, _resourceId))
                {
                    RequestUris.Enqueue(uri);
                }
            }

            _tenant = tenant;
            IHttpOperationsFactory factory;

            if (!AzureSession.Instance.TryGetComponent(HttpClientOperationsFactory.Name, out factory))
            {
                factory = HttpClientOperationsFactory.Create();
            }

            _tokenGetter = factory.GetHttpOperations <ManagedServiceTokenInfo>(true).WithHeader("Metadata", new[] { "true" });
            if (account.IsPropertySet(AzureAccount.Property.MSILoginSecret))
            {
                _tokenGetter = _tokenGetter.WithHeader("Secret", new[] { account.GetProperty(AzureAccount.Property.MSILoginSecret) });
            }
        }
예제 #4
0
        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" });
        }
예제 #5
0
        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());
        }
예제 #6
0
        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]);
            }
        }
        /// <summary>
        /// Get the common tenant from account
        /// </summary>
        /// <param name="account">The account to get tenant from</param>
        public static string GetCommonTenant(this IAzureAccount account)
        {
            string result = "organizations";

            if (account.IsPropertySet(AzureAccount.Property.Tenants))
            {
                var candidate = account.GetTenants().FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(candidate))
                {
                    result = candidate;
                }
            }

            return(result);
        }
예제 #8
0
        private static string GetCommonTenant(IAzureAccount account)
        {
            string result = AzureEnvironmentConstants.CommonAdTenant;

            if (account.IsPropertySet(AzureAccount.Property.Tenants))
            {
                var candidate = account.GetTenants().FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(candidate))
                {
                    result = candidate;
                }
            }

            return(result);
        }
        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;
            var          cache = tokenCache as TokenCache;

            if (cache == null)
            {
                cache = TokenCache.DefaultShared;
            }

            var configuration = GetAdalConfiguration(environment, tenant, resourceId, cache);

            TracingAdapter.Information(
                Resources.AdalAuthConfigurationTrace,
                configuration.AdDomain,
                configuration.AdEndpoint,
                configuration.ClientId,
                configuration.ClientRedirectUri,
                configuration.ResourceClientUri,
                configuration.ValidateAuthority);
            if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
            {
                var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint);
#if !NETSTANDARD
                token = TokenProvider.GetAccessTokenWithCertificate(configuration, account.Id, thumbprint, account.Type);
#else
                throw new NotSupportedException("Certificate based authentication is not supported in netcore version.");
#endif
            }
            else
            {
                token = TokenProvider.GetAccessToken(configuration, promptBehavior, promptAction, account.Id, password, account.Type);
            }

            account.Id = token.UserId;
            return(token);
        }
예제 #10
0
 /// <summary>
 /// Create a new access token from the given account and tenant id
 /// </summary>
 /// <param name="account">The account, containing user id, access token information</param>
 /// <param name="tenantId">The tenant id for the given access token</param>
 /// <param name="tokenType">The token type for the given token.</param>
 public SimpleAccessToken(IAzureAccount account, string tenantId, string tokenType = _defaultTokenType)
 {
     if (account == null)
     {
         throw new ArgumentNullException("account");
     }
     if (string.IsNullOrWhiteSpace(account.Id))
     {
         throw new ArgumentOutOfRangeException("account", Resources.AccessTokenRequiresAccount);
     }
     if (account.Type != AzureAccount.AccountType.AccessToken ||
         !account.IsPropertySet(AzureAccount.Property.AccessToken))
     {
         throw new ArgumentException(Resources.TypeNotAccessToken);
     }
     this.UserId      = account.Id;
     this._tokenType  = tokenType;
     this.AccessToken = account.GetProperty(AzureAccount.Property.AccessToken);
     this.TenantId    = tenantId;
 }
예제 #11
0
 public SimpleAccessToken(IAzureAccount account, string tenantId, string tokenType = _defaultTokenType)
 {
     if (account == null)
     {
         throw new ArgumentNullException("account");
     }
     if (string.IsNullOrWhiteSpace(account.Id))
     {
         throw new ArgumentOutOfRangeException("account", "AccountId must be provided to use an AccessToken credential.");
     }
     if (account.Type != AzureAccount.AccountType.AccessToken ||
         !account.IsPropertySet(AzureAccount.Property.AccessToken))
     {
         throw new ArgumentException("To create an access token credential, you must provide an access token account.");
     }
     this.UserId      = account.Id;
     this._tokenType  = tokenType;
     this.AccessToken = account.GetProperty(AzureAccount.Property.AccessToken);
     this.TenantId    = tenantId;
 }
예제 #12
0
        private IAzureAccount MergeAccountProperties(IAzureAccount account1, IAzureAccount account2)
        {
            if (account1 == null || account2 == null)
            {
                throw new ArgumentNullException("account1");
            }
            if (!string.Equals(account1.Id, account2.Id, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Account Ids do not match.");
            }
            if (account1.Type != account2.Type)
            {
                throw new ArgumentException("Account1 types do not match.");
            }
            AzureAccount mergeAccount = new AzureAccount
            {
                Id   = account1.Id,
                Type = account1.Type
            };

            foreach (var property in account1.ExtendedProperties.Keys.Union(account2.ExtendedProperties.Keys))
            {
                mergeAccount.SetProperty(property, account1.IsPropertySet(property) ?
                                         account1.GetProperty(property) : account2.GetProperty(property));
            }


            // Merge Tenants
            var tenants = account1.GetPropertyAsArray(AzureAccount.Property.Tenants)
                          .Union(account2.GetPropertyAsArray(AzureAccount.Property.Tenants), StringComparer.CurrentCultureIgnoreCase);

            mergeAccount.SetProperty(AzureAccount.Property.Tenants, tenants.ToArray());

            // Merge Subscriptions
            var subscriptions = account1.GetPropertyAsArray(AzureAccount.Property.Subscriptions)
                                .Union(account2.GetPropertyAsArray(AzureAccount.Property.Subscriptions), StringComparer.CurrentCultureIgnoreCase);

            mergeAccount.SetProperty(AzureAccount.Property.Subscriptions, subscriptions.ToArray());

            return(mergeAccount);
        }
        /// <summary>
        /// Get the list of subscriptions associated with the given account
        /// </summary>
        /// <param name="account">The account to look for</param>
        /// <param name="profile">The profile to search</param>
        /// <returns>A list of subscriptions available to the given account</returns>
        public static List <IAzureSubscription> GetSubscriptions(this IAzureAccount account, IAzureContextContainer profile)
        {
            string[] subscriptions = new string[0];
            List <IAzureSubscription> subscriptionsList = new List <IAzureSubscription>();

            if (account.IsPropertySet(AzureAccount.Property.Subscriptions))
            {
                subscriptions = account.GetSubscriptions();
            }

            foreach (var subscription in subscriptions)
            {
                var foundSubscription = profile.Subscriptions.FirstOrDefault((s) => string.Equals(s.Id, subscription, StringComparison.OrdinalIgnoreCase));
                if (foundSubscription != null)
                {
                    subscriptionsList.Add(foundSubscription);
                }
            }

            return(subscriptionsList);
        }
        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;
            var          cache = tokenCache as TokenCache;

            if (cache == null)
            {
                cache = TokenCache.DefaultShared;
            }

            var configuration = GetAdalConfiguration(environment, tenant, resourceId, cache);

            TracingAdapter.Information(
                Resources.AdalAuthConfigurationTrace,
                configuration.AdDomain,
                configuration.AdEndpoint,
                configuration.ClientId,
                configuration.ClientRedirectUri,
                configuration.ResourceClientUri,
                configuration.ValidateAuthority);
            if (account != null && account.Type == AzureAccount.AccountType.ManagedService)
            {
                token = GetManagedServiceToken(account, environment, tenant, resourceId);
            }
            else if (account != null && environment != null &&
                     account.Type == AzureAccount.AccountType.AccessToken)
            {
                var rawToken = new RawAccessToken
                {
                    TenantId  = tenant,
                    UserId    = account.Id,
                    LoginType = AzureAccount.AccountType.AccessToken
                };

                if ((string.Equals(resourceId, environment.AzureKeyVaultServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase) ||
                     string.Equals(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) &&
                    account.IsPropertySet(AzureAccount.Property.KeyVaultAccessToken))
                {
                    rawToken.AccessToken = account.GetProperty(AzureAccount.Property.KeyVaultAccessToken);
                }
                else if ((string.Equals(resourceId, environment.GraphEndpointResourceId, StringComparison.OrdinalIgnoreCase) ||
                          string.Equals(AzureEnvironment.Endpoint.GraphEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) &&
                         account.IsPropertySet(AzureAccount.Property.GraphAccessToken))
                {
                    rawToken.AccessToken = account.GetProperty(AzureAccount.Property.GraphAccessToken);
                }
                else if ((string.Equals(resourceId, environment.ActiveDirectoryServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase) ||
                          string.Equals(AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) &&
                         account.IsPropertySet(AzureAccount.Property.AccessToken))
                {
                    rawToken.AccessToken = account.GetAccessToken();
                }
                else
                {
                    throw new InvalidOperationException(string.Format(Resources.AccessTokenResourceNotFound, resourceId));
                }

                token = rawToken;
            }
            else if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
            {
                var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint);
#if !NETSTANDARD
                token = TokenProvider.GetAccessTokenWithCertificate(configuration, account.Id, thumbprint, account.Type);
#else
                throw new NotSupportedException("Certificate based authentication is not supported in netcore version.");
#endif
            }
            else
            {
                token = TokenProvider.GetAccessToken(configuration, promptBehavior, promptAction, account.Id, password, account.Type);
            }

            account.Id = token.UserId;
            return(token);
        }
예제 #15
0
        private List <AzureTenant> ListAccountTenants(
            IAzureAccount account,
            IAzureEnvironment environment,
            SecureString password,
            string promptBehavior,
            Action <string> promptAction)
        {
            List <AzureTenant> result = new List <AzureTenant>();
            var commonTenant          = GetCommonTenant(account);

            try
            {
                var commonTenantToken = AcquireAccessToken(
                    account,
                    environment,
                    commonTenant,
                    password,
                    promptBehavior,
                    promptAction);

                SubscriptionClient subscriptionClient = null;
                try
                {
                    subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>(
                        environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager),
                        new TokenCredentials(commonTenantToken.AccessToken) as ServiceClientCredentials,
                        AzureSession.Instance.ClientFactory.GetCustomHandlers());
                    //TODO: Fix subscription client to not require subscriptionId
                    result = account.MergeTenants(subscriptionClient.Tenants.List(), commonTenantToken);
                }
                finally
                {
                    // In test mode, we are reusing the client since disposing of it will
                    // fail some tests (due to HttpClient being null)
                    if (subscriptionClient != null && !TestMockSupport.RunningMocked)
                    {
                        subscriptionClient.Dispose();
                    }
                }
            }
            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);
        }
예제 #16
0
        public AzureRmProfile Login(
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            SecureString password,
            bool skipValidation,
            Action <string> promptAction,
            string name = null)
        {
            IAzureSubscription newSubscription = null;
            IAzureTenant       newTenant       = null;
            string             promptBehavior  =
                (password == null &&
                 account.Type != AzureAccount.AccountType.AccessToken &&
                 account.Type != AzureAccount.AccountType.ManagedService &&
                 !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
                ? ShowDialog.Always : ShowDialog.Never;

            if (skipValidation)
            {
                if (string.IsNullOrEmpty(subscriptionId) || string.IsNullOrEmpty(tenantId))
                {
                    throw new PSInvalidOperationException(Resources.SubscriptionOrTenantMissing);
                }

                newSubscription = new AzureSubscription
                {
                    Id = subscriptionId
                };

                newSubscription.SetOrAppendProperty(AzureSubscription.Property.Tenants, tenantId);
                newSubscription.SetOrAppendProperty(AzureSubscription.Property.Account, account.Id);

                newTenant = new AzureTenant
                {
                    Id = tenantId
                };
            }

            else
            {
                // (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,
                        promptAction);
                    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, promptAction)
                                  .Select(s => s.Id.ToString()).ToList();
                    account.SetProperty(AzureAccount.Property.Tenants, null);
                    string accountId = null;

                    foreach (var tenant in tenants)
                    {
                        IAzureTenant       tempTenant;
                        IAzureSubscription tempSubscription;

                        IAccessToken token = null;

                        try
                        {
                            token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto, null);
                            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(
                                                        ProfileMessages.AccountIdMismatch,
                                                        account.Id,
                                                        tenant,
                                                        accountId));
                                account.Id = accountId;
                                token      = null;
                            }
                        }
                        catch
                        {
                            WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant));
                        }

                        if (token != null &&
                            newTenant == null &&
                            TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant))
                        {
                            // If no subscription found for the given token/tenant
                            // discard tempTenant value unless current token/tenant is the last one.
                            if (tempSubscription != null || tenant.Equals(tenants[tenants.Count - 1]))
                            {
                                newTenant       = tempTenant;
                                newSubscription = tempSubscription;
                            }
                        }
                    }
                }
            }

            if (newSubscription == null)
            {
                if (subscriptionId != null)
                {
                    throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionIdNotFound, account.Id, subscriptionId));
                }
                else if (subscriptionName != null)
                {
                    throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionNameNotFound, account.Id, subscriptionName));
                }

                var newContext = new AzureContext(account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(name, newContext))
                {
                    WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString()));
                }
            }
            else
            {
                var newContext = new AzureContext(newSubscription, account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(name, newContext))
                {
                    WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString()));
                }

                if (!skipValidation && !newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase))
                {
                    WriteWarningMessage(string.Format(
                                            ProfileMessages.SelectedSubscriptionNotActive,
                                            newSubscription.State));
                }
            }

            _profile.DefaultContext.TokenCache = _cache;

            return(_profile.ToProfile());
        }
예제 #17
0
        public AzureRmProfile Login(
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            SecureString password,
            bool skipValidation,
            Action <string> promptAction,
            string name = null,
            bool shouldPopulateContextList = true,
            int maxContextPopulation       = Profile.ConnectAzureRmAccountCommand.DefaultMaxContextPopulation)
        {
            IAzureSubscription newSubscription = null;
            IAzureTenant       newTenant       = null;
            string             promptBehavior  =
                (password == null &&
                 account.Type != AzureAccount.AccountType.AccessToken &&
                 account.Type != AzureAccount.AccountType.ManagedService &&
                 !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
                ? ShowDialog.Always : ShowDialog.Never;

            SubscritpionClientCandidates.Reset();

            if (skipValidation)
            {
                if (string.IsNullOrEmpty(subscriptionId) || string.IsNullOrEmpty(tenantId))
                {
                    throw new PSInvalidOperationException(Resources.SubscriptionOrTenantMissing);
                }

                newSubscription = new AzureSubscription
                {
                    Id = subscriptionId
                };

                newSubscription.SetOrAppendProperty(AzureSubscription.Property.Tenants, tenantId);
                newSubscription.SetOrAppendProperty(AzureSubscription.Property.Account, account.Id);

                newTenant = new AzureTenant
                {
                    Id = tenantId
                };
            }
            else
            {
                // (tenant and subscription are present) OR
                // (tenant is present and subscription is not provided)
                if (!string.IsNullOrEmpty(tenantId))
                {
                    Guid tempGuid = Guid.Empty;
                    if (!Guid.TryParse(tenantId, out tempGuid))
                    {
                        var tenants     = ListAccountTenants(account, environment, password, promptBehavior, promptAction);
                        var homeTenants = tenants.FirstOrDefault(t => t.IsHome);
                        var tenant      = homeTenants ?? tenants.FirstOrDefault();
                        if (tenant == null || tenant.Id == null)
                        {
                            string baseMessage    = string.Format(ProfileMessages.TenantDomainNotFound, tenantId);
                            var    typeMessageMap = new Dictionary <string, string>
                            {
                                { AzureAccount.AccountType.ServicePrincipal, string.Format(ProfileMessages.ServicePrincipalTenantDomainNotFound, account.Id) },
                                { AzureAccount.AccountType.User, ProfileMessages.UserTenantDomainNotFound },
                                { AzureAccount.AccountType.ManagedService, ProfileMessages.MSITenantDomainNotFound }
                            };
                            string typeMessage = typeMessageMap.ContainsKey(account.Type) ? typeMessageMap[account.Type] : string.Empty;
                            throw new ArgumentNullException(string.Format("{0} {1}", baseMessage, typeMessage));
                        }

                        tenantId = tenant.Id;
                    }


                    var token = AcquireAccessToken(
                        account,
                        environment,
                        tenantId,
                        password,
                        promptBehavior,
                        promptAction);
                    if (TryGetTenantSubscription(
                            token,
                            account,
                            environment,
                            subscriptionId,
                            subscriptionName,
                            true,
                            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, promptAction)
                                  .Select(s => s.Id.ToString()).ToList();
                    account.SetProperty(AzureAccount.Property.Tenants, null);
                    string             accountId        = null;
                    IAzureTenant       tempTenant       = null;
                    IAzureSubscription tempSubscription = null;
                    foreach (var tenant in tenants)
                    {
                        tempTenant       = null;
                        tempSubscription = null;

                        IAccessToken token = null;

                        try
                        {
                            token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto, null);
                            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(
                                                        ProfileMessages.AccountIdMismatch,
                                                        account.Id,
                                                        tenant,
                                                        accountId));
                                account.Id = accountId;
                                token      = null;
                            }
                        }
                        catch
                        {
                            WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant));
                        }

                        if (token != null &&
                            newTenant == null &&
                            TryGetTenantSubscription(token, account, environment, subscriptionId, subscriptionName, false, out tempSubscription, out tempTenant))
                        {
                            // If no subscription found for the given token/tenant,discard tempTenant value.
                            // Continue to look for matched subscripitons until one subscription retrived by its home tenant is found.
                            if (tempSubscription != null)
                            {
                                newSubscription = tempSubscription;
                                if (tempSubscription.GetTenant() == tempSubscription.GetHomeTenant())
                                {
                                    newTenant = tempTenant;
                                }
                            }
                        }
                    }
                    newSubscription = newSubscription ?? tempSubscription;
                    newTenant       = newTenant ??
                                      (newSubscription != null ? new AzureTenant()
                    {
                        Id = newSubscription.GetTenant()
                    } : tempTenant);
                }
            }

            shouldPopulateContextList &= _profile.DefaultContext?.Account == null;
            if (newSubscription == null)
            {
                if (subscriptionId != null)
                {
                    throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionIdNotFound, account.Id, subscriptionId));
                }
                else if (subscriptionName != null)
                {
                    throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionNameNotFound, account.Id, subscriptionName));
                }

                var newContext = new AzureContext(account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(name, newContext))
                {
                    WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString()));
                }
            }
            else
            {
                var newContext = new AzureContext(newSubscription, account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(name, newContext))
                {
                    WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString()));
                }

                if (!skipValidation && !newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase))
                {
                    WriteWarningMessage(string.Format(
                                            ProfileMessages.SelectedSubscriptionNotActive,
                                            newSubscription.State));
                }
            }

            _profile.DefaultContext.TokenCache = _cache;
            if (shouldPopulateContextList && maxContextPopulation != 0)
            {
                var defaultContext = _profile.DefaultContext;
                var subscriptions  = maxContextPopulation > 0 ? ListSubscriptions(tenantId).Take(maxContextPopulation) : ListSubscriptions(tenantId);

                foreach (var subscription in subscriptions)
                {
                    IAzureTenant tempTenant = new AzureTenant()
                    {
                        Id = subscription.GetProperty(AzureSubscription.Property.Tenants)
                    };

                    var tempContext = new AzureContext(subscription, account, environment, tempTenant);
                    tempContext.TokenCache = _cache;
                    string tempName = null;
                    if (!_profile.TryGetContextName(tempContext, out tempName))
                    {
                        WriteWarningMessage(string.Format(Resources.CannotGetContextName, subscription.Id));
                        continue;
                    }

                    if (!_profile.TrySetContext(tempName, tempContext))
                    {
                        WriteWarningMessage(string.Format(Resources.CannotCreateContext, subscription.Id));
                    }
                }

                _profile.TrySetDefaultContext(defaultContext);
                _profile.TryRemoveContext("Default");
            }

            return(_profile.ToProfile());
        }
예제 #18
0
        private void Login(
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            SecureString password,
            Action <string> promptAction)
        {
            IAzureSubscription newSubscription = null;
            IAzureTenant       newTenant       = null;
            string             promptBehavior  =
                (password == null &&
                 account.Type != AzureAccount.AccountType.AccessToken &&
                 account.Type != AzureAccount.AccountType.ManagedService &&
                 !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))
            {
                Guid tempGuid = Guid.Empty;
                if (!Guid.TryParse(tenantId, out tempGuid))
                {
                    var tenant = ListAccountTenants(
                        account,
                        environment,
                        password,
                        promptBehavior,
                        promptAction)?.FirstOrDefault();
                    if (tenant == null || tenant.Id == null)
                    {
                        throw new ArgumentNullException(string.Format("Could not find tenant id for provided tenant domain '{0}'. Please ensure that " +
                                                                      "the provided service principal is found in the provided tenant domain.", tenantId));
                    }

                    tenantId = tenant.Id;
                }

                var token = AcquireAccessToken(
                    account,
                    environment,
                    tenantId,
                    password,
                    promptBehavior,
                    promptAction);
                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, promptAction)
                              .Select(s => s.Id.ToString()).ToList();
                account.SetProperty(AzureAccount.Property.Tenants, null);
                string accountId = null;

                foreach (var tenant in tenants)
                {
                    IAzureTenant       tempTenant;
                    IAzureSubscription tempSubscription;

                    IAccessToken token = null;

                    try
                    {
                        token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto, null);
                        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
                            account.Id = accountId;
                            token      = null;
                        }
                    }
                    catch
                    {
                        // Unable to acquire token for tenant
                    }

                    if (token != null &&
                        newTenant == null &&
                        TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant))
                    {
                        // If no subscription found for the given token/tenant
                        // discard tempTenant value unless current token/tenant is the last one.
                        if (tempSubscription != null || tenant.Equals(tenants[tenants.Count - 1]))
                        {
                            newTenant       = tempTenant;
                            newSubscription = tempSubscription;
                        }
                    }
                }
            }

            if (newSubscription == null)
            {
                if (subscriptionId != null)
                {
                    throw new PSInvalidOperationException(String.Format("The provided account {0} does not have access to subscription ID '{1}'. Please try logging in with different credentials or a different subscription ID.", account.Id, subscriptionId));
                }
                else if (subscriptionName != null)
                {
                    throw new PSInvalidOperationException(String.Format("The provided account {0} does not have access to subscription name '{1}'. Please try logging in with different credentials or a different subscription name.", account.Id, subscriptionName));
                }

                var newContext = new AzureContext(account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(null, newContext))
                {
                    // Unable to set default context
                }
            }
            else
            {
                var newContext = new AzureContext(newSubscription, account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(null, newContext))
                {
                    // Unable to set default context
                }

                if (!newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase))
                {
                    // Selected subscription is not in an "enabled" state
                }
            }

            _profile.DefaultContext.TokenCache = _cache;
            var defaultContext = _profile.DefaultContext;
            var subscriptions  = ListSubscriptions(tenantId).Take(25);

            foreach (var subscription in subscriptions)
            {
                IAzureTenant tempTenant = new AzureTenant()
                {
                    Id = subscription.GetTenant()
                };

                var tempContext = new AzureContext(subscription, account, environment, tempTenant);
                tempContext.TokenCache = _cache;
                string tempName = null;
                if (!_profile.TryGetContextName(tempContext, out tempName))
                {
                    // Unable to get context name for subscription
                    continue;
                }

                if (!_profile.TrySetContext(tempName, tempContext))
                {
                    // Cannot create a context for subscription
                }

                _profile.TrySetDefaultContext(defaultContext);
                _profile.TryRemoveContext("Default");
            }

            _profile.Dispose();
        }
 public override bool CanAuthenticate(IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Task <Action <string> > promptAction, IAzureTokenCache tokenCache, string resourceId)
 {
     return(account?.Type == AzureAccount.AccountType.User && environment != null && !string.IsNullOrWhiteSpace(tenant) && password == null && promptBehavior != ShowDialog.Never && tokenCache != null && account != null && !account.IsPropertySet("UseDeviceAuth"));
 }
예제 #20
0
        public AzureRmProfile Login(
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            SecureString password)
        {
            IAzureSubscription newSubscription = null;
            IAzureTenant       newTenant       = null;
            string             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];

                    IAzureTenant       tempTenant;
                    IAzureSubscription 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))
                    {
                        // If no subscription found for the given token/tenant
                        // discard tempTenant value unless current token/tenant is the last one.
                        if (tempSubscription != null || i == (tenants.Count() - 1))
                        {
                            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.DefaultContext = new AzureContext(account, environment, newTenant);
            }
            else
            {
                _profile.DefaultContext = new AzureContext(newSubscription, account, environment, newTenant);
                if (!newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase))
                {
                    WriteWarningMessage(string.Format(
                                            Microsoft.Azure.Commands.Profile.Properties.Resources.SelectedSubscriptionNotActive,
                                            newSubscription.State));
                }
            }

            _profile.DefaultContext.TokenCache = _cache;

            return(_profile);
        }