/// <summary>
        /// Acquires the security token from the authority.
        /// </summary>
        /// <param name="account">The account information to be used when generating the client.</param>
        /// <param name="environment">The environment where the client is connecting.</param>
        /// <param name="scopes">Scopes requested to access a protected service.</param>
        /// <param name="message">The message to be written to the console.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>The result from the authentication request.</returns>
        public async Task <AuthenticationResult> AuthenticateAsync(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message = null, CancellationToken cancellationToken = default)
        {
            AuthenticationResult authResult           = null;
            IAuthenticator       processAuthenticator = Builder.Authenticator;

            while (processAuthenticator != null && authResult == null)
            {
                authResult = await processAuthenticator.TryAuthenticateAsync(GetAuthenticationParameters(account, environment, scopes, message), cancellationToken).ConfigureAwait(false);

                if (authResult != null)
                {
                    if (authResult.Account?.HomeAccountId != null)
                    {
                        account.Identifier = authResult.Account.HomeAccountId.Identifier;
                        account.ObjectId   = authResult.Account.HomeAccountId.ObjectId;
                    }

                    if (account.Tenant.Equals("organizations", StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(authResult.TenantId))
                    {
                        account.Tenant = authResult.TenantId;
                    }

                    break;
                }

                processAuthenticator = processAuthenticator.NextAuthenticator;
            }

            return(authResult);
        }
Exemplo n.º 2
0
        private AuthenticationParameters GetAuthenticationParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message = null)
        {
            if (account.IsPropertySet(PartnerAccountPropertyType.AccessToken))
            {
                return(new AccessTokenParameters(account, environment, scopes));
            }
            else if (account.IsPropertySet("UseAuthCode"))
            {
                return(new InteractiveParameters(account, environment, scopes, message));
            }
            else if (account.IsPropertySet(PartnerAccountPropertyType.RefreshToken))
            {
                return(new RefreshTokenParameters(account, environment, scopes));
            }
            else if (account.Type == AccountType.User)
            {
                if (!string.IsNullOrEmpty(account.ObjectId))
                {
                    return(new SilentParameters(account, environment, scopes));
                }
                else if (account.IsPropertySet("UseDeviceAuth"))
                {
                    return(new DeviceCodeParameters(account, environment, scopes));
                }

                return(new InteractiveParameters(account, environment, scopes, message));
            }
            else if (account.Type == AccountType.ServicePrincipal || account.Type == AccountType.Certificate)
            {
                return(new ServicePrincipalParameters(account, environment, scopes));
            }

            return(null);
        }
Exemplo n.º 3
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>
        /// Gets an aptly configured client.
        /// </summary>
        /// <param name="account">The account information to be used when generating the client.</param>
        /// <param name="environment">The environment where the client is connecting.</param>
        /// <param name="redirectUri">The redirect URI for the client.</param>
        /// <returns>An aptly configured client.</returns>
        public IClientApplicationBase GetClient(PartnerAccount account, PartnerEnvironment environment, string redirectUri = null)
        {
            IClientApplicationBase app;

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

            return(app);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Performs the execution of the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            string result = "pass";

            PartnerAccount account = new PartnerAccount
            {
                Tenant = "organizations",
                Type   = AccountType.User
            };

            PartnerEnvironment environment = PartnerEnvironment.PublicEnvironments[Environment];

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

            account.SetProperty(PartnerAccountPropertyType.ApplicationId, PowerShellApplicationId);

            Scheduler.RunTask(async() =>
            {
                AuthenticationResult authResult = await PartnerSession.Instance.AuthenticationFactory.AuthenticateAsync(
                    account,
                    environment,
                    new[] { $"{environment.PartnerCenterEndpoint}/user_impersonation" },
                    Message,
                    CancellationToken).ConfigureAwait(false);


                JsonWebToken jwt = new JsonWebToken(authResult.AccessToken);

                WriteDebug("Checking if the access token contains the MFA claim...");

                /*
                 * Obtain the authentication method reference (AMR) claim. This claim contains the methods used
                 * during authenitcation. See https://tools.ietf.org/html/rfc8176 for more information.
                 */

                if (jwt.TryGetClaim("amr", out Claim claim))
                {
                    if (!claim.Value.Contains("mfa"))
                    {
                        WriteWarning("Unable to determine if the account authenticated using MFA. See https://aka.ms/partnercenterps-psr-warning for more information.");
                        result = "fail";
                    }
                }
                else
                {
                    WriteWarning("Unable to find the AMR claim, which means the ability to verify the MFA challenge happened will not be possible. See https://aka.ms/partnercenterps-psr-warning for more information.");
                    result = "fail";
                }

                WriteObject(result);
            });
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationParameters" /> class.
        /// </summary>
        protected AuthenticationParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes)
        {
            account.AssertNotNull(nameof(account));
            environment.AssertNotNull(nameof(environment));
            scopes.AssertNotNull(nameof(scopes));

            Account     = account;
            Environment = environment;
            Scopes      = scopes;
        }
