public override void ExecuteCmdlet()

in src/PowerShell/Commands/NewPartnerAccessToken.cs [167:326]


        public override void ExecuteCmdlet()
        {
            Scheduler.RunTask(async () =>
            {
                PartnerAccount account = new PartnerAccount();
                string applicationId;

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

                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(RefreshTokenParameterSet, StringComparison.InvariantCultureIgnoreCase))
                {
                    if (Credential != null)
                    {
                        account.ObjectId = Credential.UserName;
                        account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString());
                        applicationId = Credential.UserName;
                    }
                    else
                    {
                        applicationId = ApplicationId;
                    }
                }
                else if (ParameterSetName.Equals(ServicePrincipalCertificateParameterSet, StringComparison.InvariantCultureIgnoreCase))
                {
                    account.SetProperty(PartnerAccountPropertyType.ApplicationId, ApplicationId);
                    account.Type = AccountType.Certificate;
                    applicationId = ApplicationId;
                }
                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);

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

                byte[] cacheData = null;

                if (PartnerSession.Instance.TryGetComponent(ComponentKey.TokenCache, out IPartnerTokenCache tokenCache))
                {
                    cacheData = tokenCache.GetCacheData();

                    if (cacheData?.Length > 0)
                    {
                        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);
                                }
                            }
                        }

                        if (authResult.Account != null)
                        {
                            string key = tokenCache.GetCacheKey(authResult);

                            if (tokens.ContainsKey(key))
                            {
                                result.RefreshToken = tokens[key].Secret;
                            }
                        }
                    }
                    else
                    {
                        WriteDebug("There was not any data in the token cache, so a refresh token could not be retrieved.");
                    }
                }
                else
                {
                    WriteDebug("Unable to find a registered token cache.");
                }

                WriteObject(result);
            });
        }