public IAccessToken Authenticate(ref AzureAccount account, AzureEnvironment environment, string tenant, SecureString password,
     ShowDialog promptBehavior)
 {
     var token = TokenProvider.GetAccessToken(GetAdalConfiguration(environment, tenant), 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,
            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 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 IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
     AzureAccount.AccountType credentialType)
 {
     if (credentialType == AzureAccount.AccountType.User)
     {
         throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType");
     }
     return new ServicePrincipalAccessToken(config, AcquireTokenWithSecret(config, userId, password), this.RenewWithSecret, userId);
 }
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            return TokenProvider(account, environment, tenant);
        }
 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 IEnumerable<IResult> ShowInputDialog() {
            var showDialog = new ShowDialog<DialogViewModel>();
            yield return showDialog;

            var result = showDialog.Dialog.Result;
            if(result != null) {
                yield return new ShowDialog<MessageViewModel>()
                    .ConfigureWith(x => x.Message = "The user entered: " + result);
            }
        }
Esempio n. 8
0
 private IEnumerator<IResult> IncomingCall()
 {
     var callDialog = new ShowDialog<IncomingCallDialogViewModel>().ConfigureWith(x => x.CallerID = CalleeID);
     yield return callDialog;
     if (callDialog.Dialog.Answered)
         navService.UriFor<ActiveCallPageViewModel>()
             .WithParam(x => x.calleeID, CalleeID)
             .WithParam(x => x.isIncoming, true)
             .Navigate();
 }
        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 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;
 }
Esempio n. 11
0
        public IEnumerable<IResult> ReportDueFungalResults()
        {
            var showCriteriaDialog = new ShowDialog<DateDialogViewModel>().ConfigureWith(x => { x.DisplayName = "Enter Result Read Date"; }, UILib.GetSettingsWithOutCloseOrResize());
            yield return showCriteriaDialog;
            var selectedDate = (DateTime?)showCriteriaDialog.Dialog.ReturnObject;

            if (selectedDate != null)
            {
                var reportParameters = new Dictionary<string, object> { { "reportDate", selectedDate } };
                Shell.Value.Dialogs.ShowDialog(new ReportViewModel("Fungal Results Due Report", "ReportDueFungalResults", reportParameters, true));
            }
        }
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
     AzureAccount.AccountType credentialType)
 {
     switch (credentialType)
     {
         case AzureAccount.AccountType.User:
             return userTokenProvider.GetAccessToken(config, promptBehavior, userId, password, credentialType);
         case AzureAccount.AccountType.ServicePrincipal:
             return servicePrincipalTokenProvider.GetAccessToken(config, promptBehavior, userId, password, credentialType);
         default:
             throw new ArgumentException(Resources.UnknownCredentialType, "credentialType");
     }
 }
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            var token = new MockAccessToken
            {
                UserId = account.Id,
                LoginType = LoginType.OrgId,
                AccessToken = "123"
            };

            return token;
        }
        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;
        }
