Example #1
0
        private async Task<string> OAuthRequest(ICredential credentials, OAuthToken oAuthToken, string oauthUri)
        {
            try
            {
                string outUrl;
                string querystring;
                var nonce = GenerateNonce();
                var timeStamp = GenerateTimeStamp();
                var sig = GenerateSignature(new Uri(oauthUri),
                    credentials.ConsumerKey,
                    credentials.ConsumerSecret,
                    oAuthToken.TokenKey,
                    oAuthToken.TokenSecret,
                    "GET",
                    timeStamp,
                    nonce,
                    out outUrl,
                    out querystring);

                return await OAuthResponseGet(querystring, sig, outUrl);
            }
            catch (Exception e)
            {
                if (e is OAuthException)
                    throw;
                return string.Empty;
            }
        }
		/// <summary>
		/// Returns the 20 most recent mentions (tweets containing a users’s @screen_name) for the authenticating user.
		/// The timeline returned is the equivalent of the one seen when you view your mentions on twitter.com.
		/// This method can only return up to 800 tweets.
		/// </summary>
		/// <param name="count">Specifies the number of tweets to try and retrieve, up to a maximum of 200. The value of count is best thought of as a limit to the number of tweets to return because suspended or deleted content is removed after the count has been applied. We include retweets in the count, even if include_rts is not supplied. It is recommended you always send include_rts=1 when using this API method</param>
		/// <param name="since_id">Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available</param>
		/// <param name="max_id">Returns results with an ID less than (that is, older than) or equal to the specified ID</param>
		/// <param name="trim_user">When set to either true, t or 1, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object</param>
		/// <param name="contributor_details">This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included</param>
		/// <param name="include_entities">The entities node will be disincluded when set to false</param>
		public static Task<HttpResponseMessage> GetMentionsTimeline(
			this HttpClient client,
			ICredential consumerCredential,
			ICredential accessToken,
			int? count = null,
			int? since_id = null,
			int? max_id = null,
			bool trim_user = false,
			bool contributor_details = false,
			bool include_entities = true)
		{
			var parameters = new Dictionary<string, string>();

			#region Add Parameters
			if (count.HasValue) parameters.Add(nameof(count), count.Value.ToString());
			if (since_id.HasValue) parameters.Add(nameof(since_id), since_id.Value.ToString());
			if (max_id.HasValue) parameters.Add(nameof(max_id), max_id.Value.ToString());
			if (trim_user) parameters.Add(nameof(trim_user), trim_user.ToString());
			if (contributor_details) parameters.Add(nameof(contributor_details), contributor_details.ToString());
			if (!include_entities) parameters.Add(nameof(include_entities), include_entities.ToString());
			#endregion

			var uri = BuildUri("mentions_timeline.json", parameters);
			return client.AccessResourceAsync(
				uri,
				HttpMethod.Get,
				consumerCredential,
				accessToken,
				parameters);
		}
		public API_AmazonEC2(ICredential apiKey) 
		{
			DefaultRegion = "us-west-1";//"eu-west-1";
			if (apiKey.isNull())
				apiKey = ascx_AskUserForLoginDetails.ask();
			ApiKey = apiKey;
		}
Example #4
0
		/// <returns>An access token</returns>
		public async static Task<ICredential> ObtainAccessTokenAsync(
			this HttpClient httpClient, 
			Uri requestUri, 
			HttpMethod httpMethod, 
			ICredential consumerCredentials, 
			ICredential authorizationToken, 
			RequestToken requestToken)
		{
			var httpRequest = new HttpRequestMessage(httpMethod, requestUri);
			var parameters = new Dictionary<string, string>();

			string oauthHeader = parameters.GenerateOAuthHeader(
				httpMethod.Method,
				consumerCredentials.Key,
				consumerCredentials.Secret,
				requestUri,
				token: authorizationToken.Key,
				tokenSecret: requestToken.Secret,
				verifier: authorizationToken.Secret);

			httpRequest.Headers.Authorization = new AuthenticationHeaderValue("OAuth", oauthHeader);

			HttpResponseMessage response = await httpClient.SendAsync(httpRequest);
			string responseString = await response.Content.ReadAsStringAsync();
			
			return ParseAccessToken(responseString);
        }
 /// <see cref="ISmartLockCredentialsImpl.Load"/>
 public void Load(System.Action<Status, ICredential> callback, params string[] accountTypes)
 {
     if (sampleCredential == null)
     {
         sampleCredential = new Credential("*****@*****.**",
             "http://[email protected]",
             "Sample User", "password123", null);
     }
     callback(Status.Success, sampleCredential);
 }
        public TransitionPolicyControllerContext(IStateMachine stateMachine, IStateTransition currentTransition, ICredential credentialToApprov)
        {
            stateMachine.TestForArgumentNull();
            ControledMachine = stateMachine;

            currentTransition.TestForArgumentNull();
            _currentTransition = currentTransition;

            credentialToApprov.TestForArgumentNull();
            _credentialToApprov = credentialToApprov;
        }
Example #7
0
		static async Task Run()
		{			
			if (accessToken == null)
			{
				var authorizer = new Authorizer(consumerCredentials, new ConsoleWebAuthenticationBroker());
				accessToken = await authorizer.AuthorizeAsync(new TwitterUriSet());
			}
			
			var client = new HttpClient();
			var response = await client.GetUserTimelineAsync(consumerCredentials, accessToken, screen_name: "luzianz", count: 10, trim_user: true, exclude_replies: true);
			Console.WriteLine(await response.Content.ReadAsStringAsync());
		}
        /// <inheritdoc/>
        public bool IsSupported(ICredential credential, string serviceName)
        {
            if (credential == null || credential.ServiceCatalog == null)
            {
                return false;
            }

            var catalog = credential.ServiceCatalog;
            return
                catalog.Any(
                    s =>
                        string.Equals(s.Name, GetServiceName(serviceName), StringComparison.OrdinalIgnoreCase));
        }
 /// <inheritdoc/>
 public bool IsSupported(ICredential credential, string serviceName)
 {
     if (credential != null && credential.AuthenticationEndpoint != null)
     {
         //https://someidentityendpoint:35357/v2.0
         var endpointSegs = credential.AuthenticationEndpoint.Segments;
         if (endpointSegs.Count() == 2 && string.Equals(endpointSegs[1].Trim('/'), "v2.0", StringComparison.Ordinal))
         {
             return true;
         }
     }
     return false;
 }
        /// <inheritdoc/>
        public bool IsSupported(ICredential credential, string serviceName)
        {
            if (credential == null || credential.ServiceCatalog == null)
            {
                return false;
            }

            var catalog = credential.ServiceCatalog;
            return
                catalog.Any(
                    s =>
                        string.Equals(s.Name, GetServiceName(serviceName), StringComparison.OrdinalIgnoreCase) &&
                        s.Endpoints.Any(e => this.ListSupportedVersions().Contains(e.Version) || e.PublicUri.Contains("/v2")));
        }