Exemplo n.º 7
0
 /// <summary>
 /// Acquires the security token from the authority.
 /// </summary>
 /// <returns>The result from the authentication request.</returns>
 public AuthenticationResult Authenticate(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message, Action <string> promptAction = null, CancellationToken cancellationToken = default)
 {
     return(new AuthenticationResult(
                "STUB_TOKEN",
                true,
                "uniquedId",
                DateTimeOffset.UtcNow.AddHours(1),
                DateTimeOffset.UtcNow.AddHours(1),
                "xxxx-xxxx-xxxx-xxxx",
                null,
                "STUB_TOKEN",
                scopes));
 }
Exemplo n.º 8
0
        public async Task <AuthenticationResult> AuthenticateAsync(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message = null, CancellationToken cancellationToken = default)
        {
            await Task.CompletedTask;

            return(new AuthenticationResult(
                       "STUB_TOKEN",
                       true,
                       "uniquedId",
                       DateTimeOffset.UtcNow.AddHours(1),
                       DateTimeOffset.UtcNow.AddHours(1),
                       "xxxx-xxxx-xxxx-xxxx",
                       null,
                       "STUB_TOKEN",
                       scopes,
                       Guid.Empty));
        }
Exemplo n.º 9
0
        public decimal QueryBalance()
        {
            BalanceRequestInfo info3   = new BalanceRequestInfo();
            PartnerAccount     account = new PartnerAccount();

            account.PartnerId    = PartnerId;
            info3.PartnerAccount = account;
            BalanceRequestInfo  messageObject = info3;
            BalanceResponseInfo info2         = RequestMessage <BalanceResponseInfo>(messageObject);

            if ((info2.ErrInfo != null) && (info2.ErrInfo.TransCode != null))
            {
                throw new GatewayException(info2.ErrInfo.Message);
            }
            return(info2.PartnerAccount.Balance);
        }
        /// <summary>
        /// Creates a new service client used interact with a specific service.
        /// </summary>
        /// <typeparam name="TClient">Type of service client being created.</typeparam>
        /// <param name="scopes">Scopes requested to access a protected service.</param>
        /// <param name="tenantId">The identifier for the tenant.</param>
        /// <returns>An instance of a service client that is connected to a specific service.</returns>
        public virtual async Task <TClient> CreateServiceClientAsync <TClient>(string[] scopes, string tenantId = null) where TClient : ServiceClient <TClient>
        {
            PartnerAccount account = PartnerSession.Instance.Context.Account.Clone();

            if (!string.IsNullOrEmpty(tenantId))
            {
                account.Tenant = tenantId;
            }

            AuthenticationResult authResult = await PartnerSession.Instance.AuthenticationFactory.AuthenticateAsync(
                account,
                PartnerSession.Instance.Context.Environment,
                scopes).ConfigureAwait(false);

            return(CreateServiceClient <TClient>(new TokenCredentials(authResult.AccessToken, "Bearer"), HttpClient, false));
        }