Esempio n. 15
0
        //public static GlobalExceptionHandler(IEventAggregator eventAggregator)
        //{
        //    this.eventAggregator = eventAggregator;
        //}

        public static IEnumerable<IResult> HandleException(Exception ex)
        {
            var showDialog = new ShowDialog<ExceptionViewModel>();
            yield return showDialog;

            var sendException = showDialog.Dialog.SendException;
            if (sendException)
            {
                EmailComposeTask emailCompose = new EmailComposeTask();
                emailCompose.To = "*****@*****.**";
                emailCompose.Subject = ex.Message;

                string exceptionString = ex.ToString();
                for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
                    exceptionString = exceptionString + "\n\n" + "INNER EXCEPTION:\n" + ((object)innerException).ToString();

                string exceptionWithVersion = exceptionString + "APPLICATION VERSION: " + AppResources.ApplicationVersion;
                emailCompose.Body = exceptionWithVersion;
                emailCompose.Show();

                //yield return new ShowDialog<MessageViewModel>()
                //    .Init(x => x.Message = "The user entered: " + result);
            }
        }
        private IEnumerable<AzureSubscription> ListServiceManagementSubscriptions(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior, string[] tenants)
        {
            List<AzureSubscription> result = new List<AzureSubscription>();

            if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement))
            {
                return result;
            }

            foreach (var tenant in tenants)
            {
                try
                {
                    var tenantAccount = new AzureAccount();
                    CopyAccount(account, tenantAccount);
                    var tenantToken = AzureSession.AuthenticationFactory.Authenticate(tenantAccount, environment, tenant, password, ShowDialog.Never);
                    if (tenantAccount.Id == account.Id)
                    {
                        tenantAccount = account;
                    }

                    tenantAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, new string[] { tenant });
                    using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<WindowsAzure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(tenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                    {
                        var subscriptionListResult = subscriptionClient.Subscriptions.List();
                        foreach (var subscription in subscriptionListResult.Subscriptions)
                        {
                            // only add the subscription if it's actually in this tenant
                            if (subscription.ActiveDirectoryTenantId == tenant)
                            {
                                AzureSubscription psSubscription = new AzureSubscription
                                {
                                    Id = new Guid(subscription.SubscriptionId),
                                    Name = subscription.SubscriptionName,
                                    Environment = environment.Name
                                };
                                psSubscription.Properties[AzureSubscription.Property.SupportedModes] =
                                    AzureModule.AzureServiceManagement.ToString();
                                psSubscription.SetProperty(AzureSubscription.Property.Tenants,
                                    subscription.ActiveDirectoryTenantId);
                                psSubscription.Account = tenantAccount.Id;
                                tenantAccount.SetOrAppendProperty(AzureAccount.Property.Subscriptions,
                                    new string[] { psSubscription.Id.ToString() });
                                result.Add(psSubscription);
                            }
                        }
                    }

                    AddOrSetAccount(tenantAccount);
                }
                catch (CloudException cEx)
                {
                    WriteOrThrowAadExceptionMessage(cEx);
                }
                catch (AadAuthenticationException aadEx)
                {
                    WriteOrThrowAadExceptionMessage(aadEx);
                }
            }

            return result;
        }
Esempio n. 17
0
        private IEnumerable<AzureSubscription> ListSubscriptionsFromServer(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            try
            {
                if (!account.IsPropertySet(AzureAccount.Property.Tenants))
                {
                    LoadAccountTenants(ref account, environment, password, promptBehavior);
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return new AzureSubscription[0];
            }

            try
            {
                List<AzureSubscription> mergedSubscriptions = MergeSubscriptions(
                    ListServiceManagementSubscriptions(ref account, environment, password, ShowDialog.Never).ToList(),
                    ListResourceManagerSubscriptions(ref account, environment, password, ShowDialog.Never).ToList());

                // Set user ID
                foreach (var subscription in mergedSubscriptions)
                {
                    subscription.Environment = environment.Name;
                    subscription.Account = account.Id;
                    account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                }

                if (mergedSubscriptions.Any())
                {
                    return mergedSubscriptions;
                }
                else
                {
                    return new AzureSubscription[0];
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return new AzureSubscription[0];
            }
        }
Esempio n. 18
0
        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";
            }

            if (TokenProvider == null)
            {
                return(new MockAccessToken()
                {
                    AccessToken = account.Id,
                    LoginType = LoginType.OrgId,
                    UserId = account.Id
                });
            }
            else
            {
                return(TokenProvider(account, environment, tenant));
            }
        }