Example #11
0
		public static bool TryGetCredential(this IConfiguration configuration, string key, out ICredential credential)
		{
			var section = configuration.GetSection(key);
			if (section["key"] != null && section["secret"] != null)
			{
				credential = new Credential(section["key"], section["secret"]);
				return true;
			}
			else
			{
				credential = null;
				return false;
			}
		}
        /// <see cref="ISmartLockCredentialsImpl.Delete"/>
        public void Delete(ICredential credential, Action<Status, ICredential> callback)
        {
            AndroidJavaClass supportClass = GetSupportClass();
            if (supportClass == null)
            {
                Debug.LogError("Cannot load java support class: " + SupportActivityClassname);
                callback(Status.Error, null);
                return;
            }

            AndroidJavaObject unityActivity = GetUnityActivity();
            if (unityActivity == null)
            {
                Debug.LogError("Cannot get Unity player activity");
                callback(Status.Error, null);
                return;
            }

            IntPtr methodId = AndroidJNI.GetStaticMethodID(supportClass.GetRawClass(),
                                  "doDelete",
                                  "(Landroid/app/Activity;" +
                                  "Lcom/google/smartlocksupport/SmartLockSupportResponseHandler;" +
                                  "Ljava/lang/String;" +
                                  "Ljava/lang/String;" +
                                  "Ljava/lang/String;)V");

            if (methodId.Equals(IntPtr.Zero))
            {
                Debug.LogError("Cannot find method doDelete in java support class");
                callback(Status.Error, null);
                return;
            }
            object[] objectArray = new object[5];
            jvalue[] jArgs;
            LoadCallback cb = new LoadCallback(callback);

            objectArray[0] = unityActivity;
            objectArray[1] = cb;
            objectArray[2] = credential.ID;
            objectArray[3] = credential.Password;
            objectArray[4] = credential.AccountType;
            jArgs = AndroidJNIHelper.CreateJNIArgArray(objectArray);

            AndroidJNI.CallStaticVoidMethod(supportClass.GetRawClass(), methodId, jArgs);

            Debug.Log("Done calling doDelete");
        }
Example #13
0
        public async Task Delete(UriString host)
        {
            //Logger.Trace("Delete: {0}", host);

            if (!await LoadCredentialHelper())
            {
                return;
            }

            await RunCredentialHelper(
                "erase",
                new string[] {
                String.Format("protocol={0}", host.Protocol),
                String.Format("host={0}", host.Host)
            }).StartAwait();

            credential = null;
        }
        /// <summary>
        ///     Opens a database to perform operations on.
        ///     This is the synchronous implementation.
        /// </summary>
        /// <parameters>
        /// <param name="credential">The credential used to open the database.</param>
        /// </parameters>
        /// <returns>
        ///     True if open succeeded. False if the operation failed.
        /// </returns>
        protected virtual bool ExecuteOpen(ICredential credential)
        {
            bool Success;

            if (Connector.Open(credential))
            {
                Debug.Assert(Connector.IsOpen);

                StartOperationThread();
                Success = true;
            }
            else
            {
                Success = false;
            }

            return(Success);
        }
Example #15
0
        public async Task GitHubHostProvider_GenerateCredentialAsync_OAuth_ReturnsCredential()
        {
            var input = new InputArguments(new Dictionary <string, string>
            {
                ["protocol"] = "https",
                ["host"]     = "github.com",
            });

            var expectedTargetUri = new Uri("https://github.com/");
            IEnumerable <string> expectedOAuthScopes = new[]
            {
                GitHubConstants.OAuthScopes.Repo,
                GitHubConstants.OAuthScopes.Gist,
                GitHubConstants.OAuthScopes.Workflow,
            };

            var tokenValue = "OAUTH-TOKEN";
            var response   = new OAuth2TokenResult(tokenValue, "bearer");

            var context = new TestCommandContext();

            var ghAuthMock = new Mock <IGitHubAuthentication>(MockBehavior.Strict);

            ghAuthMock.Setup(x => x.GetAuthenticationAsync(expectedTargetUri, It.IsAny <AuthenticationModes>()))
            .ReturnsAsync(new AuthenticationPromptResult(AuthenticationModes.OAuth));

            ghAuthMock.Setup(x => x.GetOAuthTokenAsync(expectedTargetUri, It.IsAny <IEnumerable <string> >()))
            .ReturnsAsync(response);

            var ghApiMock = new Mock <IGitHubRestApi>(MockBehavior.Strict);

            var provider = new GitHubHostProvider(context, ghApiMock.Object, ghAuthMock.Object);

            ICredential credential = await provider.GenerateCredentialAsync(input);

            Assert.NotNull(credential);
            Assert.Equal(Constants.OAuthTokenUserName, credential.UserName);
            Assert.Equal(tokenValue, credential.Password);

            ghAuthMock.Verify(
                x => x.GetOAuthTokenAsync(
                    expectedTargetUri, expectedOAuthScopes),
                Times.Once);
        }
        public override async Task <ICredential> GenerateCredentialAsync(InputArguments input)
        {
            ThrowIfDisposed();

            // We should not allow unencrypted communication and should inform the user
            if (StringComparer.OrdinalIgnoreCase.Equals(input.Protocol, "http"))
            {
                throw new Exception("Unencrypted HTTP is not supported for GitHub. Ensure the repository remote URL is using HTTPS.");
            }

            Uri targetUri = GetTargetUri(input);

            ICredential credentials = await _gitHubAuth.GetCredentialsAsync(targetUri);

            AuthenticationResult result = await _gitHubApi.AcquireTokenAsync(
                targetUri, credentials, null, GitHubCredentialScopes);

            if (result.Type == GitHubAuthenticationResultType.Success)
            {
                Context.Trace.WriteLine($"Token acquisition for '{targetUri}' succeeded");

                return(result.Token);
            }

            if (result.Type == GitHubAuthenticationResultType.TwoFactorApp ||
                result.Type == GitHubAuthenticationResultType.TwoFactorSms)
            {
                bool isSms = result.Type == GitHubAuthenticationResultType.TwoFactorSms;

                string authCode = await _gitHubAuth.GetAuthenticationCodeAsync(targetUri, isSms);

                result = await _gitHubApi.AcquireTokenAsync(
                    targetUri, credentials, authCode, GitHubCredentialScopes);

                if (result.Type == GitHubAuthenticationResultType.Success)
                {
                    Context.Trace.WriteLine($"Token acquisition for '{targetUri}' succeeded.");

                    return(result.Token);
                }
            }

            throw new Exception($"Interactive logon for '{targetUri}' failed.");
        }
