Beispiel #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="account"></param>
        /// <param name="environment"></param>
        /// <param name="redirectUri"></param>
        /// <returns></returns>
        public IClientApplicationBase GetClient(PartnerAccount account, PartnerEnvironment environment, string redirectUri = null)
        {
            IClientApplicationBase app;

            if (account.IsPropertySet(PartnerAccountPropertyType.CertificateThumbprint) || account.IsPropertySet(PartnerAccountPropertyType.ServicePrincipalSecret))
            {
                app = SharedTokenCacheClientFactory.CreateConfidentialClient(
                    $"{environment.ActiveDirectoryAuthority}{account.Tenant}",
                    account.GetProperty(PartnerAccountPropertyType.ApplicationId),
                    account.GetProperty(PartnerAccountPropertyType.ServicePrincipalSecret),
                    GetCertificate(account.GetProperty(PartnerAccountPropertyType.CertificateThumbprint)),
                    redirectUri,
                    account.Tenant);
            }
            else
            {
                app = SharedTokenCacheClientFactory.CreatePublicClient(
                    $"{environment.ActiveDirectoryAuthority}{account.Tenant}",
                    account.GetProperty(PartnerAccountPropertyType.ApplicationId),
                    redirectUri,
                    account.Tenant);
            }

            return(app);
        }
        /// <summary>
        /// Performs the execution of the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            PartnerAccount account = new PartnerAccount();

            if (ParameterSetName.Equals(AccessTokenParameterSet, StringComparison.InvariantCultureIgnoreCase))
            {
                account.SetProperty(PartnerAccountPropertyType.AccessToken, AccessToken);
                account.Type = AccountType.AccessToken;
            }
            else if (ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase))
            {
                account.ObjectId = Credential.UserName;
                account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString());
                account.Type = AccountType.ServicePrincipal;
            }
            else
            {
                account.Type = AccountType.User;
            }

            if (UseAuthorizationCode.IsPresent)
            {
                account.SetProperty("UseAuthCode", "true");
            }

            if (UseDeviceAuthentication.IsPresent)
            {
                account.SetProperty("UseDeviceAuth", "true");
            }

            if (!string.IsNullOrEmpty(RefreshToken))
            {
                account.SetProperty(PartnerAccountPropertyType.RefreshToken, RefreshToken);
            }

            account.SetProperty(PartnerAccountPropertyType.ApplicationId, ApplicationId);

            account.Tenant = string.IsNullOrEmpty(Tenant) ? "common" : Tenant;

            AuthenticationResult authResult = PartnerSession.Instance.AuthenticationFactory.Authenticate(
                account,
                PartnerEnvironment.PublicEnvironments[Environment],
                Scopes,
                Message);

            byte[] cacheData = SharedTokenCacheClientFactory.GetTokenCache(ApplicationId).SerializeMsalV3();

            IEnumerable <string> knownPropertyNames = new[] { "AccessToken", "RefreshToken", "IdToken", "Account", "AppMetadata" };

            JObject root = JObject.Parse(Encoding.UTF8.GetString(cacheData, 0, cacheData.Length));

            IDictionary <string, JToken> known = (root as IDictionary <string, JToken>)
                                                 .Where(kvp => knownPropertyNames.Any(p => string.Equals(kvp.Key, p, StringComparison.OrdinalIgnoreCase)))
                                                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            IDictionary <string, TokenCacheItem> tokens = new Dictionary <string, TokenCacheItem>();

            if (known.ContainsKey("RefreshToken"))
            {
                foreach (JToken token in root["RefreshToken"].Values())
                {
                    if (token is JObject j)
                    {
                        TokenCacheItem item = new TokenCacheItem
                        {
                            ClientId       = ExtractExistingOrEmptyString(j, "client_id"),
                            CredentialType = ExtractExistingOrEmptyString(j, "credential_type"),
                            Environment    = ExtractExistingOrEmptyString(j, "environment"),
                            HomeAccountId  = ExtractExistingOrEmptyString(j, "home_account_id"),
                            RawClientInfo  = ExtractExistingOrEmptyString(j, "client_info"),
                            Secret         = ExtractExistingOrEmptyString(j, "secret")
                        };

                        tokens.Add($"{item.HomeAccountId}-{item.Environment}-RefreshToken-{item.ClientId}--", item);
                    }
                }
            }

            string key = GetTokenCacheKey(authResult);

            AuthResult result = new AuthResult(
                authResult.AccessToken,
                authResult.IsExtendedLifeTimeToken,
                authResult.UniqueId,
                authResult.ExpiresOn,
                authResult.ExtendedExpiresOn,
                authResult.TenantId,
                authResult.Account,
                authResult.IdToken,
                authResult.Scopes);

            if (tokens.ContainsKey(key))
            {
                result.RefreshToken = tokens[key].Secret;
            }

            FlushDebugMessages();
            WriteObject(result);
        }
        /// <summary>
        /// Executes the operations associated with the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            Scheduler.RunTask(async() =>
            {
                PartnerAccount account = new PartnerAccount();
                string applicationId;

                if (ParameterSetName.Equals(AccessTokenParameterSet, StringComparison.InvariantCultureIgnoreCase))
                {
                    account.SetProperty(PartnerAccountPropertyType.AccessToken, AccessToken);
                    account.Type  = AccountType.AccessToken;
                    applicationId = ApplicationId;
                }
                else if (ParameterSetName.Equals(ByModuleParameterSet, StringComparison.InvariantCultureIgnoreCase))
                {
                    account.SetProperty(PartnerAccountPropertyType.UseDeviceAuth, "true");
                    account.Type  = AccountType.User;
                    applicationId = PowerShellModule.KnownModules[Module].ApplicationId;

                    Scopes = PowerShellModule.KnownModules[Module].Scopes.ToArray();
                }
                else if (ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase))
                {
                    account.ObjectId = Credential.UserName;
                    account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString());
                    account.Type  = AccountType.ServicePrincipal;
                    applicationId = ApplicationId;
                }
                else
                {
                    account.Type  = AccountType.User;
                    applicationId = ApplicationId;
                }

                if (!ParameterSetName.Equals(ByModuleParameterSet, StringComparison.InvariantCultureIgnoreCase))
                {
                    if (UseAuthorizationCode.IsPresent)
                    {
                        account.SetProperty(PartnerAccountPropertyType.UseAuthCode, "true");
                    }

                    if (UseDeviceAuthentication.IsPresent)
                    {
                        account.SetProperty(PartnerAccountPropertyType.UseDeviceAuth, "true");
                    }
                }

                if (!string.IsNullOrEmpty(RefreshToken))
                {
                    account.SetProperty(PartnerAccountPropertyType.RefreshToken, RefreshToken);
                }

                account.SetProperty(PartnerAccountPropertyType.ApplicationId, applicationId);
                account.Tenant = string.IsNullOrEmpty(Tenant) ? "organizations" : Tenant;

                AuthenticationResult authResult = await PartnerSession.Instance.AuthenticationFactory.AuthenticateAsync(
                    account,
                    PartnerEnvironment.PublicEnvironments[Environment],
                    Scopes,
                    Message,
                    CancellationToken).ConfigureAwait(false);

                byte[] cacheData = SharedTokenCacheClientFactory.GetMsalCacheStorage(ApplicationId).ReadData();

                IEnumerable <string> knownPropertyNames = new[] { "AccessToken", "RefreshToken", "IdToken", "Account", "AppMetadata" };

                JObject root = JObject.Parse(Encoding.UTF8.GetString(cacheData, 0, cacheData.Length));

                IDictionary <string, JToken> known = (root as IDictionary <string, JToken>)
                                                     .Where(kvp => knownPropertyNames.Any(p => string.Equals(kvp.Key, p, StringComparison.OrdinalIgnoreCase)))
                                                     .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

                IDictionary <string, TokenCacheItem> tokens = new Dictionary <string, TokenCacheItem>();

                if (known.ContainsKey("RefreshToken"))
                {
                    foreach (JToken token in root["RefreshToken"].Values())
                    {
                        if (token is JObject j)
                        {
                            TokenCacheItem item = new TokenCacheItem
                            {
                                ClientId       = ExtractExistingOrEmptyString(j, "client_id"),
                                CredentialType = ExtractExistingOrEmptyString(j, "credential_type"),
                                Environment    = ExtractExistingOrEmptyString(j, "environment"),
                                HomeAccountId  = ExtractExistingOrEmptyString(j, "home_account_id"),
                                RawClientInfo  = ExtractExistingOrEmptyString(j, "client_info"),
                                Secret         = ExtractExistingOrEmptyString(j, "secret")
                            };

                            tokens.Add($"{item.HomeAccountId}-{item.Environment}-RefreshToken-{item.ClientId}--", item);
                        }
                    }
                }

                AuthResult result = new AuthResult(
                    authResult.AccessToken,
                    authResult.IsExtendedLifeTimeToken,
                    authResult.UniqueId,
                    authResult.ExpiresOn,
                    authResult.ExtendedExpiresOn,
                    authResult.TenantId,
                    authResult.Account,
                    authResult.IdToken,
                    authResult.Scopes,
                    authResult.CorrelationId);

                if (authResult.Account != null)
                {
                    string key = SharedTokenCacheClientFactory.GetTokenCacheKey(authResult, applicationId);

                    if (tokens.ContainsKey(key))
                    {
                        result.RefreshToken = tokens[key].Secret;
                    }
                }

                WriteObject(result);
            });
        }