Exemplo n.º 11
0
        public object Any(InitGateway request)
        {
            try
            {
                Logger.OpenLog("TripThruGateway");

                StorageManager.OpenStorage(new SqliteStorage("~/../../Db/db.sqlite".MapHostAbsolutePath()));
                PartnerAccount partnerAccount = new PartnerAccount
                {
                    UserName            = "******",
                    Password            = "******",
                    Email               = "",
                    AccessToken         = "iUaySN4P1v3a1m5kQ3K1XvCIa8NkV1Psr",
                    RefreshToken        = "",
                    ClientId            = "*****@*****.**",
                    ClientSecret        = "",
                    TripThruAccessToken = ""
                };
                StorageManager.CreatePartnerAccount(partnerAccount);

                GatewayService.gateway = new TripThru();
                //Logger.OpenLog("TripThruGateway", "c:\\Users\\Edward\\");

                foreach (PartnerAccount account in StorageManager.GetPartnerAccounts())
                {
                    if (account.CallbackUrl != null && account.PartnerName != null)
                    {
                        GatewayService.gateway.RegisterPartner(
                            new GatewayClient(
                                account.ClientId,
                                account.PartnerName,
                                account.TripThruAccessToken,
                                account.CallbackUrl
                                )
                            );
                    }
                }

                MapTools.SetGeodataFilenames("~/App_Data/Geo-Location-Names.csv".MapHostAbsolutePath(), "~/App_Data/Geo-Routes.csv".MapHostAbsolutePath(), "~/App_Data/Geo-Location-Addresses.csv".MapHostAbsolutePath());
                MapTools.LoadGeoData();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            return(new InitGatewayResponse());
        }
Exemplo n.º 12
0
        public AuthenticationResult Authenticate(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message = null, Action <string> promptAction = null, CancellationToken cancellationToken = default)
        {
            AuthenticationResult authResult           = null;
            IAuthenticator       processAuthenticator = Builder.Authenticator;
            int retries = 5;

            while (retries-- > 0)
            {
                try
                {
                    while (processAuthenticator != null && processAuthenticator.TryAuthenticate(GetAuthenticationParameters(account, environment, scopes, message), out Task <AuthenticationResult> result, promptAction, cancellationToken))
                    {
                        authResult = result.ConfigureAwait(true).GetAwaiter().GetResult();

                        if (authResult != null)
                        {
                            if (authResult.Account?.HomeAccountId != null)
                            {
                                account.Identifier = authResult.Account.HomeAccountId.Identifier;
                                account.ObjectId   = authResult.Account.HomeAccountId.ObjectId;
                            }

                            if (account.Tenant.Equals("common", StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(authResult.TenantId))
                            {
                                account.Tenant = authResult.TenantId;
                            }

                            break;
                        }

                        processAuthenticator = processAuthenticator.Next;
                    }
                }
                catch (InvalidOperationException)
                {
                    continue;
                }

                break;
            }

            return(authResult ?? null);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Authenticates the specified request message.
        /// </summary>
        /// <param name="request">The HTTP request to be authenticated.</param>
        /// <returns>An instance of the <see cref="Task"/> class that represents the asynchronous operation.</returns>
        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            request.AssertNotNull(nameof(request));

            PartnerAccount account = PartnerSession.Instance.Context.Account.Clone();

            if (!string.IsNullOrEmpty(tenantId))
            {
                account.Tenant = tenantId;
            }

            AuthenticationResult authResult = await PartnerSession.Instance.AuthenticationFactory.AuthenticateAsync(
                account,
                PartnerSession.Instance.Context.Environment,
                new[] { $"{PartnerSession.Instance.Context.Environment.GraphEndpoint}/.default" }).ConfigureAwait(false);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

            await Task.CompletedTask.ConfigureAwait(false);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TestBase" /> class.
        /// </summary>
        static TestBase()
        {
            IPartnerCredentials credentials = new TestPartnerCredentials();

            PartnerSession.Instance.ClientFactory = new MockClientFactory(httpMockHandler, credentials);

            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            PartnerSession.Instance.AuthenticationFactory = new MockAuthenticationFactory();

            PartnerAccount account = new PartnerAccount
            {
                Type = AccountType.User
            };

            PartnerSession.Instance.Context = new PartnerContext
            {
                Account     = account,
                CountryCode = "US",
                Environment = PartnerEnvironment.PublicEnvironments[EnvironmentName.AzureCloud],
                Locale      = "en-US",
            };
        }
        // GET: PayLogin
        //[HttpGet]
        // public ActionResult Index()
        // {
        //     return View();
        // }

        // [HttpPost]
        // public ActionResult Index(PartnerAccount partner)
        // {
        //     if (db.LoginPartnerAccount(partner) == false)
        //     {
        //         return View(partner);
        //     }
        //     else
        //     {
        //         Session["PartnerAccount"] = db.Find(partner.partnerAccount).accountNumber;
        //         return RedirectToAction("Checkout","PayCheckout");
        //     }
        // }

        public JsonResult Login(string Account, string Password)
        {
            var partner = new PartnerAccount()
            {
                partnerAccount = Convert.ToInt64(Account),
                password       = Password
            };

            if (db.LoginPartnerAccount(partner) == true)
            {
                Session["PartnerAccount"] = db.Find(partner.partnerAccount).accountNumber;
                return(Json(new
                {
                    status = true
                }));
            }
            else
            {
                return(Json(new
                {
                    status = false
                }));
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RefreshTokenParameters" /> class.
 /// </summary>
 public RefreshTokenParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes)
     : base(account, environment, scopes)
 {
 }
 public void Create(PartnerAccount entity)
 {
     PartnerAccountRepository.Create(entity);
 }
        /// <summary>
        /// Performs the operations associated with the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            IPartner            partnerOperations;
            OrganizationProfile profile;
            PartnerAccount      account     = new PartnerAccount();
            PartnerEnvironment  environment = PartnerEnvironment.PublicEnvironments[Environment];

            PartnerService.Instance.EnforceMfa = (EnforceMFA.IsPresent && EnforceMFA.ToBool());

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

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

            account.SetProperty(PartnerAccountPropertyType.ApplicationId, PowerShellApplicationId);

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

                account.SetProperty(PartnerAccountPropertyType.ApplicationId, Credential.UserName);
                account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString());
            }
            else
            {
                account.Type = AccountType.User;
            }

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

            account.SetProperty(
                PartnerAccountPropertyType.Scope,
                ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase) ?
                $"{environment.AzureAdGraphEndpoint}/.default" :
                $"{environment.PartnerCenterEndpoint}/user_impersonation");

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

            PartnerSession.Instance.AuthenticationFactory.Authenticate(
                account,
                environment,
                new[] { account.GetProperty(PartnerAccountPropertyType.Scope) },
                Message);

            PartnerSession.Instance.Context = new PartnerContext
            {
                Account     = account,
                Environment = environment
            };

            try
            {
                partnerOperations = PartnerSession.Instance.ClientFactory.CreatePartnerOperations();
                profile           = partnerOperations.Profiles.OrganizationProfile.GetAsync().GetAwaiter().GetResult();

                PartnerSession.Instance.Context.CountryCode = profile.DefaultAddress.Country;
                PartnerSession.Instance.Context.Locale      = profile.Culture;
            }
            catch (PartnerException)
            {
                /* This error can safely be ignored */
            }

            WriteObject(PartnerSession.Instance.Context);
        }
 public void Update(PartnerAccount entity)
 {
     PartnerAccountRepository.Update(entity);
 }