Example #17
0
        public override bool CreateTables(ICredential credential)
        {
            string ConnectionString;
            string CommandString;

            try
            {
                ConnectionString = CredentialToConnectionString(credential, false);

                using (MySqlConnection RootConnection = new MySqlConnection(ConnectionString))
                {
                    RootConnection.Open();
                    ReadServerVersion(RootConnection);

                    CommandString = $"CREATE DATABASE IF NOT EXISTS {credential.Schema.Name} DEFAULT CHARACTER SET utf8;";
                    ExecuteCommand(RootConnection, CommandString);

                    CommandString = $"USE {credential.Schema.Name};";
                    ExecuteCommand(RootConnection, CommandString);

                    CreateSchemaTables(credential.Schema, RootConnection);

                    RootConnection.Close();
                }

                return(true);
            }
#if TRACE
            catch (ApplicationException)
            {
                throw;
            }
#endif
            catch (MySqlException e)
            {
                TraceMySqlException(e);
                return(false);
            }
            catch (Exception e)
            {
                TraceException(e);
                return(false);
            }
        }
Example #18
0
        public override bool Open(ICredential credential)
        {
            try
            {
                string ConnectionString = CredentialToConnectionString(credential, false);

                Connection = new MySqlConnection(ConnectionString);
                Connection.Open();

                if (IsOpen)
                {
                    ReadServerVersion(Connection);

                    string CreateCommandString = $"CREATE DATABASE IF NOT EXISTS {credential.Schema.Name} DEFAULT CHARACTER SET utf8;";
                    ExecuteCommand(Connection, CreateCommandString);

                    string UseCommandString = $"USE {credential.Schema.Name};";
                    ExecuteCommand(Connection, UseCommandString);

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
#if TRACE
            catch (ApplicationException)
            {
                throw;
            }
#endif
            catch (MySqlException e)
            {
                TraceMySqlException(e);
                return(false);
            }
            catch (Exception e)
            {
                TraceException(e);
                return(false);
            }
        }
Example #19
0
        public void AddOrUpdate(string key, ICredential credential)
        {
            byte[] passwordBytes = Encoding.UTF8.GetBytes(credential.Password);

            IntPtr passwordData = IntPtr.Zero;
            IntPtr itemRef      = IntPtr.Zero;

            try
            {
                // Check if an entry already exists in the keychain
                SecKeychainFindGenericPassword(
                    IntPtr.Zero, (uint)key.Length, key, (uint)credential.UserName.Length, credential.UserName,
                    out uint _, out passwordData, out itemRef);

                if (itemRef != IntPtr.Zero) // Update existing entry
                {
                    ThrowOnError(
                        SecKeychainItemModifyAttributesAndData(itemRef, IntPtr.Zero, (uint)passwordBytes.Length, passwordBytes),
                        "Could not update existing item"
                        );
                }
                else // Create new entry
                {
                    ThrowOnError(
                        SecKeychainAddGenericPassword(IntPtr.Zero, (uint)key.Length, key, (uint)credential.UserName.Length,
                                                      credential.UserName, (uint)passwordBytes.Length, passwordBytes, out itemRef),
                        "Could not create new item"
                        );
                }
            }
            finally
            {
                if (passwordData != IntPtr.Zero)
                {
                    SecKeychainItemFreeContent(IntPtr.Zero, passwordData);
                }

                if (itemRef != IntPtr.Zero)
                {
                    CFRelease(itemRef);
                }
            }
        }
Example #20
0
        public void GetPayloadForCertificate()
        {
            credential  = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), Constants.CertificateAPIUserName);
            soapHandler = new MerchantAPICallPreHandler(ConfigManager.Instance.GetProperties(), defaultSoapHandler, credential);
            string      payload             = soapHandler.GetPayload();
            XmlDocument xmlDoc              = GetXmlDocument(payload);
            XmlNodeList xmlNodeListUsername = xmlDoc.GetElementsByTagName("Username");

            Assert.IsTrue(xmlNodeListUsername.Count > 0);
            Assert.AreEqual(Constants.CertificateAPIUserName, xmlNodeListUsername[0].InnerXml);
            XmlNodeList xmlNodeListPassword = xmlDoc.GetElementsByTagName("Password");

            Assert.IsTrue(xmlNodeListPassword.Count > 0);
            Assert.AreEqual(Constants.CertificateAPIPassword, xmlNodeListPassword[0].InnerXml);
            XmlNodeList xmlNodeListRequest = xmlDoc.GetElementsByTagName("Request");

            Assert.IsTrue(xmlNodeListRequest.Count > 0);
            Assert.AreEqual("test", xmlNodeListRequest[0].InnerXml);
        }
Example #21
0
        public void BasicAuthentication_GetCredentials_NonDesktopSession_ResourceAndUserName_PasswordPromptReturnsCredentials()
        {
            const string testResource = "https://example.com";
            const string testUserName = "******";
            const string testPassword = "******";

            var context = new TestCommandContext {
                SessionManager = { IsDesktopSession = false }
            };

            context.Terminal.SecretPrompts["Password"] = testPassword;

            var basicAuth = new BasicAuthentication(context);

            ICredential credential = basicAuth.GetCredentials(testResource, testUserName);

            Assert.Equal(testUserName, credential.Account);
            Assert.Equal(testPassword, credential.Password);
        }
Example #22
0
        public void LoadCertificateCredential()
        {
            string apiUsername = Constants.CertificateAPIUserName;

            credentialMngr = CredentialManager.Instance;
            credential     = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), apiUsername);
            Assert.IsNotNull(credential);
#if NUnit
            Assert.IsInstanceOf <CertificateCredential>(credential);
#else
            Assert.IsInstanceOfType(credential, typeof(CertificateCredential));