Esempio n. 19
0
        private IEnumerable<AzureSubscription> ListSubscriptionsFromServer(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog 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.AuthenticationFactory.Authenticate(account, environment, storedTenants[0], password,
                            promptBehavior);
                    }
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return new AzureSubscription[0];
            }

            try
            {
                tenants = tenants ?? account.GetPropertyAsArray(AzureAccount.Property.Tenants);
                List<AzureSubscription> 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];
            }
        }
        private AuthenticationResult DoAcquireToken(AdalConfiguration config, ShowDialog showDialog, string userId, SecureString password)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            if (string.IsNullOrEmpty(userId))
            {
                PromptBehavior promptBehavior = (PromptBehavior)Enum.Parse(typeof(PromptBehavior), showDialog.ToString());

                if (promptBehavior != PromptBehavior.Never)
                {
                    ClearCookies();
                }

                result = context.AcquireToken(config.ResourceClientUri, config.ClientId,
                        config.ClientRedirectUri, promptBehavior,
                        UserIdentifier.AnyUser, AdalConfiguration.EnableEbdMagicCookie);
            }
            else
            {
                PromptBehavior promptBehavior = (PromptBehavior)Enum.Parse(typeof(PromptBehavior), showDialog.ToString());

                if (password == null)
                {
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId,
                        config.ClientRedirectUri, promptBehavior,
                        new UserIdentifier(userId, UserIdentifierType.OptionalDisplayableId),
                        AdalConfiguration.EnableEbdMagicCookie);
                }
                else
                {
                    UserCredential credential = new UserCredential(userId, password);
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId, credential);
                }
            }
            return result;
        }
        // We have to run this in a separate thread to guarantee that it's STA. This method
        // handles the threading details.
        private AuthenticationResult AcquireToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password)
        {
            AuthenticationResult result = null;
            Exception ex = null;

            var thread = new Thread(() =>
            {
                try
                {
                    result = DoAcquireToken(config, promptBehavior, userId, password);
                }
                catch (AdalException adalEx)
                {
                    if (adalEx.ErrorCode == AdalError.UserInteractionRequired ||
                        adalEx.ErrorCode == AdalError.MultipleTokensMatched)
                    {
                        ex = new AadAuthenticationFailedWithoutPopupException(Resources.InvalidSubscriptionState, adalEx);
                    }
                    else if (adalEx.ErrorCode == AdalError.MissingFederationMetadataUrl)
                    {
                        ex = new AadAuthenticationFailedException(Resources.CredentialOrganizationIdMessage, adalEx);
                    }
                    else
                    {
                        ex = adalEx;
                    }
                }
                catch (Exception threadEx)
                {
                    ex = threadEx;
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Name = "AcquireTokenThread";
            thread.Start();
            thread.Join();
            if (ex != null)
            {
                var adex = ex as AdalException;
                if (adex != null)
                {
                    if (adex.ErrorCode == AdalError.AuthenticationCanceled)
                    {
                        throw new AadAuthenticationCanceledException(adex.Message, adex);
                    }
                }
                if (ex is AadAuthenticationException)
                {
                    throw ex;
                }
                throw new AadAuthenticationFailedException(GetExceptionMessage(ex), ex);
            }

            return result;
        }
Esempio n. 22
0
        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);
                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));
                }

                _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 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 IEnumerable <AzureSubscription> ListServiceManagementSubscriptions(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior, string[] tenants)
        {
            List <AzureSubscription> result = new List <AzureSubscription>();

            if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement))
            {
                return(result);
            }

            foreach (var tenant in tenants)
            {
                try
                {
                    var tenantAccount = new AzureAccount();
                    CopyAccount(account, tenantAccount);
                    var tenantToken = AzureSession.AuthenticationFactory.Authenticate(tenantAccount, environment, tenant, password, ShowDialog.Never);
                    if (string.Equals(tenantAccount.Id, account.Id, StringComparison.InvariantCultureIgnoreCase))
                    {
                        tenantAccount = account;
                    }

                    tenantAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, new string[] { tenant });
                    using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <WindowsAzure.Subscriptions.SubscriptionClient>(
                               new TokenCloudCredentials(tenantToken.AccessToken),
                               environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                    {
                        var subscriptionListResult = subscriptionClient.Subscriptions.List();
                        foreach (var subscription in subscriptionListResult.Subscriptions)
                        {
                            // only add the subscription if it's actually in this tenant
                            if (subscription.ActiveDirectoryTenantId == tenant)
                            {
                                AzureSubscription psSubscription = new AzureSubscription
                                {
                                    Id          = new Guid(subscription.SubscriptionId),
                                    Name        = subscription.SubscriptionName,
                                    Environment = environment.Name
                                };
                                psSubscription.Properties[AzureSubscription.Property.SupportedModes] =
                                    AzureModule.AzureServiceManagement.ToString();
                                psSubscription.SetProperty(AzureSubscription.Property.Tenants,
                                                           subscription.ActiveDirectoryTenantId);
                                psSubscription.Account = tenantAccount.Id;
                                tenantAccount.SetOrAppendProperty(AzureAccount.Property.Subscriptions,
                                                                  new string[] { psSubscription.Id.ToString() });
                                result.Add(psSubscription);
                            }
                        }
                    }

                    AddOrSetAccount(tenantAccount);
                }
                catch (CloudException cEx)
                {
                    WriteOrThrowAadExceptionMessage(cEx);
                }
                catch (AadAuthenticationException aadEx)
                {
                    WriteOrThrowAadExceptionMessage(aadEx);
                }
            }

            return(result);
        }