Exemplo n.º 20
0
        /// <summary>
        /// Executes the operations associated with the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            Scheduler.RunTask(async() =>
            {
                IPartner partnerOperations;
                OrganizationProfile profile;
                PartnerAccount account         = new PartnerAccount();
                PartnerEnvironment environment = PartnerEnvironment.PublicEnvironments[Environment];

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

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

                account.SetProperty(PartnerAccountPropertyType.ApplicationId, string.IsNullOrEmpty(ApplicationId) ? PowerShellApplicationId : ApplicationId);

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

                    account.SetProperty(PartnerAccountPropertyType.ApplicationId, Credential.UserName);
                    account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString());
                }
                else
                {
                    account.Type = AccountType.User;
                }

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

                account.SetProperty(
                    PartnerAccountPropertyType.Scope,
                    ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase) ?
                    $"{environment.AzureAdGraphEndpoint}/.default" :
                    $"{environment.PartnerCenterEndpoint}/user_impersonation");

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

                await PartnerSession.Instance.AuthenticationFactory.AuthenticateAsync(
                    account,
                    environment,
                    new[] { account.GetProperty(PartnerAccountPropertyType.Scope) },
                    Message,
                    CancellationToken).ConfigureAwait(false);

                PartnerSession.Instance.Context = new PartnerContext
                {
                    Account     = account,
                    Environment = environment
                };

                try
                {
                    partnerOperations = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId).ConfigureAwait(false);
                    profile           = await partnerOperations.Profiles.OrganizationProfile.GetAsync().ConfigureAwait(false);

                    PartnerSession.Instance.Context.CountryCode = profile.DefaultAddress.Country;
                    PartnerSession.Instance.Context.Locale      = profile.Culture;
                }
                catch (PartnerException)
                {
                    /* This error can safely be ignored */
                }

                WriteObject(PartnerSession.Instance.Context);
            });
        }
        /// <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);
            });
        }
        /// <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>
 /// Initializes a new instance of the <see cref="ServicePrincipalParameters" /> class.
 /// </summary>
 public ServicePrincipalParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes)
     : base(account, environment, scopes)
 {
 }
Exemplo n.º 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InteractiveParameters" /> class.
 /// </summary>
 public InteractiveParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message)
     : base(account, environment, scopes)
 {
     Message = message;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DeviceCodeParameters" /> class.
 /// </summary>
 public DeviceCodeParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes)
     : base(account, environment, scopes)
 {
 }
Exemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthenticationParameters" /> class.
 /// </summary>
 protected AuthenticationParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes)
 {
     Account     = account;
     Environment = environment;
     Scopes      = scopes;
 }