#endif
            CertificateCredential certCredential = (CertificateCredential)credential;
            Assert.AreEqual(apiUsername, certCredential.UserName);
            Assert.AreEqual(Constants.CertificateAPIPassword, certCredential.Password);
            Assert.AreEqual(Path.GetFileName(Constants.CertificatePath), Path.GetFileName(certCredential.CertificateFile));
            Assert.AreEqual(Constants.CertificatePassword, certCredential.PrivateKeyPassword);
            Assert.AreEqual(Constants.ApplicationId, certCredential.ApplicationId);
        }
        public static IBucketClient CreateClient(CloudServiceProvider service, ICredential credential)
        {
            HttpClient httpClient = new HttpClient();

            switch (service)
            {
            case CloudServiceProvider.AWS:
                if (!(credential is AWSCredential))
                {
                    throw new ArgumentException("AWS needs AWSCredential!");
                }
                AWSCredential aws = credential as AWSCredential;
                return(new AWSBucketClient(httpClient, aws.accessKeyID, aws.accessKeySecret, aws.region));

            case CloudServiceProvider.Azure:
                if (!(credential is AzureCredential))
                {
                    throw new ArgumentException("Azure needs AzureCredential!");
                }
                AzureCredential azure = credential as AzureCredential;
                return(new AzureBucketClient(azure.AccountName, azure.Secret));

            case CloudServiceProvider.GCP:
                if (!(credential is GCPCredential))
                {
                    throw new ArgumentException("Google Cloud Platform needs GCPCredential!");
                }
                GCPCredential gcp = credential as GCPCredential;
                return(new GCPBucketClient(gcp.projectID, gcp.secretJSON));

            case CloudServiceProvider.DigitalOcean:
                if (!(credential is DigitalOceanCredential))
                {
                    throw new ArgumentException("Digital Ocean needs DigitalOceanCredential!");
                }
                DigitalOceanCredential DO = credential as DigitalOceanCredential;
                return(new DigitalOceanBucketClient(httpClient, DO.accessKeyID, DO.accessKeySecret, DO.region));

            case CloudServiceProvider.AliCloud:
                throw new NotImplementedException();
            }
            return(null);
        }
Example #24
0
        /// <summary>
        /// This method deletes (un-enrolls) specific credentials for specific user and remove credential data from Altus (DA) database.
        /// </summary>
        /// <param name="officerTicket">JSON Web Token of Security Officer.</param>
        /// <param name="owner">JSON Web Token of the owner of credentials. </param>
        /// <param name="credential">Credential to be deleted. </param>
        /// <remarks>
        /// DeleteUserCredentials method deletes (un-enrolls) specific credentials for specific user and remove credential data from Altus (DA) database.
        /// This method will work for both Altus and Altus AD backend servers.
        ///
        /// Security Officer should use DigitalPersona Web AUTH Service to authenticate itself and acquire this token.
        /// Token must be valid to call succeed. To be valid token must be:
        /// 1) issued no longer than 10 minutes before the operation,
        /// 2) one of the Primary credentials must be used to acquire this token and
        /// 3) token owner must have a rights to enroll user in Altus (AD LDS) or Altus AD (Active Directory) database.
        ///  NOTE: This parameter is optional. If user has rights to enroll himself (self-enrollment allowed), caller may provide "null" to this parameter.
        ///
        /// User should use DigitalPersona Web AUTH Service to authenticate itself and acquire this token.
        /// Token must be valid to call succeeded. To be valid token must be:
        /// 1) issued no longer than 10 minutes before the operation,
        /// 2) one of the Primary credentials (or same credentials) must be used to acquire this token.
        /// </remarks>
        public async Task DeleteCredential(Ticket officerTicket, Ticket owner, ICredential credential)
        {
            if (officerTicket == null)
            {
                throw new ArgumentNullException("officerTicket");
            }

            if (owner == null)
            {
                throw new ArgumentNullException("owner");
            }

            if (credential == null)
            {
                throw new ArgumentNullException("credential");
            }

            await DeleteCredentialCore(officerTicket, owner, credential);
        }
Example #25
0
        public void GnuPassCredentialStore_ReadWriteDelete()
        {
            var    fs        = new TestFileSystem();
            var    gpg       = new TestGpg(fs);
            string storeRoot = InitializePasswordStore(fs, gpg);

            var collection = new GpgPassCredentialStore(fs, gpg, storeRoot, TestNamespace);

            // Create a service that is guaranteed to be unique
            string       uniqueGuid = Guid.NewGuid().ToString("N");
            string       service    = $"https://example.com/{uniqueGuid}";
            const string userName   = "******";
            const string password   = "******"; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="Fake credential")]

            string expectedSlug         = $"{TestNamespace}/https/example.com/{uniqueGuid}/{userName}.gpg";
            string expectedFilePath     = Path.Combine(storeRoot, expectedSlug);
            string expectedFileContents = password + Environment.NewLine +
                                          $"service={service}" + Environment.NewLine +
                                          $"account={userName}" + Environment.NewLine;

            byte[] expectedFileBytes = Encoding.UTF8.GetBytes(expectedFileContents);

            try
            {
                // Write
                collection.AddOrUpdate(service, userName, password);

                // Read
                ICredential outCredential = collection.Get(service, userName);

                Assert.NotNull(outCredential);
                Assert.Equal(userName, userName);
                Assert.Equal(password, outCredential.Password);
                Assert.True(fs.Files.ContainsKey(expectedFilePath));
                Assert.Equal(expectedFileBytes, fs.Files[expectedFilePath]);
            }
            finally
            {
                // Ensure we clean up after ourselves even in case of 'get' failures
                collection.Remove(service, userName);
            }
        }
        /// <summary>
        /// Авторизация на сайте. При успешной авторизации инициализирует FomsCodeMO.
        /// </summary>
        /// <param name="credential">Учетные данные.</param>
        /// <returns>true-в случае успешной авторизации, false-иначе.</returns>
        public async Task <bool> AuthorizeAsync(ICredential credential)
        {
            var requestValues = new Dictionary <string, string> {
                { "Login", credential.Login },
                { "Password", credential.Password }
            };

            var responseText = await SendPostAsync(@"account/login", requestValues);

            if (!string.IsNullOrEmpty(responseText) && !responseText.Contains(@"<li>Пользователь не найден</li>"))
            {
                FomsCodeMO = responseText.SubstringBetween("<div>", "<div>", "</div>");
                return(IsAuthorized = true);
            }
            else
            {
                FomsCodeMO = null;
                return(IsAuthorized = false);
            }
        }