Esempio n. 25
0
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior,
                                         AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)
        {
            var token = TokenProvider.GetAccessToken(GetAdalConfiguration(environment, tenant, resourceId), promptBehavior, account.Id, password, account.Type);

            account.Id = token.UserId;
            return(token);
        }
        private string[] LoadAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(account, environment,
                                                                                    AuthenticationFactory.CommonAdTenant, password, promptBehavior);

            if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager))
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                                                .CreateCustomClient <Azure.Subscriptions.SubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    return(subscriptionClient.Tenants.List().TenantIds.Select(ti => ti.TenantId).ToArray());
                }
            }
            else
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                                                .CreateCustomClient <WindowsAzure.Subscriptions.SubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                {
                    var subscriptionListResult = subscriptionClient.Subscriptions.List();
                    return(subscriptionListResult.Subscriptions.Select(s => s.ActiveDirectoryTenantId).Distinct().ToArray());
                }
            }
        }
        private IEnumerable <AzureSubscription> ListSubscriptionsFromServer(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            string[] tenants = null;
            try
            {
                if (!account.IsPropertySet(AzureAccount.Property.Tenants))
                {
                    tenants = LoadAccountTenants(account, environment, password, promptBehavior);
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return(new AzureSubscription[0]);
            }

            try
            {
                tenants = tenants ?? account.GetPropertyAsArray(AzureAccount.Property.Tenants);
                List <AzureSubscription> mergedSubscriptions = MergeSubscriptions(
                    ListServiceManagementSubscriptions(account, environment, password, ShowDialog.Never, tenants).ToList(),
                    ListResourceManagerSubscriptions(account, environment, password, ShowDialog.Never, tenants).ToList());

                // Set user ID
                foreach (var subscription in mergedSubscriptions)
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                }

                if (mergedSubscriptions.Any())
                {
                    return(mergedSubscriptions);
                }
                else
                {
                    return(new AzureSubscription[0]);
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return(new AzureSubscription[0]);
            }
        }
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior)
        {
            var token = TokenProvider.GetAccessToken(GetAdalConfiguration(environment, tenant), promptBehavior, account.Id, password, account.Type);

            account.Id = token.UserId;
            return(token);
        }
