public SqlGetDatabaseFromProcedureWorker(string server, AuthenticationType authenticationType, string user, string password, string version, out ISqlGetDatabaseFromProcedureWorkerReturnedData data) : base(server, "", authenticationType, user, password) { data = this.data = new SqlGetDatabaseFromProcedureWorkerReturnedData(); this.version = version; }
protected bool InitializeClient(AuthenticationType authType, EventHandler<AuthorizationCodeRequiredEventArgs> codeRequiredHandler, Guid clientId = default(Guid), string clientSecret = null) { var s = GetSettings(); if (!s.IsConfigured) return false; lock (_lck) { if (_aaClient == null || _settings == null || _clientSecret != clientSecret || _clientId != clientId || _settings.LastChanged < s.LastChanged ) { if (authType == AuthenticationType.Code) { clientId = s.UserAppId; if (clientId == default(Guid)) clientId = Parameters.CLIENT_ID; } _aaClient = new AAClient(s.TenantId, s.SubscriptionId, s.ResourceGroupName, s.AutomationAccountName, authType, clientId, clientSecret); if (authType == AuthenticationType.Code) _aaClient.AuthorizationCodeRequired += codeRequiredHandler; _clientSecret = clientSecret; _settings = s; _isInitialized = true; } } return true; }
/// <summary> /// Inicializa un nuevo cliente con la clavede acceso, la clave secreta, el tipo de autenticación y la url base /// </summary> /// <param name="accessKey"></param> /// <param name="secretKey"></param> /// <param name="authenticationScheme"></param> /// <param name="baseUrl"></param> public EffiPeopleRestClient(string accessKey, string secretKey, AuthenticationType authenticationScheme, string baseUrl) : base(baseUrl) { _accessKey = accessKey; _secretKey = secretKey; _authenticationScheme = authenticationScheme; }
/// <summary> /// Inicializa un nuevo cliente con la clavede acceso, la clave secreta y el tipo de autenticación /// </summary> /// <param name="accessKey"></param> /// <param name="secretKey"></param> /// <param name="authenticationScheme"></param> public EffiPeopleRestClient(string accessKey, string secretKey, AuthenticationType authenticationScheme) : base("https://api.effipeople.com/v1") { _accessKey = accessKey; _secretKey = secretKey; _authenticationScheme = authenticationScheme; }
public AppManager(string sharePointUrl, AuthenticationType authenticationType, string userName, SecureString password) { this.sharePointUrl = sharePointUrl; this.authenticationType = authenticationType; this.userName = userName; this.password = password; }
public SqlDatabaseExistWorker(string server, string checkedDatabase, AuthenticationType authenticationType, string user, string password, out ISqlDatabaseExistWorkerReturnedData data) : base(server, "", authenticationType, user, password) { this.checkedDatabase = checkedDatabase; data = this.data = new ReturnedData(); }
public AuthenticationService(IConfigFileProvider configFileProvider, IUserService userService) { _configFileProvider = configFileProvider; _userService = userService; API_KEY = configFileProvider.ApiKey; AUTH_METHOD = configFileProvider.AuthenticationMethod; }
protected CouchBase(string username, string password, AuthenticationType aT, DbType dbType) { this.username = username; this.password = password; this.authType = aT; this.dbType = dbType; }
public SqlProgressWorker(string server, string database, AuthenticationType authenticationType, string user, string password, EventHandler<SqlWorkerProgressEventArgs> progressEvent = null) : base(server, database, authenticationType, user, password) { this.progressEvent = progressEvent; initializedDataAreSent = false; prevCurrentCount = 0; }
public AppManager(string sharePointUrl, AuthenticationType authenticationType, string credentialManagerLabel) { this.sharePointUrl = sharePointUrl; this.authenticationType = authenticationType; NetworkCredential cred = CredentialManager.GetCredential(credentialManagerLabel); userName = cred.UserName; password = cred.SecurePassword; }
public RemoteOperation(string targetUrl, AuthenticationType authType, string user, string password, string domain = "") { this.TargetSiteUrl = targetUrl; this.AuthType = authType; this.User = user; this.Password = password; this.Domain = domain; }
public static AuthenticationType ParseAuthType(string value, AuthenticationType defaultvalue) { if (value == "Password") return AuthenticationType.Password; else if (value == "PublicKey") return AuthenticationType.PublicKey; else return defaultvalue; }
public RemoteOperation(string targetUrl, AuthenticationType authType, string user, SecureString password, string AppInstanceId, string domain = "") { TargetSiteUrl = targetUrl; AuthType = authType; User = user; Password = password; Domain = domain; this.AppInstanceId = AppInstanceId; }
public SharepointServerSourceCallbackHandler(IEnvironmentRepository environmentRepository,string server,string userName,string password,AuthenticationType authenticationType) : base(environmentRepository) { VerifyArgument.AreNotNull(new Dictionary<string, object>{{"environmentRepository",environmentRepository}}); _server = server; _userName = userName; _password = password; _authenticationType = authenticationType; }
public SqlAttachDatabaseWorker(string server, string newDatabase, AuthenticationType authenticationType, string user, string password, string pathToMdf, string pathToLdf, out ISqlAttachDatabaseWorkerReturnedData data) : base(server, "", authenticationType, user, password) { data = this.data = new ReturnedData(); this.newDatabase = newDatabase; this.pathToMdf = pathToMdf; this.pathToLdf = pathToLdf; }
public ApiInitializePushCommand(IEnumerable<IntegrationPackageDto> packages, AuthenticationType authenticationType, AuditIntegrationCommand audit, ApiConfigurationIdentifier configuration, long configurationId) { Packages = packages; PackageTransactions = new List<PackageTransactionDto>(); AuthenticationType = authenticationType; Audit = audit; Configuration = configuration; ConfigurationId = configurationId; }
/// <summary> /// This static method activates a user and creates a new instance of SecureEnvironment. /// The authentication type determines the type of user identity that will be activated. /// If Permanent Windows activation is requested then the default currently logged on /// Windows Account identity will be activated. If Temporary Windows activation requested /// then user will be prompted for Windows Domain credentials through a dialog, and the /// user identified through those credentials will be activated. /// In case of Passport authentication, a Passport authentication dialog will always /// appear regardless of temporary or permanent activation mode. The user that authenticatd /// through that Passport Authentication dialog will be activated. /// Regardless of Windows or Passport Authentication, all Temporary created activation will be /// destroyed when SecureEnvironment instance is Disposed or Finalized. /// </summary> public static SecureEnvironment Create(string applicationManifest, AuthenticationType authentication, UserActivationMode userActivationMode) { SecurityHelper.DemandRightsManagementPermission(); return CriticalCreate(applicationManifest, authentication, userActivationMode); }
public Stream(Uri streamUrl, AuthenticationType authenticationType, string httpMethod = "GET", int timeout = -1) { tokenSource = new CancellationTokenSource(); ct = tokenSource.Token; AuthenticationType = authenticationType; HttpMethod = httpMethod.ToUpper(); _streamUrl = streamUrl; Timeout = timeout; }
internal SqlServerSettings(string server, AuthenticationType authentication, string adminUser, string adminPassword, string ibnUser, string ibnPassword) { Server = server; Authentication = authentication; AdminUser = adminUser; AdminPassword = adminPassword; PortalUser = ibnUser; PortalPassword = ibnPassword; AdminConnectionString = BuildConnectionString(authentication, server, "master", adminUser, adminPassword); }
public AccountingRequest(string nasIpAddress, ServiceType serviceType, string userName, AuthenticationType authenticationType, StatusType statusType, uint delayTime, string clientIp, string sessionId, Client client) : base(PacketType.AccountingRequest, nasIpAddress, serviceType, userName) { Packet.Secret = client.Secret; Packet.Attributes.Add(new AuthenticationTypeAttribute(authenticationType)); Packet.Attributes.Add(new StatusTypeAttribute(statusType)); Packet.Attributes.Add(new IntegerAttribute(AttributeType.AcctDelayTime, delayTime)); Packet.Attributes.Add(new IpAddressAttribute(AttributeType.FramedIpAddress, clientIp)); Packet.Attributes.Add(new StringAttribute(AttributeType.AcctSessionId, sessionId)); }
/// <summary> /// Initializes a new instance of the ActivateSessionRequest class. /// </summary> /// <param name="sessionAuthenticationType">Session authentication type.</param> /// <param name="maximumPrivilegeLevel">Maximum privilege level for this session.</param> /// <param name="sessionChallengeString">Challenge string from Get Session Challenge message.</param> /// <param name="initialOutboundSequenceNumber">Initial outbound sequence number.</param> internal ActivateSessionRequest( AuthenticationType sessionAuthenticationType, PrivilegeLevel maximumPrivilegeLevel, byte[] sessionChallengeString, uint initialOutboundSequenceNumber) { this.sessionAuthenticationType = sessionAuthenticationType; this.maximumPrivilegeLevel = maximumPrivilegeLevel; this.sessionChallengeString = sessionChallengeString; this.initialOutboundSequenceNumber = initialOutboundSequenceNumber; }
internal static string BuildConnectionString(AuthenticationType authentication, string server, string database, string user, string password) { string format; if (authentication == AuthenticationType.SqlServer) format = "Data source={0};Initial catalog={1};User Id={2};Password={3}"; else format = "Data source={0};Initial catalog={1};Integrated Security=SSPI"; return string.Format(CultureInfo.InvariantCulture, format, server, database, user, password); }
/// <summary> /// Constructs the CouchClient and gets an authentication cookie (10 min) /// </summary> /// <param name="host">The hostname of the CouchDB instance</param> /// <param name="port">The port of the CouchDB instance</param> /// <param name="username">The username of the CouchDB instance</param>Cou /// <param name="password">The password of the CouchDB instance</param> public CouchClient(string host, int port, string username, string password, bool isHttps, AuthenticationType aT) : base(username, password, aT) { if (isHttps == false) { baseUri = "http://" + host + ":" + port + "/"; } else { baseUri = "https://" + host + ":" + port + "/"; } authType = aT; }
/// <summary> /// Initializes a new instance of the GetSessionChallengeRequest class. /// </summary> /// <param name="authenticationType">Authentication type for challenge.</param> /// <param name="userid">Userid or null.</param> internal GetSessionChallengeRequest(AuthenticationType authenticationType, string userId) { this.challengeAuthenticationType = (byte)authenticationType; this.UserId = new byte[16]; if (!string.IsNullOrEmpty(userId)) { for (int i = 0; i < userId.Length; i++) { this.UserId[i] = (byte)userId[i]; } } }
/// <summary> /// Constructor /// </summary> /// <param name="hostName">Host name</param> /// <param name="portNumber">port number</param> /// <param name="protocol">SSH protocol version</param> /// <param name="authType">authentication type</param> /// <param name="userName">user name for login</param> /// <param name="password">password for login. pass empty string for the keyboard interactive mode.</param> public SSHConnectionParameter(string hostName, int portNumber, SSHProtocol protocol, AuthenticationType authType, string userName, string password) { HostName = hostName; PortNumber = portNumber; Protocol = protocol; PreferableCipherAlgorithms = new CipherAlgorithm[] { CipherAlgorithm.AES256CTR, CipherAlgorithm.AES256, CipherAlgorithm.AES192CTR, CipherAlgorithm.AES192, CipherAlgorithm.AES128CTR, CipherAlgorithm.AES128, CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES }; PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.DSA, PublicKeyAlgorithm.RSA }; AuthenticationType = authType; UserName = userName; Password = password; TerminalName = "vt100"; WindowSize = 0x1000; MaxPacketSize = 0x10000; CheckMACError = true; }
/// <summary> /// Initializes a new instance of the WebProxySettings class with /// required arguments. /// </summary> public WebProxySettings(AuthenticationType authentication, string connectionURI, string username) : this() { if (connectionURI == null) { throw new ArgumentNullException("connectionURI"); } if (username == null) { throw new ArgumentNullException("username"); } this.Authentication = authentication; this.ConnectionURI = connectionURI; this.Username = username; }
public WebAPIConnection(AuthenticationType AuthType,string Hostname, string Username, System.Security.SecureString Password) { _Hostname = Hostname; _Username = Username; _AuthType = AuthType; _Client = new RestSharp.RestClient(Hostname); if (AuthType == AuthenticationType.Basic) _Client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator(Username, Password.ToString()); else if (AuthType == AuthenticationType.Kerberos) { System.Net.NetworkCredential netCred = new System.Net.NetworkCredential(Username, Password.ToString()); _Client.Authenticator = new RestSharp.Authenticators.NtlmAuthenticator(netCred); } }
public SSHConnectionParameter() { _random = new Random(); _authtype = AuthenticationType.Password; _terminalname = "vt100"; _width = 80; _height = 25; _protocol = SSHProtocol.SSH2; _cipherAlgorithms = new CipherAlgorithm[] { CipherAlgorithm.AES128, CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES }; _hostkeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.DSA, PublicKeyAlgorithm.RSA }; _windowsize = 0x1000; _maxpacketsize = 0x10000; _checkMACError = true; _ssh1VersionEOL = "\n"; }
public AppManager(string sharePointUrl, string userName, SecureString password) { this.sharePointUrl = sharePointUrl; if (sharePointUrl.IndexOf("sharepoint.com") > -1) { authenticationType = AuthenticationType.Office365; } else { authenticationType = AuthenticationType.NetworkCredentials; } this.userName = userName; this.password = password; }
public static string PuttyArguments(HostInfo host, PuttyProfile profile, AuthenticationType authType) { // example: -ssh -load _stm_preset_ username@domainName -P 22 -pw password -D 5000 -L 44333:username.dyndns.org:44333 string profileArg = ""; if (profile != null) { profileArg = @" -load " + profile.Name; } var startShellOption = ""; if (string.IsNullOrWhiteSpace(host.RemoteCommand)) { startShellOption = " -N"; } string args; switch (authType) { case AuthenticationType.None: args = String.Format(@"-ssh{0} {1}@{2} -P {3} -v{4}", profileArg, host.Username, host.Hostname, host.Port, startShellOption); Logger.Log.DebugFormat(@"plink.exe {0}", args); break; case AuthenticationType.Password: args = String.Format(@"-ssh{0} {1}@{2} -P {3} -pw {4} -v{5}", profileArg, host.Username, host.Hostname, host.Port, host.Password, startShellOption); Logger.Log.DebugFormat(@"plink.exe -ssh{0} {1}@{2} -P {3} -pw ******** -v -N", profileArg, host.Username, host.Hostname, host.Port); break; case AuthenticationType.PrivateKey: args = String.Format(@"-ssh{0} {1}@{2} -P {3} -i {4} -v{5}", profileArg, host.Username, host.Hostname, host.Port, PrivateKeysStorage.CreatePrivateKey(host).Filename, startShellOption); Logger.Log.DebugFormat(@"plink.exe {0}", args); break; default: throw new ArgumentOutOfRangeException("authType"); } var sb = new StringBuilder(args); foreach (var tunnelArg in host.Tunnels.Select(tunnelArguments)) { sb.Append(tunnelArg); } args = sb.ToString(); return args; }
/// <summary> /// Gets the user details. /// </summary> /// <remarks> /// Sequence Diagram:<br/> /// <img src="SequenceDiagrams/SD_DataManager.Provider.Users.GetUserDetails.jpg" /> /// </remarks> /// <param name="authenticationType">Type of the authetication.</param> /// <param name="authenticationValue">The authetication value.</param> /// <returns>DbDataReader</returns> public static DbDataReader ProvideUserDetails(AuthenticationType authenticationType, string authenticationValue) { // TODO>> Get Device Authentication Type and return the user Details DbDataReader drUdetails = null; string sqlQuery = "select * from M_USERS where ("; switch (authenticationType) { case AuthenticationType.UserSystemId: sqlQuery += string.Format(CultureInfo.CurrentCulture, " USR_ACCOUNT_ID = N'{0}' ", authenticationValue); break; case AuthenticationType.UserId: sqlQuery += string.Format(CultureInfo.CurrentCulture, " USR_ID = N'{0}' ", authenticationValue); break; case AuthenticationType.CardId: sqlQuery += string.Format(CultureInfo.CurrentCulture, " USR_CARD_ID = '{0}' ", authenticationValue); break; case AuthenticationType.PinNumber: sqlQuery += string.Format(CultureInfo.CurrentCulture, " USR_PIN = N'{0}' ", authenticationValue); break; case AuthenticationType.AnyOfThem: sqlQuery += string.Format(CultureInfo.CurrentCulture, " USR_ACCOUNT_ID = N'{0}' or USR_ID = N'{0}' or USR_CARD_ID = N'{0}' or USR_PIN =N'{0}'", authenticationValue); break; default: sqlQuery += string.Format(CultureInfo.CurrentCulture, " USR_ACCOUNT_ID = '{0}' ", authenticationValue); break; } sqlQuery += ")"; using (Database dbUserDetails = new Database()) { DbCommand cmdUserDetails = dbUserDetails.GetSqlStringCommand(sqlQuery); drUdetails = dbUserDetails.ExecuteReader(cmdUserDetails, CommandBehavior.CloseConnection); } return(drUdetails); }
public async Task <ServiceReturn <bool> > UpdateDescendantColorAsync(AuthenticationType tipoAuth, string idParent, string idDesc, string colorHex, string successMessage = "", string errorMessage = "") { var uiMessages = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(errorMessage)) { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, errorMessage); } else { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, AppResources.Error); } if (!string.IsNullOrEmpty(successMessage)) { uiMessages.Add(ServiceReturnHandling.SuccessMessageKey, successMessage); } try { if (string.IsNullOrEmpty(idParent) || string.IsNullOrEmpty(idDesc) || string.IsNullOrEmpty(colorHex)) { throw new Exception("Parametros inválidos em UpdateUserDescendantColor"); } string baseUrl = await CommunicationManager.ServiceManager.GetServiceEndpoint("GP_BASE_MULE_URL"); ChangeColor colorBody = new ChangeColor() { Color = colorHex }; IdDescendantsDescendantClient sc = new IdDescendantsDescendantClient(baseUrl, await CommunicationManager.Instance.GetHttpClientWithToken(tipoAuth, new HttpClient())); await sc.IdChangeColorAsync(colorBody, idDesc, idParent); return(ServiceReturnHandling.BuildSuccessCallReturn <bool>(true, uiMessages)); } catch (Exception ex) { return(ServiceReturnHandling.HandleException <bool>(ex, uiMessages)); } }
public static void MessageInspector_RoundtripCustomHeaders() { MI_ClientBase_ClientAuth mi_ClientBase_ClientAuth = null; BasicHttpBinding binding = null; string accessToken = "Allow"; try { // *** SETUP *** \\ binding = new BasicHttpBinding((BasicHttpSecurityMode)BasicHttpSecurityMode.None); AuthenticationType authType = AuthenticationType.None; EndpointAddress endPoint = new EndpointAddress(Endpoints.HttpBaseAddress_Basic); mi_ClientBase_ClientAuth = new MI_ClientBase_ClientAuth(authType.ToString(), accessToken, binding, endPoint); // *** EXECUTE *** \\ Dictionary <string, string> headers = mi_ClientBase_ClientAuth.ValidateHeaders(); // *** VALIDATE *** \\ string authorizationHeaderValue, authTypeHeaderValue = ""; if (headers.TryGetValue("Authorization", out authorizationHeaderValue) && (headers.TryGetValue("authType", out authTypeHeaderValue))) { Assert.True(String.Equals(authorizationHeaderValue, accessToken), String.Format("Expected Authorization Header value: {0}/nActual Authorization Header value: {1}", accessToken, authorizationHeaderValue)); Assert.True(String.Equals(authTypeHeaderValue, authType.ToString()), String.Format("Expected AuthType Header value: {0}/nActual AuthType Header value: {1}", authType.ToString(), authTypeHeaderValue)); } else { Assert.True(false, String.Format("One or both of the expected headers were not found.\nHeader: \"authType\" had value: {0}\nHeader: \"HttpRequestHeader.Authorization\" had value: {1}", authorizationHeaderValue, authTypeHeaderValue)); } // *** CLEANUP *** \\ ((ICommunicationObject)mi_ClientBase_ClientAuth).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)mi_ClientBase_ClientAuth); } }
public async Task <ServiceReturn <bool> > ShareResultDocumentFileAsync(AuthenticationType tipoAuth, List <string> emails, List <string> IdDocumentList, string successMessage = "", string errorMessage = "") { var uiMessages = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(errorMessage)) { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, errorMessage); } else { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, AppResources.FailGetResults); } if (!string.IsNullOrEmpty(successMessage)) { uiMessages.Add(ServiceReturnHandling.SuccessMessageKey, successMessage); } bool res; try { string baseUrl = await CommunicationManager.ServiceManager.GetServiceEndpoint("GP_BASE_URL"); Generated.SyncronizingClient sc = new Generated.SyncronizingClient(baseUrl, await CommunicationManager.Instance.GetHttpClientWithToken(tipoAuth, new HttpClient())); Generated.ShareResultsFilter filter = new Generated.ShareResultsFilter(); filter.DocumentIds = new System.Collections.ObjectModel.ObservableCollection <string>(IdDocumentList); filter.Emails = new System.Collections.ObjectModel.ObservableCollection <string>(emails); var result = await sc.ShareResultsAsync(filter, User.UserId, "Documento", GetGPAppVersion()); res = true; // checkar return? return(ServiceReturnHandling.BuildSuccessCallReturn <bool>(res, uiMessages)); } catch (Exception ex) { return(ServiceReturnHandling.HandleException <bool>(ex, uiMessages)); } }
public async Task <ServiceReturn <string> > CreateProPatientAsync(AuthenticationType tipoAuth, string facilityId, string patName, string patEmail, DateTime patBirthDate, string patientNif, string patientPhoneNumber, string patGender, string successMessage = "", string errorMessage = "") { #region uimessage var uiMessages = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(errorMessage)) { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, errorMessage); } else { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, "Não foi possível registar o novo paciente."); } if (!string.IsNullOrEmpty(successMessage)) { uiMessages.Add(ServiceReturnHandling.SuccessMessageKey, successMessage); } #endregion try { facilityId = string.IsNullOrEmpty(facilityId) ? "" : facilityId; string baseUrl = await CommunicationManager.ServiceManager.GetServiceEndpoint("GP_BASE_URL"); Generated.PatientCoreClient sc = new Generated.PatientCoreClient(baseUrl, await CommunicationManager.Instance.GetHttpClientWithToken(tipoAuth, new HttpClient())); var ret = await sc.GetCreateProPatientAsync(facilityId, patName, patEmail, patBirthDate, patientNif, patientPhoneNumber, patGender, GetGPAppVersion()); if (ret != null && !string.IsNullOrEmpty(ret.CorporatePatientId)) { return(ServiceReturnHandling.BuildSuccessCallReturn <string>(ret.CorporatePatientId, uiMessages)); } else { throw new Exception(); } } catch (Exception ex) { return(ServiceReturnHandling.HandleException <string>(ex, uiMessages)); } }
public void WebServiceSourceDefinition_Equals_Object_Expected_False() { const AuthenticationType expectedAuthenticationType = AuthenticationType.Public; const string expectedDefaultQuery = "testDefaultQuery"; var expectedId = Guid.NewGuid(); const string expectedName = "testResourceName"; const string expectedPassword = "******"; const string expectedHostName = "testHost"; const string expectedPath = "testPath"; const string expectedUserName = "******"; var mockWebSource = new Mock <IWebSource>(); mockWebSource.Setup(webSource => webSource.AuthenticationType).Returns(expectedAuthenticationType); mockWebSource.Setup(webSource => webSource.DefaultQuery).Returns(expectedDefaultQuery); mockWebSource.Setup(webSource => webSource.ResourceID).Returns(expectedId); mockWebSource.Setup(webSource => webSource.ResourceName).Returns(expectedName); mockWebSource.Setup(webSource => webSource.Password).Returns(expectedPassword); mockWebSource.Setup(webSource => webSource.Address).Returns(expectedHostName); mockWebSource.Setup(webSource => webSource.GetSavePath()).Returns(expectedPath); mockWebSource.Setup(webSource => webSource.UserName).Returns(expectedUserName); var webServiceSourceDefinition = new WebServiceSourceDefinition(mockWebSource.Object); var mockWebSourceDup = new Mock <IWebSource>(); mockWebSourceDup.Setup(webSource => webSource.AuthenticationType).Returns(expectedAuthenticationType); mockWebSourceDup.Setup(webSource => webSource.DefaultQuery).Returns(expectedDefaultQuery); mockWebSourceDup.Setup(webSource => webSource.ResourceID).Returns(expectedId); mockWebSourceDup.Setup(webSource => webSource.ResourceName).Returns(expectedName); mockWebSourceDup.Setup(webSource => webSource.Password).Returns(expectedPassword); mockWebSourceDup.Setup(webSource => webSource.Address).Returns("NewHostName"); mockWebSourceDup.Setup(webSource => webSource.GetSavePath()).Returns(expectedPath); mockWebSourceDup.Setup(webSource => webSource.UserName).Returns(expectedUserName); object webSourceObj = new WebServiceSourceDefinition(mockWebSourceDup.Object); var isEqual = webServiceSourceDefinition.Equals(webSourceObj); Assert.IsFalse(isEqual); }
IWebRequest BuildPostRequest(string serviceToExecute, string payload, AuthenticationType authenticationType, string userName, string password, bool isDebug) { var escapeUriString = Uri.EscapeUriString(serviceToExecute); var req = _webRequestFactory.New(escapeUriString); req.Method = "POST"; UpdateRequest(authenticationType, userName, password, isDebug, req); var data = Encoding.ASCII.GetBytes(payload); req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = data.Length; req.Headers.Add("Warewolf-Execution-Id", DataObject.ExecutionID.ToString()); using (Stream requestStream = req.GetRequestStream()) { requestStream.Write(data, 0, data.Length); requestStream.Close(); } return(req); }
private async Task <T> GetResults <T>(string query, AuthenticationType authType, Func <string, TwitterAPIEndpoint, string> buildQueryString, TwitterAPIEndpoint endpoint) where T : IQueryResults { UserRateLimitInfo userInfo = RateLimitController.GetCurrentUserInfo(rateLimitDb, endpoint, userManager, User); string responseBody = await TwitterAPIUtils.GetResponse( Configuration, authType, endpoint, buildQueryString(query, endpoint), User.GetTwitterAccessToken(), User.GetTwitterAccessTokenSecret(), userInfo); if (userInfo != null) { userInfo.ResetIfNeeded(); rateLimitDb.Update(userInfo); rateLimitDb.SaveChanges(); } if (responseBody == null) { return(default);
public void SetAuthenticationType(AuthenticationType authenticationType) { switch (authenticationType) { case AuthenticationType.Windows: WindowsRadioButton.IsChecked = true; break; case AuthenticationType.User: UserRadioButton.IsChecked = true; break; case AuthenticationType.Public: PublicRadioButton.IsChecked = true; break; default: WindowsRadioButton.IsChecked = true; break; } }
public RedisSourceViewModel(IRedisSourceModel redisSourceModel, IEventAggregator aggregator, IAsyncWorker asyncWorker, IExternalProcessExecutor executor) : base("RedisSource") { VerifyArgument.IsNotNull(nameof(executor), executor); VerifyArgument.IsNotNull(nameof(asyncWorker), asyncWorker); VerifyArgument.IsNotNull(nameof(redisSourceModel), redisSourceModel); VerifyArgument.IsNotNull(nameof(aggregator), aggregator); AsyncWorker = asyncWorker; Executor = executor; _redisSourceModel = redisSourceModel; _warewolfserverName = redisSourceModel.ServerName; _authenticationType = AuthenticationType.Anonymous; _hostName = string.Empty; _port = "6379"; _password = string.Empty; HeaderText = Resources.Languages.Core.RedisNewHeaderLabel; Header = Resources.Languages.Core.RedisNewHeaderLabel; TestCommand = new DelegateCommand(TestConnection, CanTest); OkCommand = new DelegateCommand(SaveConnection, CanSave); CancelTestCommand = new DelegateCommand(CancelTest, CanCancelTest); }
public IQueryable <Authentication> GetAuthenticationPaged(Expression <Func <Authentication, bool> > orderByProperty, AuthenticationType userLoginAuthenticationType, long levelId, bool isAscendingOrder, out int pageCount, int pageNum = 1, int pageSize = 20) { IQueryable <Authentication> authentications; if (userLoginAuthenticationType == AuthenticationType.AdminCentral) { authentications = _authenticationRepository.Where(a => a.AuthenticationType != AuthenticationType.AdminCentral && a.CentralOrganizationId == levelId); } else if (userLoginAuthenticationType == AuthenticationType.AdminBranch) { authentications = _authenticationRepository.Where(a => a.AuthenticationType != AuthenticationType.AdminBranch && a.BranchProvinceId == levelId); } else { authentications = _authenticationRepository.Where(a => a.AuthenticationType != AuthenticationType.AdminUniversity && a.UniversityId == levelId); } authentications = authentications.Include(i => i.Users); return(_authenticationRepository.PagedResult(authentications, orderByProperty, isAscendingOrder, out pageCount, pageNum, pageSize)); }
public async Task GetIdentityTest( string value, string clientId, string iotHubHostName, string token, bool success, Type expectedCredentialsType, Type expectedIdentityType, AuthenticationType expected) { X509Certificate2 certificate = new X509Certificate2(); IList <X509Certificate2> chain = new List <X509Certificate2>(); IClientCredentials clientCredentials = await GetClientCredentials(iotHubHostName, clientId, value, token, token == null, string.Empty, certificate, chain); Assert.NotNull(clientCredentials); Assert.IsType(expectedCredentialsType, clientCredentials); Assert.IsType(expectedIdentityType, clientCredentials.Identity); Assert.Equal(iotHubHostName, ((Identity)clientCredentials.Identity).IotHubHostName); Assert.Equal(ProductInfo, clientCredentials.ProductInfo); Assert.Equal(expected, clientCredentials.AuthenticationType); }
protected TwitchAccountViewModel(ITwitchAuthentication twitchAuthentication, ITwitchConnection twitchConnection, AuthenticationType authType, object icon, object label, object toolTip, UserControl content) : base(icon, label, toolTip, content) { AuthType = authType; _twitchAuthentication = twitchAuthentication; _twitchConnection = twitchConnection; ConnectCommand = new ActionCommand(Connect); DisconnectCommand = new ActionCommand(Disconnect); GenerateTokenCommand = new ActionCommand(GenerateToken); ManualEntryCommand = new ActionCommand(SwitchToManualEntry); if (!_twitchAuthentication.Credentials.ContainsKey(AuthType)) { _twitchAuthentication.Credentials[AuthType] = new TwitchCredentials { AuthType = authType }; } }
public async Task GetModuleIdentityTest( string value, string iotHubHostName, string token, string deviceId, string moduleId, AuthenticationType authenticationType) { var certificate = new X509Certificate2(); var chain = new List <X509Certificate2>(); IClientCredentials clientCredentials = await GetClientCredentials(iotHubHostName, $"{deviceId}/{moduleId}", value, token, token == null, string.Empty, certificate, chain); Assert.NotNull(clientCredentials); Assert.Equal(authenticationType, clientCredentials.AuthenticationType); var hubModuleIdentity = clientCredentials.Identity as IModuleIdentity; Assert.NotNull(hubModuleIdentity); Assert.Equal(deviceId, hubModuleIdentity.DeviceId); Assert.Equal(moduleId, hubModuleIdentity.ModuleId); Assert.Equal($"{deviceId}/{moduleId}", hubModuleIdentity.Id); }
public async Task Test10163(TestContext ctx, HttpServer server, [AuthenticationType] AuthenticationType authType, CancellationToken cancellationToken) { int handlerCalled = 0; var post = new PostHandler("Post bug #10163", HttpContent.HelloWorld); post.Method = "PUT"; post.CustomHandler = (request) => { Interlocked.Increment(ref handlerCalled); return(null); }; var handler = CreateAuthMaybeNone(post, authType); using (var operation = new WebClientOperation(server, handler, WebClientOperationType.OpenWriteTaskAsync)) { await operation.Run(ctx, cancellationToken).ConfigureAwait(false); } ctx.Assert(handlerCalled, Is.EqualTo(1), "handler called"); }
public async Task Test10163( TestContext ctx, [HttpServer] HttpServer server, [AuthenticationType] AuthenticationType authType, CancellationToken cancellationToken) { var post = new PostHandler("Post bug #10163", HttpContent.HelloWorld); var handler = CreateAuthMaybeNone(post, authType); var uri = handler.RegisterRequest(server); using (var client = new WebClient()) { ConfigureWebClient(client, handler, cancellationToken); var stream = await client.OpenWriteTaskAsync(uri, "PUT"); using (var writer = new StreamWriter(stream)) { await post.Content.WriteToAsync(writer); } } }
public Identity(X509Certificate2 certificate, string applicationId) { if (applicationId == null) { throw new ArgumentNullException("applicationId", "El valor no puede ser nulo."); } if (applicationId == "") { throw new ArgumentException("applicationId", "El valor no puede ser una cadena vacía."); } if (certificate == null) { throw new ArgumentNullException("certificate", "El valor no puede ser nulo."); } _certificate = certificate; _authenticationType = AuthenticationType.BinarySecurityToken; _applicationId = applicationId; }
public async Task <ServiceReturn <string> > GetHumanResourceCvAsync(AuthenticationType tipoAuth, int humanResourceID, string successMessage = "", string errorMessage = "") { var uiMessages = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(errorMessage)) { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, errorMessage); } else { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, AppResources.GetMedicInfoError); } if (!string.IsNullOrEmpty(successMessage)) { uiMessages.Add(ServiceReturnHandling.SuccessMessageKey, successMessage); } string result = string.Empty; try { string baseMuleUrl = await CommunicationManager.ServiceManager.GetServiceEndpoint("GP_BASE_MULE_URL"); Generated.Mulesoft.GETClient sc = new Generated.Mulesoft.GETClient(baseMuleUrl, await CommunicationManager.Instance.GetHttpClientWithToken(tipoAuth, new HttpClient())); var ret = (await sc.StaffIdCvAsync(humanResourceID)); if (ret != null) { result = ret.Data; } return(ServiceReturnHandling.BuildSuccessCallReturn <string>(result, uiMessages)); } catch (Exception ex) { return(ServiceReturnHandling.HandleException <string>(ex, uiMessages)); } }
#pragma warning restore 618 private void UpdateInputFileProperties(PdfOperationsDesigner designer, IFunctionData data, string propertyPrefix, string filePathPropertyName, string authenticationTypePropertyName, string passwordPropertyName, string certificateSourcePropertyName, string certificateFilePathPropertyName, string certificateFilePasswordPropertyName, string certificatePropertyName) { Func <string, string> addPrefix = (value) => (string.IsNullOrEmpty(propertyPrefix)) ? value : propertyPrefix + " " + char.ToLower(value[0]) + value.Substring(1); designer.Properties[filePathPropertyName].Value = data.Properties[addPrefix("Pdf filename")].Value; AuthenticationType authenticationType = data.Properties[addPrefix("Authentication type")].GetValue <AuthenticationType>(); designer.Properties[authenticationTypePropertyName].Value = authenticationType; switch (authenticationType) { case AuthenticationType.Password: designer.Properties[passwordPropertyName].Value = data.Properties[addPrefix("Pdf password")].Value; break; case AuthenticationType.Certificate: CertificateSource certificateSource = data.Properties[addPrefix("Certificate source")].GetValue <CertificateSource>(); designer.Properties[certificateSourcePropertyName].Value = certificateSource; switch (certificateSource) { case CertificateSource.File: designer.Properties[certificateFilePathPropertyName].Value = data.Properties[addPrefix("Certificate file path")].Value; designer.Properties[certificateFilePasswordPropertyName].Value = data.Properties[addPrefix("Certificate file password")].Value; break; case CertificateSource.Store: designer.Properties[certificatePropertyName].Value = data.Properties[addPrefix("Certificate")].Value; break; } break; } }
/// <summary> /// /// </summary> /// <param name="tipoAuth"></param> /// <param name="setUser">Persiste na classe GPService os dados do paciente (conceito UserPatient) obtidos para consumo posterior (GPService funciona tipo repositório/Sessão)</param> /// <returns></returns> public async Task <bool> GetAndSetPatientInfoByUniqueIdAsync(AuthenticationType tipoAuth, string userID) { try { var serviceResponse = await GetPatientInfoByUniqueIdAsync(tipoAuth, userID, string.Empty, string.Empty); if (serviceResponse.Success) { UserPatient = serviceResponse.Result; User.Name = UserPatient.Name; UserPatient.PatientUniqueId = User.UserId; return(true); } throw new Exception(); } catch (Exception e) { Debug.WriteLine("Error on GetAndSetPatientInfoByUniqueIdAsync: "); UserPatient = null; return(false); } }
public static bool ExtractDacPac(string sourceDatabase, string sourceServer, AuthenticationType authType, string userName, string password, string dacPacFileName) { try { log.LogInformation($"Extracting dacpac from {sourceServer} : {sourceDatabase}"); DacExtractOptions opts = new DacExtractOptions(); opts.IgnoreExtendedProperties = true; opts.IgnoreUserLoginMappings = true; SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder(); if (authType == AuthenticationType.Windows) { connBuilder.IntegratedSecurity = true; } if (!string.IsNullOrWhiteSpace(userName)) { connBuilder.UserID = userName; } if (!string.IsNullOrWhiteSpace(password)) { connBuilder.Password = password; } connBuilder.DataSource = sourceServer; connBuilder.InitialCatalog = sourceDatabase; Version ver = Assembly.GetExecutingAssembly().GetName().Version; DacServices service = new DacServices(connBuilder.ConnectionString); service.Extract(dacPacFileName, sourceDatabase, "Sql Build Manager", ver); log.LogInformation($"dacpac from {sourceServer}.{sourceDatabase} saved to {dacPacFileName}"); return(true); } catch (Exception exe) { log.LogError($"Problem creating DACPAC from {sourceServer}.{sourceDatabase}: {exe.ToString()}"); return(false); } }
public Task RunAuthentication( TestContext ctx, [WebTestFeatures.SelectProxyKind(IncludeSSL = true)] ProxyKind kind, [TestHost] ProxyServer server, [AuthenticationType] AuthenticationType authType, [ProxyHandler] Handler handler, CancellationToken cancellationToken) { var authHandler = new AuthenticationHandler(authType, handler); if (kind == ProxyKind.Unauthenticated) { return(TestRunner.RunTraditional( ctx, server, authHandler, cancellationToken, false, HttpStatusCode.ProxyAuthenticationRequired, WebExceptionStatus.ProtocolError)); } else { return(TestRunner.RunTraditional( ctx, server, authHandler, cancellationToken, false)); } }
public async Task <ServiceReturn <bool> > CreateSchedulingRequestAsync(AuthenticationType tipoAuth, string userId, string facilityId, string medActId, string specialityId, string humanResourceId, string observations, DateTime datePref, string successMessage = "", string errorMessage = "") { var uiMessages = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(errorMessage)) { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, errorMessage); } else { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, "Não é possível criar o pedido de marcação"); } if (!string.IsNullOrEmpty(successMessage)) { uiMessages.Add(ServiceReturnHandling.SuccessMessageKey, successMessage); } try { string baseUrl = await CommunicationManager.ServiceManager.GetServiceEndpoint("GP_BASE_URL"); Generated.SchedulingRequestClient sc = new Generated.SchedulingRequestClient(baseUrl, await CommunicationManager.Instance.GetHttpClientWithToken(tipoAuth, new HttpClient())); var facilityIdFinal = !string.IsNullOrEmpty(facilityId) ? facilityId : string.Empty; var medActIdFinal = !string.IsNullOrEmpty(medActId) ? medActId : string.Empty; var specialityIdFinal = !string.IsNullOrEmpty(specialityId) ? specialityId : string.Empty; var humanResourceIdFinal = !string.IsNullOrEmpty(humanResourceId) ? humanResourceId : string.Empty; var observationsFinal = !string.IsNullOrEmpty(observations) ? observations : string.Empty; //var result = await sc.CreateSchedulingRequestAsync(Generated.RequestType.TELEF, User.UserId, facilityIdFinal, medActIdFinal, specialityIdFinal, humanResourceIdFinal, observationsFinal, datePref, GetGPAppVersion()); var result = await sc.CreateSchedulingRequestAsync(Generated.RequestType3.TELEF, userId, facilityIdFinal, medActIdFinal, specialityIdFinal, humanResourceIdFinal, observationsFinal, datePref, DateTime.Now, string.Empty, string.Empty, GetGPAppVersion()); return(ServiceReturnHandling.BuildSuccessCallReturn <bool>(true, uiMessages)); } catch (Exception ex) { return(ServiceReturnHandling.HandleException <bool>(ex, uiMessages)); } }
public void DbSourceDefinition_Equals_DbSource_Expected_True() { const AuthenticationType expectedAuthenticationType = AuthenticationType.Public; const string expectedDatabaseName = "warewolfDb"; var expectedResourceID = Guid.NewGuid(); const string expectedPassword = "******"; const string expectedServer = "localhost"; const int expectedConnectionTimeout = 30; const enSourceType expectedServerType = enSourceType.SqlDatabase; const string expectedUserId = "userId"; var mockDb = new Mock <IDb>(); mockDb.Setup(db => db.Server).Returns(expectedServer); mockDb.Setup(db => db.ServerType).Returns(expectedServerType); mockDb.Setup(db => db.UserID).Returns(expectedUserId); mockDb.Setup(db => db.Password).Returns(expectedPassword); mockDb.Setup(db => db.AuthenticationType).Returns(expectedAuthenticationType); mockDb.Setup(db => db.ResourceID).Returns(expectedResourceID); mockDb.Setup(db => db.DatabaseName).Returns(expectedDatabaseName); mockDb.Setup(db => db.ConnectionTimeout).Returns(expectedConnectionTimeout); var dbSourceDefinition = new DbSourceDefinition(mockDb.Object); var mockDbSource = new Mock <IDbSource>(); mockDbSource.Setup(db => db.ServerName).Returns(expectedServer); mockDbSource.Setup(db => db.Type).Returns(expectedServerType); mockDbSource.Setup(db => db.UserName).Returns(expectedUserId); mockDbSource.Setup(db => db.Password).Returns(expectedPassword); mockDbSource.Setup(db => db.AuthenticationType).Returns(expectedAuthenticationType); mockDbSource.Setup(db => db.Id).Returns(expectedResourceID); mockDbSource.Setup(db => db.DbName).Returns(expectedDatabaseName); mockDbSource.Setup(db => db.ConnectionTimeout).Returns(expectedConnectionTimeout); var isEqual = dbSourceDefinition.Equals(mockDbSource.Object); Assert.IsTrue(isEqual); }
public static Task <EdgeDevice> CreateIdentityAsync( string deviceId, IotHub iotHub, AuthenticationType authType, X509Thumbprint x509Thumbprint, CancellationToken token) { if (authType == AuthenticationType.SelfSigned && x509Thumbprint == null) { throw new ArgumentException("A device created with self-signed mechanism must provide an x509 thumbprint."); } return(Profiler.Run( async() => { Device device = await iotHub.CreateEdgeDeviceIdentityAsync(deviceId, authType, x509Thumbprint, token); return new EdgeDevice(device, true, iotHub); }, "Created edge device '{Device}' on hub '{IotHub}'", deviceId, iotHub.Hostname)); }
public void RedisSourceDefinition_ReferenceEquals_RedisSourceDefinition_Expected_True() { const AuthenticationType expectedAuthenticationType = AuthenticationType.Password; var expectedId = Guid.NewGuid(); const string expectedName = "testResourceName"; const string expectedPassword = "******"; const string expectedHostName = "testHost"; var mockRedisSource = new Mock <IRedisSource>(); mockRedisSource.Setup(redisSource => redisSource.HostName).Returns(expectedHostName); mockRedisSource.Setup(redisSource => redisSource.ResourceID).Returns(expectedId); mockRedisSource.Setup(redisSource => redisSource.ResourceName).Returns(expectedName); mockRedisSource.Setup(redisSource => redisSource.Password).Returns(expectedPassword); mockRedisSource.Setup(redisSource => redisSource.AuthenticationType).Returns(expectedAuthenticationType); var redisSourceDefinition = new RedisSourceDefinition(mockRedisSource.Object); var isEqual = redisSourceDefinition.Equals(redisSourceDefinition); Assert.IsTrue(isEqual); }
static IServer CreateEnvironmentModel(Guid id, Uri applicationServerUri, AuthenticationType authenticationType, string userName, string password, string name) { ServerProxy connectionProxy; if (authenticationType == AuthenticationType.Windows || authenticationType == AuthenticationType.Anonymous) { connectionProxy = new ServerProxy(applicationServerUri); } else { if (authenticationType == AuthenticationType.Public) { userName = "******"; password = ""; } connectionProxy = new ServerProxy(applicationServerUri.ToString(), userName, password); } return(new Server(id, connectionProxy) { Name = name }); }
public void SharePointServiceSourceDefinition_Equals_SharePointServiceSourceDefinition_Expected_True() { const AuthenticationType expectedAuthenticationType = AuthenticationType.Public; const string expectedServer = "localhost"; const string expectedPassword = "******"; const string expectedUserName = "******"; var mockSharepointSource = new Mock <ISharepointSource>(); mockSharepointSource.Setup(sharepointSource => sharepointSource.Server).Returns(expectedServer); mockSharepointSource.Setup(sharepointSource => sharepointSource.UserName).Returns(expectedUserName); mockSharepointSource.Setup(sharepointSource => sharepointSource.Password).Returns(expectedPassword); mockSharepointSource.Setup(sharepointSource => sharepointSource.AuthenticationType).Returns(expectedAuthenticationType); var sharePointServiceSourceDefinition = new SharePointServiceSourceDefinition(mockSharepointSource.Object); var sharePointServiceSourceDefinitionDup = new SharePointServiceSourceDefinition(mockSharepointSource.Object); var isEqual = sharePointServiceSourceDefinition.Equals(sharePointServiceSourceDefinitionDup); Assert.IsTrue(isEqual); Assert.IsTrue(sharePointServiceSourceDefinition == sharePointServiceSourceDefinitionDup); }
WebRequest BuildGetWebRequest(string requestUri, AuthenticationType authenticationType, string userName, string password) { try { var req = WebRequest.Create(requestUri); if (authenticationType == AuthenticationType.Windows) { req.UseDefaultCredentials = true; } else { req.UseDefaultCredentials = false; // we to default to the hidden public user name of \, silly know but that is how to get around ntlm auth ;) if (authenticationType == AuthenticationType.Public) { userName = GlobalConstants.PublicUsername; password = string.Empty; } req.Credentials = new NetworkCredential(userName, password); } req.Method = "GET"; // set header for server to know this is a remote invoke ;) var remoteInvokerId = DataObject.RemoteInvokerID; if (remoteInvokerId == Guid.Empty.ToString()) { throw new Exception("Remote Server ID Empty"); } req.Headers.Add(HttpRequestHeader.From, remoteInvokerId); // Set to remote invoke ID ;) req.Headers.Add(HttpRequestHeader.Cookie, GlobalConstants.RemoteServerInvoke); return(req); } catch (Exception) { return(null); } }
public async Task<bool> ChangeUserPasswordAsync(AuthenticationType tipoAuth, string username, string oldPassword, string newPassword) { try { string baseUrl = await CommunicationManager.ServiceManager.GetServiceEndpoint("GP_BASE_URL"); Generated.SecurityClient sc = new Generated.SecurityClient(baseUrl, await CommunicationManager.Instance.GetHttpClientWithToken(tipoAuth, new HttpClient())); var result = await sc.GetChangeUserPasswordAsync(username, oldPassword, newPassword, GetGPAppVersion()); if (result) { // Este assign permite/serve para posteriormente a esta chamada quando algum serv for invocado com AuthenticationType = UserAuthentication utilizar estas credenciais para obter token CommunicationManager.UserName = username; CommunicationManager.UserPassWord = newPassword; } return result; } catch (Exception ex) { throw ex; } }