Example #27
0
        public bool ChangePassword(ICredential credential, string newPassword)
        {
            var testIdentity = GetIdentity(credential.Identity);

            if (testIdentity == null)
            {
                return(false);
            }

            var foundCredential = _credentials.FirstOrDefault(c => string.Equals(c.Username, credential.Username));

            if (foundCredential == null)
            {
                return(false);
            }

            foundCredential.Password = newPassword;

            return(true);
        }
        public void BasicAuthentication_GetCredentials_NonDesktopSession_Resource_UserPassPromptReturnsCredentials()
        {
            const string testResource = "https://example.com";
            const string testUserName = "******";
            const string testPassword = "******"; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="Fake credential")]

            var context = new TestCommandContext {
                SessionManager = { IsDesktopSession = false }
            };

            context.Terminal.Prompts["Username"]       = testUserName;
            context.Terminal.SecretPrompts["Password"] = testPassword; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="Fake credential")]

            var basicAuth = new BasicAuthentication(context);

            ICredential credential = basicAuth.GetCredentials(testResource);

            Assert.Equal(testUserName, credential.Account);
            Assert.Equal(testPassword, credential.Password);
        }
Example #29
0
        public ILoginMessages LoginUser(string userName, string password)
        {
            ICredential result = UserDAL.GetUserCredentials(userName);

            if (result.Success)
            {
                IIdentity        identity  = new CustomIdentity(true, userName);
                ICustomPrincipal principal = new CustomPrincipal(identity, result.UserId, result.UserName, result.UserRoles);
                var message = new LoginMessages {
                    LoginResult = LoginAttempts.Success, Message = string.Empty, Principal = principal
                };
                return(message);
            }
            else
            {
                return(new LoginMessages {
                    LoginResult = LoginAttempts.UnknownUser, Message = "User could not be found."
                });
            }
        }
Example #30
0
        private DatabaseConnectionModel GetDatabaseConnectionModel(ICredential credential)
        {
            try
            {
                var result = new DatabaseConnectionModel
                {
                    ConnectionName   = credential.TargetName.Substring(5),
                    ConnectionString = credential.ToNetworkCredential().Password,
                    DatabaseType     = (DatabaseType)credential.Attributes[nameof(DatabaseType)],
                };

                return(result);
            }
            catch
            {
                // Ignore
            }

            return(null);
        }
Example #31
0
        /// <summary>
        /// Add a credential that is used for this request only.
        /// This will override a service-level credential (if there is one).
        /// Do not call more than once per request instance, as each call incrementally adds the provided credential.
        /// To perform identical requests but with distinct credentials, create a separate request instance for each credential.
        /// </summary>
        /// <typeparam name="T">The request type.</typeparam>
        /// <param name="request">The request which requires a credential. Must not be null.</param>
        /// <param name="credential">The credential to use for this request only. Must not be null.</param>
        /// <returns></returns>
        public static T AddCredential <T>(this T request, ICredential credential) where T : ClientServiceRequest
        {
            request.ThrowIfNull(nameof(request));
            credential.ThrowIfNull(nameof(credential));
            // Get underlying credential if passed credential is a GoogleCredential.
            if (credential is GoogleCredential googleCredential)
            {
                credential = googleCredential.UnderlyingCredential;
            }
            // Add the required execute interceptor to this request.
            var httpExecuteInterceptor = credential as IHttpExecuteInterceptor;

            if (httpExecuteInterceptor == null)
            {
                throw new ArgumentException("Credential must implement IHttpExecuteInterceptor.", nameof(credential));
            }
            request.Credential = httpExecuteInterceptor;

            return(request);
        }
Example #32
0
        public async Task<OAuthToken> XAuthAccessTokenRequest(string username, string password, ICredential credentials, string xauthUri)
        {
            try
            {
                string outUrl;
                string querystring;
                var nonce = GenerateNonce();
                var timeStamp = GenerateTimeStamp();
                var sig = GenerateSignature(new Uri(xauthUri),
                    credentials.ConsumerKey,
                    credentials.ConsumerSecret,
                    string.Empty,
                    string.Empty,
                    string.Empty,
                    username,
                    password,
                    "GET",
                    timeStamp,
                    nonce,
                    out outUrl,
                    out querystring);

                var responseData = await OAuthResponseGet(querystring, sig, outUrl);

                if (responseData.Length > 0)
                {
                    var qs = GetQueryParameters(responseData);
                    if (qs["oauth_token"] != null && qs["oauth_token_secret"] != null)
                    {
                        return new OAuthToken {TokenKey = qs["oauth_token"], TokenSecret = qs["oauth_token_secret"]};
                    }
                }
            }
            catch (Exception e)
            {
                if (e is OAuthException)
                    throw;
                return new OAuthToken();
            }
            return new OAuthToken();
        }
        public static string GetProjectId()
        {
            var envVar = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_PROJECT");

            if (envVar != null)
            {
                return(envVar);
            }
            // Use the service account credentials, if present.
            GoogleCredential googleCredential = Google.Apis.Auth.OAuth2
                                                .GoogleCredential.GetApplicationDefault();

            if (googleCredential != null)
            {
                ICredential credential = googleCredential.UnderlyingCredential;
                ServiceAccountCredential serviceAccountCredential =
                    credential as ServiceAccountCredential;
                if (serviceAccountCredential != null)
                {
                    return(serviceAccountCredential.ProjectId);
                }
            }
            try
            {
                // Query the metadata server.
                HttpClient http = new HttpClient();
                http.DefaultRequestHeaders.Add("Metadata-Flavor", "Google");
                http.BaseAddress = new Uri(
                    @"http://metadata.google.internal/computeMetadata/v1/project/");
                return(http.GetStringAsync("project-id").Result);
            }
            catch (AggregateException e)
                when(e.InnerException is HttpRequestException)
                {
                    throw new Exception("Could not find Google project id.  " +
                                        "Run this application in Google Cloud or follow these " +
                                        "instructions to run locally: " +
                                        "https://cloud.google.com/docs/authentication/getting-started",
                                        e.InnerException);
                }
        }