Esempio n. 29
0
        private IEnumerable<AzureSubscription> ListServiceManagementSubscriptions(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            List<AzureSubscription> result = new List<AzureSubscription>();

            if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement))
            {
                return result;
            }

            foreach (var tenant in account.GetPropertyAsArray(AzureAccount.Property.Tenants))
            {
                try
                {
                    var tenantToken = AzureSession.AuthenticationFactory.Authenticate(ref account, environment, tenant, password, ShowDialog.Never);

                    using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<WindowsAzure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(tenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                    {
                        var subscriptionListResult = subscriptionClient.Subscriptions.List();
                        foreach (var subscription in subscriptionListResult.Subscriptions)
                        {
                            AzureSubscription psSubscription = new AzureSubscription
                            {
                                Id = new Guid(subscription.SubscriptionId),
                                Name = subscription.SubscriptionName,
                                Environment = environment.Name
                            };
                            psSubscription.Properties[AzureSubscription.Property.SupportedModes] = AzureModule.AzureServiceManagement.ToString();
                            psSubscription.SetProperty(AzureSubscription.Property.Tenants, subscription.ActiveDirectoryTenantId);

                            AzureSession.SubscriptionTokenCache[Tuple.Create(psSubscription.Id, account.Id)] = tenantToken;

                            result.Add(psSubscription);
                        }
                    }
                }
                catch (CloudException cEx)
                {
                    WriteOrThrowAadExceptionMessage(cEx);
                }
                catch (AadAuthenticationException aadEx)
                {
                    WriteOrThrowAadExceptionMessage(aadEx);
                }
            }

            return result;
        }
Esempio n. 30
0
        private List <AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            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)))
            {
                return(subscriptionClient.Tenants.List().TenantIds
                       .Select(ti => new AzureTenant()
                {
                    Id = new Guid(ti.TenantId), Domain = commonTenantToken.GetDomain()
                })
                       .ToList());
            }
        }
        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);
        }
Esempio n. 32
0
        private IEnumerable <AzureSubscription> ListSubscriptionsForTenant(AzureAccount account, AzureEnvironment environment,
                                                                           SecureString password, ShowDialog promptBehavior, string tenantId)
        {
            var accessToken = AcquireAccessToken(account, environment, tenantId, password, promptBehavior);

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

                return(new List <AzureSubscription>());
            }
        }
Esempio n. 33
0
        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)))));
                }

                return(new List <AzureSubscription>());
            }
        }
Esempio n. 34
0
        protected async Task InvokeAsync(Func <Task> method, Action resultCallback = null, Action <Exception> errorCallback = null, ShowDialog showDialog = ShowDialog.Yes)
        {
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }
            if (!Enum.IsDefined(typeof(ShowDialog), showDialog))
            {
                throw new InvalidEnumArgumentException(nameof(showDialog), (Int32)showDialog, typeof(ShowDialog));
            }

            try {
                this.IsBusy = true;
                await method.Invoke();

                resultCallback?.Invoke();
                this.IsBusy = false;
            } catch (AggregateException ae) {
                await HandleAggregateException(ae, errorCallback, showDialog);
            } catch (Exception ex) {
                await HandleException(ex, errorCallback, showDialog);
            }
        }
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password)
 {
     return GetAccessToken(config, promptBehavior, userId, password, AzureAccount.AccountType.User);
 }
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            Token = new MockAccessToken
            {
                UserId      = account.Id,
                LoginType   = LoginType.OrgId,
                AccessToken = Token.AccessToken
            };

            return(Token);
        }
        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));
        }
Esempio n. 38
0
        async Task HandleAggregateException(AggregateException ae, Action <Exception> errorCallback, ShowDialog showDialog)
        {
            this.IsBusy = false;
            var baseException = ae?.Flatten()?.GetBaseException() ?? new Exception(GlobalConstants.AntecedentExceptionNull);

            if (showDialog == ShowDialog.Yes)
            {
                await _pageDialogService.DisplayAlertAsync(GlobalConstants.Error, baseException.Message, GlobalConstants.OK);
            }
            errorCallback?.Invoke(baseException);
        }
Esempio n. 39
0
        /// <summary>
        /// Chart 설정 또는 변량에 대해 XML로 생성합니다.
        /// </summary>
        /// <param name="writer">xml writer</param>
        public override void GenerateXmlAttributes(System.Xml.XmlWriter writer)
        {
            base.GenerateXmlAttributes(writer);

            if (Enabled.HasValue)
            {
                writer.WriteAttributeString(EXPORT + "Enabled", Enabled.GetHashCode().ToString());
            }
            if (ShowMenuItem.HasValue)
            {
                writer.WriteAttributeString(EXPORT + "ShowMenuItem", ShowMenuItem.GetHashCode().ToString());
            }
            if (Formats.IsNotWhiteSpace())
            {
                writer.WriteAttributeString(EXPORT + "Formats", Formats);
            }
            if (AtClient.HasValue)
            {
                writer.WriteAttributeString(EXPORT + "AtClient", AtClient.GetHashCode().ToString());
            }
            if (Handler.IsNotWhiteSpace())
            {
                writer.WriteAttributeString(EXPORT + "Handler", Handler);
            }
            if (Action.IsNotWhiteSpace())
            {
                writer.WriteAttributeString(EXPORT + "Action", Action);
            }
            if (TargetWindow.IsNotWhiteSpace())
            {
                writer.WriteAttributeString(EXPORT + "TargetWindow", TargetWindow);
            }
            if (Callback.IsNotWhiteSpace())
            {
                writer.WriteAttributeString(EXPORT + "Callback", Callback);
            }
            if (FileName.IsNotWhiteSpace())
            {
                writer.WriteAttributeString(EXPORT + "FileName", FileName);
            }

            if (ShowDialog.HasValue)
            {
                writer.WriteAttributeString("Show" + EXPORT + "Dialog", ShowDialog.GetHashCode().ToString());
            }
            if (DialogMessage.IsNotWhiteSpace())
            {
                writer.WriteAttributeString(EXPORT + "DialogMessage", DialogMessage);
            }

            if (DialogColor.HasValue)
            {
                writer.WriteAttributeString(EXPORT + "DialogColor", DialogColor.Value.ToHexString());
            }
            if (DialogBorderColor.HasValue)
            {
                writer.WriteAttributeString(EXPORT + "DialogBorderColor", DialogBorderColor.Value.ToHexString());
            }
            if (DialogFontColor.HasValue)
            {
                writer.WriteAttributeString(EXPORT + "DialogFontColor", DialogFontColor.Value.ToHexString());
            }
            if (DialogPBColor.HasValue)
            {
                writer.WriteAttributeString(EXPORT + "DialogPBColor", DialogPBColor.Value.ToHexString());
            }
        }
Esempio n. 40
0
        private IEnumerable <AzureSubscription> ListSubscriptionsFromServer(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog 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.AuthenticationFactory.Authenticate(account, environment, storedTenants[0], password,
                                                                        promptBehavior);
                    }
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return(new AzureSubscription[0]);
            }

            try
            {
                tenants = tenants ?? account.GetPropertyAsArray(AzureAccount.Property.Tenants);
                List <AzureSubscription> 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]);
            }
        }