Example #34
0
        public Tuple <bool, string> EnsureSignedIn(ICredential credential, bool alwaysShowWindow = false)
        {
            Credential = credential;

            if (Credential == null)
            {
                IsSignedIn = false;
                return(new Tuple <bool, string>(IsSignedIn, PluginResources.Message_Invalid_credentials));
            }

            var result = Connect(Credential);

            if (result.Item1 && !alwaysShowWindow)
            {
                return(result);
            }

            Mouse.OverrideCursor = Cursors.Arrow;

            var credentialsWindow = GetCredentialsWindow(Owner);
            var viewModel         = new CredentialsViewModel(credentialsWindow, this);

            credentialsWindow.DataContext = viewModel;

            var message = string.Empty;
            var result1 = credentialsWindow.ShowDialog();

            if (result1.HasValue && result1.Value)
            {
                message    = viewModel.ExceptionMessage;
                IsSignedIn = viewModel.IsSignedIn;
            }
            else
            {
                IsSignedIn           = false;
                Credential.Token     = string.Empty;
                Credential.AccountId = string.Empty;
            }

            return(new Tuple <bool, string>(IsSignedIn, message));
        }
Example #35
0
        public async Task AzureReposProvider_GetCredentialAsync_ReturnsCredential()
        {
            var input = new InputArguments(new Dictionary <string, string>
            {
                ["protocol"] = "https",
                ["host"]     = "dev.azure.com",
                ["path"]     = "org/proj/_git/repo"
            });

            var expectedOrgUri      = new Uri("https://dev.azure.com/org");
            var remoteUri           = new Uri("https://dev.azure.com/org/proj/_git/repo");
            var authorityUrl        = "https://login.microsoftonline.com/common";
            var expectedClientId    = AzureDevOpsConstants.AadClientId;
            var expectedRedirectUri = AzureDevOpsConstants.AadRedirectUri;
            var expectedScopes      = AzureDevOpsConstants.AzureDevOpsDefaultScopes;
            var accessToken         = "ACCESS-TOKEN";
            var personalAccessToken = "PERSONAL-ACCESS-TOKEN";
            var authResult          = CreateAuthResult("john.doe", accessToken);

            var context = new TestCommandContext();

            var azDevOpsMock = new Mock <IAzureDevOpsRestApi>();

            azDevOpsMock.Setup(x => x.GetAuthorityAsync(expectedOrgUri))
            .ReturnsAsync(authorityUrl);
            azDevOpsMock.Setup(x => x.CreatePersonalAccessTokenAsync(expectedOrgUri, accessToken, It.IsAny <IEnumerable <string> >()))
            .ReturnsAsync(personalAccessToken);

            var msAuthMock = new Mock <IMicrosoftAuthentication>();

            msAuthMock.Setup(x => x.GetTokenAsync(authorityUrl, expectedClientId, expectedRedirectUri, expectedScopes, null))
            .ReturnsAsync(authResult);

            var provider = new AzureReposHostProvider(context, azDevOpsMock.Object, msAuthMock.Object);

            ICredential credential = await provider.GetCredentialAsync(input);

            Assert.NotNull(credential);
            Assert.Equal(personalAccessToken, credential.Password);
            // We don't care about the username value
        }
Example #36
0
        public async Task GitHubHostProvider_GenerateCredentialAsync_1FAOnly_ReturnsCredential()
        {
            var input = new InputArguments(new Dictionary <string, string>
            {
                ["protocol"] = "https",
                ["host"]     = "github.com",
            });

            var expectedTargetUri = new Uri("https://github.com/");
            var expectedUserName  = "******";
            var expectedPassword  = "******";
            IEnumerable <string> expectedPatScopes = new[]
            {
                GitHubConstants.TokenScopes.Repo,
                GitHubConstants.TokenScopes.Gist
            };

            var patValue = "PERSONAL-ACCESS-TOKEN";
            var pat      = new GitCredential(Constants.PersonalAccessTokenUserName, patValue);
            var response = new AuthenticationResult(GitHubAuthenticationResultType.Success, pat);

            var context = new TestCommandContext();

            var ghAuthMock = new Mock <IGitHubAuthentication>(MockBehavior.Strict);

            ghAuthMock.Setup(x => x.GetCredentialsAsync(expectedTargetUri))
            .ReturnsAsync(new GitCredential(expectedUserName, expectedPassword));

            var ghApiMock = new Mock <IGitHubRestApi>(MockBehavior.Strict);

            ghApiMock.Setup(x => x.AcquireTokenAsync(expectedTargetUri, expectedUserName, expectedPassword, null, It.IsAny <IEnumerable <string> >()))
            .ReturnsAsync(response);

            var provider = new GitHubHostProvider(context, ghApiMock.Object, ghAuthMock.Object);

            ICredential credential = await provider.GenerateCredentialAsync(input);

            Assert.NotNull(credential);
            Assert.Equal(Constants.PersonalAccessTokenUserName, credential.UserName);
            Assert.Equal(patValue, credential.Password);
        }
        private IEnumerable <Google.Apis.Calendar.v3.Data.Event> GetCalendarEvents(ICredential credential, string calendarId, DateTime min, DateTime max, int maxResults = 10)
        {
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Doccer Bot calendar sync",
            });

            EventsResource.ListRequest request = service.Events.List(calendarId);

            request.TimeMin      = min;
            request.TimeMax      = max;
            request.ShowDeleted  = false;
            request.SingleEvents = true;
            request.MaxResults   = maxResults;
            request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

            var events = request.Execute()?.Items;

            return(events);
        }
Example #38
0
        protected override INetworkStream ConnectToWebServer(
            InstanceLocator vmRef,
            ICredential credential)
        {
            var listener = SshRelayListener.CreateLocalListener(
                new IapTunnelingEndpoint(
                    credential,
                    vmRef,
                    80,
                    IapTunnelingEndpoint.DefaultNetworkInterface,
                    TestProject.UserAgent));

            listener.ClientAcceptLimit = 1; // Terminate after first connection.
            listener.ListenAsync(CancellationToken.None);

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(new IPEndPoint(IPAddress.Loopback, listener.LocalPort));

            return(new SocketStream(socket));
        }
Example #39
0
		public async static Task<HttpResponseMessage> AccessResourceAsync(
			this HttpClient httpClient,
			Uri resourceUri,
			HttpMethod httpMethod,
			ICredential consumerCredentials,
			ICredential accessToken,
			Dictionary<string, string> parameters)
		{
			var httpRequest = new HttpRequestMessage(httpMethod, resourceUri);
			string oauthHeader = parameters.GenerateOAuthHeader(
				httpMethod: httpMethod.Method,
				consumerKey: consumerCredentials.Key,
				consumerSecret: consumerCredentials.Secret,
				requestUrl: resourceUri,
				token: accessToken.Key,
				tokenSecret: accessToken.Secret);

			httpRequest.Headers.Authorization = new AuthenticationHeaderValue("OAuth", oauthHeader);

			return await httpClient.SendAsync(httpRequest);
		}
Example #40
0
        public void MacOSKeychain_ReadWriteDelete()
        {
            var keychain = new MacOSKeychain(TestNamespace);

            // Create a service that is guaranteed to be unique
            string       service  = $"https://example.com/{Guid.NewGuid():N}";
            const string account  = "john.doe";
            const string password = "******"; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="Fake credential")]

            try
            {
                // Write
                keychain.AddOrUpdate(service, account, password);

                // Read
                ICredential outCredential = keychain.Get(service, account);

                Assert.NotNull(outCredential);
                Assert.Equal(account, outCredential.Account);
                Assert.Equal(password, outCredential.Password);
            }
            // There is an unknown issue that the keychain can sometimes get itself in where all API calls
            // result in an errSecAuthFailed error. The only solution seems to be a machine restart, which
            // isn't really possible in CI!
            // The problem has plagued others who are calling the same Keychain APIs from C# such as the
            // MSAL.NET team - they don't know either. It might have something to do with the code signing
            // signature of the binary (our collective best theory).
            // It's probably only diagnosable at this point by Apple, but we don't have a reliable way to
            // reproduce the problem.
            // For now we will just mark the test as "skipped" when we hit this problem.
            catch (InteropException iex) when(iex.ErrorCode == SecurityFramework.ErrorSecAuthFailed)
            {
                AssertEx.Skip("macOS Keychain is in an invalid state (errSecAuthFailed)");
            }
            finally
            {
                // Ensure we clean up after ourselves even in case of 'get' failures
                keychain.Remove(service, account);
            }
        }
Example #41
0
        /// <summary>
        /// Returns the API Credentials
        /// </summary>
        /// <param name="apiUserName"></param>
        /// <returns></returns>
        public ICredential GetCredentials(Dictionary <string, string> config, string apiUserName)
        {
            ICredential credential = null;
            Account     accnt      = GetAccount(config, apiUserName);

            if (accnt == null)
            {
                throw new MissingCredentialException("Missing credentials for " + apiUserName);
            }
            if (!string.IsNullOrEmpty(accnt.APICertificate))
            {
                CertificateCredential certCredential = new CertificateCredential(accnt.APIUserName, accnt.APIPassword, accnt.APICertificate, accnt.PrivateKeyPassword);
                certCredential.ApplicationId = accnt.ApplicationId;
                if (!string.IsNullOrEmpty(accnt.CertificateSubject))
                {
                    SubjectAuthorization subAuthorization = new SubjectAuthorization(accnt.CertificateSubject);
                    certCredential.ThirdPartyAuthorization = subAuthorization;
                }
                credential = certCredential;
            }
            else
            {
                SignatureCredential signCredential = new SignatureCredential(accnt.APIUserName, accnt.APIPassword, accnt.APISignature);
                signCredential.ApplicationId = accnt.ApplicationId;
                if (!string.IsNullOrEmpty(accnt.SignatureSubject))
                {
                    SubjectAuthorization subjectAuthorization = new SubjectAuthorization(accnt.SignatureSubject);
                    signCredential.ThirdPartyAuthorization = subjectAuthorization;
                }
                if (!string.IsNullOrEmpty(accnt.CertificateSubject))
                {
                    SubjectAuthorization subAuthorization = new SubjectAuthorization(accnt.CertificateSubject);
                    signCredential.ThirdPartyAuthorization = subAuthorization;
                }
                credential = signCredential;
            }
            ValidateCredentials(credential);

            return(credential);
        }
        public void WindowsCredentialManager_ReadWriteDelete()
        {
            WindowsCredentialManager credManager = WindowsCredentialManager.OpenDefault();

            const string key        = "secretkey";
            const string userName   = "******";
            const string password   = "******";
            var          credential = new Credential(userName, password);

            // Write
            credManager.AddOrUpdate(key, credential);

            // Read
            ICredential outCredential = credManager.Get(key);

            Assert.NotNull(outCredential);
            Assert.Equal(credential.UserName, outCredential.UserName);
            Assert.Equal(credential.Password, outCredential.Password);

            // Delete
            credManager.Remove(key);
        }
        public void MacOSKeychain_ReadWriteDelete()
        {
            MacOSKeychain keychain = MacOSKeychain.OpenDefault();

            const string key        = "secretkey";
            const string userName   = "******";
            const string password   = "******";
            var          credential = new Credential(userName, password);

            // Write
            keychain.AddOrUpdate(key, credential);

            // Read
            ICredential outCredential = keychain.Get(key);

            Assert.NotNull(outCredential);
            Assert.Equal(credential.UserName, outCredential.UserName);
            Assert.Equal(credential.Password, outCredential.Password);

            // Delete
            keychain.Remove(key);
        }
Example #44
0
        private async Task DeleteCredentialCore(Ticket officerTicket, Ticket owner, ICredential credential)
        {
            try
            {
                var request = HttpHelper.CreateHttpRequest(GetRequestUri("/DeleteUserCredentials"), RequestMethod.Delete);

                var postParameters = new List <BodyParameter>
                {
                    new BodyParameter("secOfficer", officerTicket),
                    new BodyParameter("owner", owner),
                    new BodyParameter("credential", credential)
                };

                await request.WritePostParameters(postParameters.ToArray());

                await request.GetResponseData();
            }
            catch (WebException ex)
            {
                throw GetServiceException(ex);
            }
        }
 public void GetHeaderMapSignature()
 {
     credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), Constants.APIUserName);
     soapHandler = new MerchantAPICallPreHandler(ConfigManager.Instance.GetProperties(), defaultSoapHandler, credential);
     Dictionary<string, string> headers = soapHandler.GetHeaderMap();
     Assert.IsNotNull(headers);
     Assert.IsTrue(headers.Count > 0);
     Assert.AreEqual(Constants.APIUserName, headers[BaseConstants.PayPalSecurityUserIdHeader]);
     Assert.AreEqual(Constants.APIPassword, headers[BaseConstants.PayPalSecurityPasswordHeader]);
     Assert.AreEqual(Constants.APISignature, headers[BaseConstants.PayPalSecuritySignatureHeader]);
     Assert.AreEqual(BaseConstants.SOAP, headers[BaseConstants.PayPalRequestDataFormatHeader]);
     Assert.AreEqual(BaseConstants.SOAP, headers[BaseConstants.PayPalResponseDataFormatHeader]);
 }