Esempio n. 41
0
    /// <summary>
    /// Loads a dialog tree from a XML file (located in Resources/Dialogs/Trees/).
    /// </summary>
    /// <param name="filename">Filename (without extension).</param>
    public void loadFileOfDialogs(string filename)
    {
        filename = "Dialogs/Trees/" + filename;

        XmlDocument xmlDoc;

        try
        {
            xmlDoc = loadDocument(filename);
        }
        catch (XmlException e)
        {
            Debug.LogError("Unable to parse XML file. Error: " + e.Message);
            return;
        }
        catch (System.Exception e)
        {
            Debug.LogError("Unable to parse XML file (not a XmlException). Error: " + e.Message);
            return;
        }

        BaseDialog beginNode = null;
        Dictionary <string, BaseDialog> registeredNodes = new Dictionary <string, BaseDialog>();

        // Parsowanie XMLi dla drzewek dialogowych.
        foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
        {
            string type = node.Attributes.GetNamedItem("type").InnerText.ToLower();
            switch (type)
            {
            case "showdialog":
            {
                string who = node.Attributes.GetNamedItem("who")?.InnerText;
                string whichNext = node.Attributes.GetNamedItem("next")?.InnerText;
                string text = node.InnerText, finalText;
                if (!dialogPairs.TryGetValue(text, out finalText))
                {
                    finalText = text;
                }

                ShowDialog workingNode = new ShowDialog();
                //workingNode.nextNode = registeredNodes[whichNext];
                workingNode.who    = who;
                workingNode.dialog = text;
                registeredNodes.Add(node.Name, workingNode);
                if (beginNode == null)
                {
                    beginNode = workingNode;
                }
            }
            break;

            case "choicedialog":
            {
                string who = node.Attributes.GetNamedItem("who")?.InnerText;
                string text = node.InnerText, finalText;
                if (!dialogPairs.TryGetValue(text, out finalText))
                {
                    finalText = text;
                }

                ChoiceDialog choiceDialog = new ChoiceDialog();
                choiceDialog.who    = who;
                choiceDialog.dialog = text;
                registeredNodes.Add(node.Name, choiceDialog);
                if (beginNode == null)
                {
                    beginNode = choiceDialog;
                }
            }
            break;

            default:
            {
                Debug.LogWarning("Unknown dialog type: " + type);
            }
            break;
            }
        }

        foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
        {
            string type = node.Attributes.GetNamedItem("type").InnerText.ToLower();
            switch (type)
            {
            case "showdialog":
            {
                string whichNext = node.Attributes.GetNamedItem("next")?.InnerText;
                if (whichNext.Length > 0)
                {
                    ShowDialog workingNode = (ShowDialog)registeredNodes[node.Name];
                    workingNode.nextNode = registeredNodes[whichNext];
                }
            }
            break;

            case "choicedialog":
            {
                //int choices = int.Parse(node.Attributes.GetNamedItem("choices").InnerText);
                int      choices     = (node.Attributes.Count - 2) / 2;
                string[] choiceNodes = new string[choices], choiceStrs = new string[choices];
                for (int x = 0; x < choices; ++x)
                {
                    choiceStrs[x]  = node.Attributes.GetNamedItem("choice_" + x).InnerText;
                    choiceNodes[x] = node.Attributes.GetNamedItem("choiceNode_" + x).InnerText;
                }
                ChoiceDialog workingNode = (ChoiceDialog)registeredNodes[node.Name];
                workingNode.choices     = choiceStrs;
                workingNode.choiceNodes = new BaseDialog[choices];
                for (int x = 0; x < choices; ++x)
                {
                    workingNode.choiceNodes[x] = registeredNodes[choiceNodes[x]];
                }
            }
            break;
            }
        }

        if (beginNode != null)
        {
            registeredDialogs.Add(filename, beginNode);
        }
    }
 public IObservable <TResult> Of <TDialog, TResult>() where TDialog : IBaseDialog <TResult, TInitialData>
 {
     return(_data.SelectMany(data
                             => ShowDialog <TDialog, TResult, TInitialData>(_actor, () => data, _parameters)())
            .ObserveOnSelf());
 }
Esempio n. 43
0
        private string[] LoadAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(account, environment,
                AuthenticationFactory.CommonAdTenant, password, promptBehavior);

            using (SubscriptionClient SubscriptionClient = AzureSession.ClientFactory
                        .CreateCustomClient<SubscriptionClient>(
                            new TokenCloudCredentials(commonTenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
            {
                var subscriptionListResult = SubscriptionClient.Subscriptions.List();
                return subscriptionListResult.Subscriptions.Select(s => s.ActiveDirectoryTenantId).Distinct().ToArray();
            }
        }
Esempio n. 44
0
        public AzureRMProfile Login(
            AzureAccount account,
            AzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            SecureString password)
        {
            AzureSubscription newSubscription = null;
            AzureTenant       newTenant       = null;
            ShowDialog        promptBehavior  =
                (password == null &&
                 account.Type != AzureAccount.AccountType.AccessToken &&
                 !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
                ? ShowDialog.Always : ShowDialog.Never;

            // (tenant and subscription are present) OR
            // (tenant is present and subscription is not provided)
            if (!string.IsNullOrEmpty(tenantId))
            {
                var token = AcquireAccessToken(account, environment, tenantId, password, promptBehavior);
                if (TryGetTenantSubscription(token, account, environment, tenantId, subscriptionId, subscriptionName, out newSubscription, out newTenant))
                {
                    account.SetProperty(AzureAccount.Property.Tenants, new[] { newTenant.Id.ToString() });
                }
            }
            // (tenant is not provided and subscription is present) OR
            // (tenant is not provided and subscription is not provided)
            else
            {
                var tenants = ListAccountTenants(account, environment, password, promptBehavior).Select(s => s.Id.ToString()).ToArray();
                account.SetProperty(AzureAccount.Property.Tenants, null);
                string accountId = null;

                for (int i = 0; i < tenants.Count(); i++)
                {
                    var tenant = tenants[i];

                    AzureTenant       tempTenant;
                    AzureSubscription tempSubscription;

                    IAccessToken token = null;

                    try
                    {
                        token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto);

                        if (accountId == null)
                        {
                            accountId = account.Id;
                            account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                        }
                        else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase))
                        {
                            account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                        }
                        else
                        {   // if account ID is different from the first tenant account id we need to ignore current tenant
                            WriteWarningMessage(string.Format(
                                                    Microsoft.Azure.Commands.Profile.Properties.Resources.AccountIdMismatch,
                                                    account.Id,
                                                    tenant,
                                                    accountId));
                            account.Id = accountId;
                            token      = null;
                        }
                    }
                    catch
                    {
                        WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, tenant));
                    }

                    if (token != null &&
                        newTenant == null &&
                        TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant))
                    {
                        newTenant       = tempTenant;
                        newSubscription = tempSubscription;
                    }
                }
            }

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

                _profile.Context = new AzureContext(account, environment, newTenant);
            }
            else
            {
                _profile.Context = new AzureContext(newSubscription, account, environment, newTenant);
            }

            _profile.Context.TokenCache = TokenCache.DefaultShared.Serialize();

            return(_profile);
        }
Esempio n. 45
0
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
                                    AzureAccount.AccountType credentialType)
 {
     AdalConfiguration = config;
     return(this.accessToken);
 }
Esempio n. 46
0
        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);
        }
Esempio n. 47
0
        private void LoadAccountTenants(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(ref account, environment,
                AuthenticationFactory.CommonAdTenant, password, promptBehavior);

            if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager))
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                        .CreateCustomClient<Azure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(commonTenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants,
                        subscriptionClient.Tenants.List().TenantIds.Select(ti => ti.TenantId).ToArray());
                }
            }
            else
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                        .CreateCustomClient<WindowsAzure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(commonTenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                {
                    var subscriptionListResult = subscriptionClient.Subscriptions.List();
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants,
                        subscriptionListResult.Subscriptions.Select(s => s.ActiveDirectoryTenantId).Distinct().ToArray());
                }
            }
        }
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password)
 {
     return(userTokenProvider.GetAccessToken(config, promptBehavior, userId, password, AzureAccount.AccountType.User));
 }
Esempio n. 49
0
        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 IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password)
 {
     throw new InvalidOperationException(string.Format(Resources.InvalidCredentialType, "ServicePrincipal"));
 }
        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 IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId,
     SecureString password)
 {
     return this.accessToken;
 }
Esempio n. 53
0
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password)
 {
     throw new InvalidOperationException(string.Format(Resources.InvalidCredentialType, "ServicePrincipal"));
 }
Esempio n. 54
0
        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 => new AzureTenant()
                    {
                        Id     = new Guid(ti),
                        Domain = AccessTokenExtensions.GetDomain(account.Id)
                    }).ToList();
                }
            }

            return(result);
        }
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
     AzureAccount.AccountType credentialType)
 {
     return this.accessToken;
 }
 public static Task <TData> ShowDialogAsync <TDialog, TData>(this UiActor actor, params Parameter[] parameters)
     where TDialog : IBaseDialog <TData, TData>
 => ShowDialog <TDialog, TData>(actor, parameters)();