Example #46
0
 public void SetCredential(ICredential credential)
 {
     return;
 }
 	public static API_WordPress login(this API_WordPress wpApi, ICredential credential)
 	{
 		return wpApi.login(credential.UserName,credential.Password);
 	}
 public void GetEndpoint()
 {
     credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), Constants.CertificateAPIUserName);
     MerchantAPICallPreHandler soapHandler = new MerchantAPICallPreHandler(ConfigManager.Instance.GetProperties(), defaultSoapHandler, credential);
     string endpoint = soapHandler.GetEndpoint();
     Assert.AreEqual(Constants.APIEndpointNVP, endpoint);
 }
        public void GetEndpointForDefaultModeWithExplicitEndpoint()
        {
            Dictionary<string, string> config = new Dictionary<string, string>(accountConfig);
            config.Add(BaseConstants.EndpointConfig, Constants.APIEndpointNVP);

            credential = credentialMngr.GetCredentials(config, Constants.CertificateAPIUserName);
            MerchantAPICallPreHandler soapHandler = new MerchantAPICallPreHandler(config, defaultSoapHandler, credential);
            Assert.AreEqual(Constants.APIEndpointNVP, soapHandler.GetEndpoint());

            config.Add("PayPalAPI", Constants.APIEndpointSOAP);
            credential = credentialMngr.GetCredentials(config, Constants.CertificateAPIUserName);
            soapHandler = new MerchantAPICallPreHandler(config, defaultSoapHandler, credential);
            soapHandler.PortName = "PayPalAPI";
            Assert.AreEqual(Constants.APIEndpointSOAP, soapHandler.GetEndpoint());
        }
 /// <summary>Creates a new <c>GoogleCredential</c>.</summary>
 internal GoogleCredential(ICredential credential)
 {
     this.credential = credential;
 }
 public EchoServiceClient(ICredential credential, CancellationToken token, IServiceLocator serviceLocator)
 {
     this.ServiceLocator = serviceLocator;
 }
Example #52
0
 /// <summary>
 /// Sets a user as the credential.
 /// </summary>
 public void SetUser(String username, String password)
 {
     _credential = new UserCredential(username, password);
 }
        public void GetEndpointForDefaultModeWithoutEndpoint()
        {
            Dictionary<string, string> config = new Dictionary<string, string>(accountConfig);

            credential = credentialMngr.GetCredentials(config, Constants.CertificateAPIUserName);
            MerchantAPICallPreHandler soapHandler = new MerchantAPICallPreHandler(config, defaultSoapHandler, credential);
            soapHandler.GetEndpoint();
        }
        public void GetEndpointForSandboxMode()
        {
            Dictionary<string, string> config = new Dictionary<string, string>(accountConfig);
            config.Add(BaseConstants.ApplicationModeConfig, BaseConstants.LiveMode);

            credential = credentialMngr.GetCredentials(config, Constants.CertificateAPIUserName);
            MerchantAPICallPreHandler soapHandler = new MerchantAPICallPreHandler(config, defaultSoapHandler, credential);
            Assert.AreEqual(BaseConstants.MerchantCertificateLiveEndpoint, soapHandler.GetEndpoint());

            credential = credentialMngr.GetCredentials(config, Constants.APIUserName);
            soapHandler = new MerchantAPICallPreHandler(config, defaultSoapHandler, credential);
            Assert.AreEqual(BaseConstants.MerchantSignatureLiveEndpoint, soapHandler.GetEndpoint());
        }
    	public API_Blogger login(ICredential credential)
    	{    	
    		if (credential == null)
    			credential = IE.askUserForUsernameAndPassword();      	
    		this.Credential = credential;
    		IE.open(LoginPage);     		
    		if (IE.url() == LoginPage && IE.title()== ExpectedTitle_LoginPage)
    		{
    			if (IE.hasButton("Sign in"))
    			{
    				IE.set_Value("Email",this.Credential.username());
    				IE.set_Value("Passwd",this.Credential.password());    			
    				IE.click("Sign in");    				   				   				   			
    			}
    		}
    		if (inDashBoard())
			{
				UserBlogMainPage =  IE.link("View Blog").url();
				"[BloggerAPI]: logged in as user :{0}".info(this.Credential.username());
				LoggedIn = true;
				return this;
			}
			this.Credential = null;
    		"[BloggerAPI]: an error occured during the login process".error();	
			return this;
    	}
 public void GetPayloadSignature()
 {
     credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), Constants.APIUserName);
     soapHandler = new MerchantAPICallPreHandler(ConfigManager.Instance.GetProperties(), defaultSoapHandler, credential);
     string payload = soapHandler.GetPayload();
     XmlDocument xmlDoc = GetXmlDocument(payload);
     XmlNodeList xmlNodeListUsername = xmlDoc.GetElementsByTagName("Username");
     Assert.IsTrue(xmlNodeListUsername.Count > 0);
     Assert.AreEqual(Constants.APIUserName, xmlNodeListUsername[0].InnerXml);
     XmlNodeList xmlNodeListPassword = xmlDoc.GetElementsByTagName("Password");
     Assert.IsTrue(xmlNodeListPassword.Count > 0);
     Assert.AreEqual(Constants.APIPassword, xmlNodeListPassword[0].InnerXml);
     XmlNodeList xmlNodeListSignature = xmlDoc.GetElementsByTagName("Signature");
     Assert.IsTrue(xmlNodeListSignature.Count > 0);
     Assert.AreEqual(Constants.APISignature, xmlNodeListSignature[0].InnerXml);
     XmlNodeList xmlNodeListRequest = xmlDoc.GetElementsByTagName("Request");
     Assert.IsTrue(xmlNodeListRequest.Count > 0);
     Assert.AreEqual("test", xmlNodeListRequest[0].InnerXml);
 }
Example #57
0
 /// <summary>
 /// Sets a API key as the credential.
 /// </summary>
 public void SetApiKey(String apiKey)
 {
     _credential = new ApiKeyCredential(apiKey);
 }
 public void SDKVersion()
 {
     credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), Constants.CertificateAPIUserName);
     MerchantAPICallPreHandler soapHandler = new MerchantAPICallPreHandler(ConfigManager.Instance.GetProperties(), defaultSoapHandler, credential);
     soapHandler.SDKVersion = "1.0.0";
     Assert.AreEqual("1.0.0", soapHandler.SDKVersion);
 }
 public bool IsSupported(ICredential credential, string serviceName)
 {
     return true;
 }
 public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator)
 {
     return new EchoServiceClient(credential, cancellationToken, serviceLocator);
 }