/// <summary> /// 构造函数 /// </summary> public CreateTokenCommand(string clientId, AuthType authType) { Guard.IsNotNullOrEmpty(clientId, "clientId"); this.ClientId = clientId; AuthType = authType; TimeOut = 3600; }
public static Request GetInitialRequest(string authToken, AuthType authType, double lat, double lng, double altitude, params Request.Types.Requests[] customRequests) { return new Request() { Altitude = Utils.FloatAsUlong(altitude), Auth = new Request.Types.AuthInfo() { Provider = authType == AuthType.Google ? "google" : "ptc", Token = new Request.Types.AuthInfo.Types.JWT() { Contents = authToken, Unknown13 = 14 } }, Latitude = Utils.FloatAsUlong(lat), Longitude = Utils.FloatAsUlong(lng), RpcId = 1469378659230941192, Unknown1 = 2, Unknown12 = 989, //Required otherwise we receive incompatible protocol Requests = { customRequests } }; }
public SPClientContext(Uri webFullUrl, AuthType authType = AuthType.Default, string userName = null, string password = null) : this(webFullUrl) { Authentication = authType; UserName = userName; switch (Authentication) { case AuthType.Default: AuthenticationMode = ClientAuthenticationMode.Default; Credentials = string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(password) ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(UserName, password); break; case AuthType.SharePointOnline: AuthenticationMode = ClientAuthenticationMode.Default; Credentials = new SharePointOnlineCredentials(UserName, Utility.GetSecureString(password)); break; case AuthType.Anonymous: AuthenticationMode = ClientAuthenticationMode.Anonymous; break; case AuthType.Forms: AuthenticationMode = ClientAuthenticationMode.FormsAuthentication; FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo(UserName, password); break; } }
public SessionManager(int appId, int perms) { this.sessions = new List<SessionInfo>(); this.AppId = appId; this.Permissions = perms; this.AuthorizationType = AuthType.VKAuth; }
/// <summary> /// PeerEventArgs Constructor /// </summary> /// <param name="parsed">a simple MessageParse</param> internal PeerEventArgs(dynamic parsed) { #if DEBUG FCP2Protocol.ArgsDebug(this, parsed); #endif LastGoodVersion = parsed.lastGoodVersion; Opennet = parsed.opennet; MyName = parsed.myName; Identity = parsed.identity; Location = parsed.location; Testnet = parsed.testnet; Version = parsed.version; Physical = new PhysicalType(parsed); Ark = new ArkType(parsed); DsaPubKey = new DsaPubKeyType(parsed); DsaGroup = new DsaGroupType(parsed); Auth = new AuthType(parsed); Volatile = new VolatileType(parsed); Metadata = new MetadataType(parsed); #if DEBUG parsed.PrintAccessCount(); #endif }
public async Task<long> RegisterUser(string email, string password, string lastName, string firstName, string middleName, AuthType? authType, string authId, bool confirmEmail) { var salt = password == null? null: PasswordHash.CreateSalt(); var passwordHash = password == null ? null : PasswordHash.CreateHash(salt, password); var user = new User { AuthID = authId, AuthType = authType, Confirmed = authType.HasValue && !confirmEmail, DateJoined = DateTime.UtcNow, Deleted = false, Email = email, FirstName = firstName, LastName = lastName, MiddleName = middleName, Password = passwordHash, Salt = salt, Role = Role.Voter }; user.Id = await userRepository.Add(user); if (!authType.HasValue || confirmEmail) { await SendConfirmationEmail(user); } return user.Id; }
public SessionManager(int apiId, string scope) { this.sessions = new List<SessionInfo>(); this.AppId = apiId; this.Scope = scope; this.AuthorizationType = AuthType.OAuth; }
private bool GetUserNameAndPassword(HttpActionContext actionContext, out string username, out string password, out AuthType authType) { authType = AuthType.basic; bool gotIt = false; username = string.Empty; password = string.Empty; IEnumerable<string> headerVals; if (actionContext.Request.Headers.TryGetValues("Authorization", out headerVals)) { try { string authHeader = headerVals.FirstOrDefault(); char[] delims = { ' ' }; string[] authHeaderTokens = authHeader.Split(new char[] { ' ' }); if (authHeaderTokens[0].Contains("Basic")) { string decodedStr = DecodeFrom64(authHeaderTokens[1]); string[] unpw = decodedStr.Split(new char[] { ':' }); username = unpw[0]; password = unpw[1]; } else { if (authHeaderTokens.Length > 1) username = DecodeFrom64(authHeaderTokens[1]); authType = AuthType.cookie; } gotIt = true; } catch { gotIt = false; } } return gotIt; }
/// <summary> /// NodeDataEventArgs Constructor /// </summary> /// <param name="parsed">a simple MessageParse</param> internal NodeDataEventArgs(dynamic parsed) { #if DEBUG FCP2Protocol.ArgsDebug(this, parsed); #endif LastGoodVersion = parsed.lastGoodVersion; Sig = parsed.sig; Opennet = parsed.opennet; Identity = parsed.identity; Version = parsed.version; Physical = new PhysicalType(parsed.physical); Ark = new ArkType(parsed.ark); DsaPubKey = new DsaPubKeyType(parsed.dsaPubKey); DsaPrivKey = new DsaPrivKeyType(parsed.dsaPrivKey); DsaGroup = new DsaGroupType(parsed.dsaGroup); Auth = new AuthType(parsed.auth); ClientNonce = parsed.clientNonce; Location = parsed.location; if (!parsed.location.LastConversionSucessfull) { Location = -1.0; } if ([email protected]()) { Volatile = new VolatileType(parsed.@volatile); } #if DEBUG parsed.PrintAccessCount(); #endif }
/// <summary> /// LDAP library constructior where all the class variables are initialized /// The variables not specified in definition will be set at default values. /// </summary> /// <param name="adminUser">Admin user</param> /// <param name="adminMode">Admin User</param> /// <param name="ldapServer">LDAP Server with port</param> /// <param name="ldapSearchBaseDn">Base DN where start the search.</param> /// <param name="authType"></param> /// <param name="loggerType">Mode to log</param> /// <param name="logPath">Path of the logger File</param> public LdapManager(ILdapUser adminUser, LDAPAdminMode adminMode, string ldapServer, string ldapSearchBaseDn, AuthType authType, LoggerType loggerType, string logPath ) { _configRepository = LdapConfigRepositoryFactory.GetConfigRepository(); try { _configRepository.BasicLdapConfig(adminUser,adminMode, ldapServer, ldapSearchBaseDn, authType, loggerType, logPath); _logger = LoggerFactory.GetLogger(_configRepository.GetWriteLogFlag(), _configRepository.GetLogPath()); } catch (ArgumentNullException) { _ldapCurrentState = LdapState.LdapLibraryInitError; throw; } _adminModeChecker = new LdapAdminModeChecker(_configRepository); CommonInitOperations(); _ldapCurrentState = LdapState.LdapLibraryInitSuccess; }
public ActionResult DoAuth(AuthType authType) { var authHandler = AuthHandlerFactory.CreateAuthHandler(authType); // TODO: HI think of if ids are unique among differenct providers var userData = authHandler .ProcessAuthRequest(Request as HttpRequestWrapper); if (userData == null) { TempData["authError"] = "Authentication has failed."; return RedirectToAction("LogIn"); } FormsAuthentication.SetAuthCookie(userData.UserName, true); return Session["ReturnUrl"] != null ? (ActionResult) Redirect((string) Session["ReturnUrl"]) : RedirectToAction("Index", "Home"); }
/// <summary> /// PeerEventArgs Constructor /// </summary> /// <param name="parsed">a simple MessageParse</param> internal PeerEventArgs(dynamic parsed) { #if DEBUG FCP2Protocol.ArgsDebug(this, parsed); #endif lastGoodVersion = parsed.lastGoodVersion; opennet = parsed.opennet; myName = parsed.myName; identity = parsed.identity; location = parsed.location; testnet = parsed.testnet; version = parsed.version; physical = new PhysicalType(parsed); ark = new ArkType(parsed); dsaPubKey = new DsaPubKeyType(parsed); dsaGroup = new DsaGroupType(parsed); auth = new AuthType(parsed); @volatile = new VolatileType(parsed); metadata = new MetadataType(parsed); #if DEBUG parsed.PrintAccessCount(); #endif }
public void AddServer(LdapDirectoryIdentifier identifier, int maxConnections, int protocolVersion = 3, bool ssl = false, double? timeout = null, NetworkCredential credentials = null, AuthType? authType = null) { var serverName = identifier.Servers[0]; var factory = new LdapConnectionFactory(serverName); if (credentials != null) factory.AuthenticateAs(credentials); if (authType.HasValue) factory.AuthenticateBy(authType.Value); if (timeout.HasValue) factory.ConnectionTimeoutIn(timeout.Value); factory.ProtocolVersion(protocolVersion); if (identifier.FullyQualifiedDnsHostName) factory.ServerNameIsFullyQualified(); if (identifier.Connectionless) factory.UseUdp(); if (ssl) factory.UseSsl(); factory.UsePort(identifier.PortNumber); _servers[serverName] = new ServerPoolMemberConnectionFactory(serverName, factory, maxConnections); }
/// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to pop3 session.</param> /// <param name="userName">Username.</param> /// <param name="passwData">Password data.</param> /// <param name="data">Authentication specific data(as tag).</param> /// <param name="authType">Authentication type.</param> public AuthUser_EventArgs(SMTP_Session session,string userName,string passwData,string data,AuthType authType) { m_pSession = session; m_UserName = userName; m_PasswData = passwData; m_Data = data; m_AuthType = authType; }
protected ConnectionHolder GetConnectionForCore(NetworkCredential credential, AuthType authType = AuthType.Basic) { connectionFactoryConfiguration .AuthenticateBy(authType) .AuthenticateAs(credential); return new ConnectionHolder(connectionFactoryConfiguration.GetConnection, connectionFactoryConfiguration.ReleaseConnection); }
public WindowAuthetification(string connection, AuthType type, string currentAdmin=null, AdminInfo originalInfo=null) { InitializeComponent(); Connection = connection; TYPE_ = type; Father_ = currentAdmin; original = originalInfo; }
/// <summary> /// Returns true if the login worked /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public async Task<string> DoPtcLogin(string username, string password) { Logger.Write("Starting PTC login"); _accessToken = await PtcLogin.GetAccessToken(username, password); _authType = AuthType.Ptc; await SetServer(); Logger.Write("PTC login completed (" + !string.IsNullOrEmpty(_accessToken) + ")"); return _accessToken; }
public RequestBuilder(string authToken, AuthType authType, double latitude, double longitude, double altitude, AuthTicket authTicket = null) { _authToken = authToken; _authType = authType; _latitude = latitude; _longitude = longitude; _altitude = altitude; _authTicket = authTicket; }
/// <summary> /// CreateAuth /// </summary> public static OAuthBase CreateAuth(AuthType type) { switch (type) { case AuthType.Facebook: return new OAuthFacebook(); default: return null; } }
public void LoginShouldDelegateToAuthenticationManagerWithCorrectParameters(string login, string secret, AuthType authType) { var authenticationManager = Substitute.For<IAuthenticationManager>(); var client = new Client(null, null) {AuthenticationManager = authenticationManager}; client.Login(login, secret, authType); authenticationManager.Received(1).Login(login, secret, authType); }
/// <summary> /// Initializes a new CertificateVerificationResult instance. /// </summary> /// <param name="chain">The <see cref="CertificateChain"/> that has to be verified.</param> /// <param name="server">The server to which the <see cref="Certificate"/> has been issued.</param> /// <param name="type">One of the <see cref="AuthType"/> values.</param> /// <param name="flags">One of the <see cref="VerificationFlags"/> values.</param> /// <param name="callback">The delegate to call when the verification finishes.</param> /// <param name="asyncState">User-defined state data.</param> public CertificateVerificationResult(CertificateChain chain, string server, AuthType type, VerificationFlags flags, AsyncCallback callback, object asyncState) { m_Chain = chain; m_Server = server; m_Type = type; m_Flags = flags; m_AsyncState = asyncState; m_Callback = callback; m_WaitHandle = null; m_HasEnded = false; }
public bool CheckAuthToken(string clientId, string code, AuthType authType) { var query = (from d in ClientAuthorizationRepository.FindAll() let u = d.User let c = d.Client where c.ClientIdentifier == clientId && d.Token == code select d).FirstOrDefault(); if (query != null) return true; return false; }
public RequestBuilder(string authToken, AuthType authType, double latitude, double longitude, double altitude, AuthTicket authTicket = null) { _authToken = authToken; _authType = authType; _latitude = latitude; _longitude = longitude; _altitude = altitude; _authTicket = authTicket; if (!_internalWatch.IsRunning) _internalWatch.Start(); }
/// <summary> /// Send a query /// </summary> /// <param name="method">Method.</param> /// <param name="url">URL.</param> /// <param name="urlParams">URL parameters.</param> /// <param name="bodyParams">Body parameters.</param> /// <param name="authType">Auth type.</param> public async Task<ServerResponse> Query(QueryType method, String url, Dictionary<String, String> urlParams, Dictionary<String, String> bodyParams, AuthType authType) { App context = ((App)App.Current); HttpResponseMessage response = null; FormUrlEncodedContent body = null; String formattedUrl = formatUrl (url, urlParams); // Setting Authorization Header httpClient.DefaultRequestHeaders.Clear(); if (authType == AuthType.APP) { httpClient.DefaultRequestHeaders.Add ("Authorization", "Bearer " + context.appAuth.AccessToken); } else if (authType == AuthType.USER) { httpClient.DefaultRequestHeaders.Add ("Authorization", "Bearer " + context.userAuth.AccessToken); } // Building Body if (bodyParams != null) { body = new FormUrlEncodedContent(bodyParams); } // Sending Query switch (method) { case QueryType.GET: response = await httpClient.GetAsync (formattedUrl); break; case QueryType.POST: response = await httpClient.PostAsync (formattedUrl, body); break; case QueryType.PUT: response = await httpClient.PutAsync (formattedUrl, body); break; case QueryType.DELETE: response = await httpClient.DeleteAsync(formattedUrl); break; } Console.WriteLine ("[DEBUG] Request to {0} with status : {1}", formattedUrl, response.StatusCode); // If the request is rejected because of invalid token we try to refresh it if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) { if(authType == AuthType.APP) await ((App)App.Current).appAuth.Refresh (); if (authType == AuthType.USER) { bool userTokenRefresh = await ((App)App.Current).userAuth.Refresh (); if (!userTokenRefresh) throw new UserAuthFailedException (); // token refresh failed, user input is required ! } return await Query (method, url, urlParams, bodyParams, authType); } String content = await response.Content.ReadAsStringAsync (); JsonValue json = JsonObject.Parse (content); return new ServerResponse (response.StatusCode, json); }
/// <summary> /// Initializes a new instance of the AwsHttpConnection class with the specified AccessKey, SecretKey and Token. /// </summary> /// <param name="settings">The NEST/Elasticsearch.Net settings.</param> /// <param name="awsSettings">AWS specific settings required for signing requests.</param> public AwsHttpConnection(IConnectionConfigurationValues settings, AwsSettings awsSettings) : base(settings) { if (awsSettings == null) throw new ArgumentNullException("awsSettings"); if (string.IsNullOrWhiteSpace(awsSettings.AccessKey)) throw new ArgumentException("awsSettings.AccessKey is invalid.", "awsSettings"); if (string.IsNullOrWhiteSpace(awsSettings.SecretKey)) throw new ArgumentException("awsSettings.SecretKey is invalid.", "awsSettings"); if (string.IsNullOrWhiteSpace(awsSettings.Region)) throw new ArgumentException("awsSettings.Region is invalid.", "awsSettings"); _accessKey = awsSettings.AccessKey; _secretKey = awsSettings.SecretKey; _token = awsSettings.Token; _region = awsSettings.Region.ToLowerInvariant(); _authType = AuthType.AccessKey; }
protected ConnectionHolder GetConnectionFor(string userName, string password, IDirectoryAttributes userEntry = null, AuthType authType = AuthType.Basic) { if (userEntry == null) using (var holder = GetConnectionForServiceUser()) { userEntry = LookupUserEntry(holder, userName); if (userEntry == null) throw new ApplicationException(string.Format("No object was found with the user name {0}.", userName)); } return GetConnectionForCore(new NetworkCredential(userEntry.DistinguishedName, password), authType); }
/// <summary>Gets the data access object for the specified connection information</summary> /// <param name="ConnectionType">Type of database server to connect to</param> /// <param name="DataSource">Server to connect to</param> /// <param name="InitialCatalog">Initial database</param> /// <param name="Auth">Authentication method to use</param> /// <param name="Username">Username for basic authentication</param> /// <param name="Password">Password for basic authentication</param> /// <returns>DataAccessBase object for the specified connection type</returns> public static DataAccessBase GetDataAccess(ConnectionType ConnectionType, string DataSource, string InitialCatalog, AuthType Auth, string Username, string Password) { DataAccessBase dab = GetConnection(ConnectionType); dab.ConnectionType = ConnectionType; dab.DataSource = DataSource; dab.InitialCatalog = InitialCatalog; dab.Authentication = Auth; dab.Username = Username; dab.Password = Password; dab.Open(); return dab; }
/// <summary> /// This is purely a convience method to ensure the user is connected properly. /// It also checks if the user has an AuthLevel above the required level. /// </summary> private static void CheckAuth(AuthType required) { if (!Authenticated) { throw new Exception("Attempted to perform an action, while un-authenticated, which requires authentication."); } else { if (required >= AuthLevel) { throw new Exception("You don't have permission to perform this action."); } } }
public ActionResult Authenticate(AuthType authType) { var authHandler = AuthHandlerFactory.CreateAuthHandler(authType); string redirectUrl = authHandler .PrepareAuthRequest( Request, Url.Action("DoAuth", new { authType = (int)authType })); return Redirect(redirectUrl); }
public void BasicLdapConfig(ILdapUser adminUser, LDAPAdminMode adminMode, string server, string searchBaseDn, AuthType authType, LoggerType loggerType, string logPath) { BasicLdapConfigValidator(server, loggerType, logPath,searchBaseDn,adminUser,adminMode); _authType = authType; _searchBaseDn = searchBaseDn; _server = server; _adminUser = adminUser; _loggerType = loggerType; _logPath = logPath; _adminMode = adminMode; StandardLdapInformation(); }
internal SSHTerminalParam() { _method = ConnectionMethod.SSH2; _auth = AuthType.Password; _port = 22; }
/// <summary> /// Verifies the end <see cref="Certificate"/> according to the SSL policy rules. /// </summary> /// <param name="server">The server that returned the certificate -or- a null reference if the certificate is a client certificate.</param> /// <param name="type">One of the <see cref="AuthType"/> values.</param> /// <returns>One of the <see cref="CertificateStatus"/> values.</returns> /// <exception cref="CertificateException">An error occurs while verifying the certificate.</exception> public virtual CertificateStatus VerifyChain(string server, AuthType type) { return(VerifyChain(server, type, VerificationFlags.None)); }
private PingWebTestProperties CreatePingWebTestProperties(TestLocations testLocations, TestStatus testStatus, TestFrequency testFrequency, TestTimeout testTimeout, bool parseDependentRequests, RetriesForWebTestFailure retriesForWebTestFailure, int expectedHttpStatusCode = 200, AuthType authType = AuthType.None, string accessToken = null, string text = null) { var properties = new PingWebTestProperties() { Name = this._name, Description = string.Empty, TestStatus = testStatus, TestFrequency = testFrequency, TestTimeout = testTimeout, EnableRetriesForWebTestFailure = retriesForWebTestFailure, Locations = WebTestLocations.GetWebTestLocations(testLocations), Configuration = new PingWebTestConfiguration(this._name, this._url, (int)testTimeout, parseDependentRequests, expectedHttpStatusCode, authType, accessToken, text), SyntheticMonitorId = this._syntheticMonitorId, }; return(properties); }
public SamClient(AuthType authType, string authToken) : this(new SamAuth(authType, authToken)) { }
public RestifizerRequest WithClientAuth() { this.authType = AuthType.Client; return(this); }
public CustomAuthorizeAttribute(params string[] Roles) { Feature = ""; this.allowedroles = Roles; AuthType = AuthType.View; }
public SamAuth(AuthType type, string token) { this.Type = type; this.Token = token; }
/// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="userName">Username.</param> /// <param name="passwData">Password data.</param> /// <param name="data">Authentication specific data(as tag).</param> /// <param name="authType">Authentication type.</param> public AuthUser_EventArgs(IMAP_Session session, string userName, string passwData, string data, AuthType authType) { m_pSession = session; m_UserName = userName; m_PasswData = passwData; m_Data = data; m_AuthType = authType; }
/// <summary> /// Create a new instance of SMTP /// </summary> /// <param name="ipAddress">IP Address or Hostname</param> /// <param name="port">Port</param> /// <param name="username">SMTP Username</param> /// <param name="password">SMTP Password</param> /// <param name="authType">Authentication Type</param> /// <param name="useSSL">If TRUE, use SSL Connection</param> /// <param name="sslCertificateIsAlwaysSecure">If TRUE, SSL Certificate will always be marked as secure even if not</param> public SMTP(string ipAddress, string port, string username, string password, AuthType authType = AuthType.Login, bool useSSL = false, bool sslCertificateIsAlwaysSecure = false) { ConfigureSMTP(ipAddress, port, useSSL, sslCertificateIsAlwaysSecure); ConfigureLogin(username, password, authType); }
/// <summary> /// Sends an HTTP DELETE /// </summary> /// <param name="uri"></param> /// <param name="parameters"></param> /// <param name="creds"></param> /// <returns></returns> /// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception> public static NexmoResponse DoDeleteRequestWithUrlContent(Uri uri, Dictionary <string, string> parameters, AuthType authType = AuthType.Query, Credentials creds = null) => DoRequestWithUrlContent("DELETE", uri, parameters, authType, creds);
/// <summary> /// get access token from identity server /// </summary> /// <param name="request">AuthTokenRequest</param> /// <returns>AuthTokenResponse</returns> public static async Task <AuthTokenResponse> RequestAccesstokenAsync(AuthTokenRequest request, AuthType authType) { AuthTokenResponse authTokenResponse; var clientHandler = request.HttpClientHandler; var client = new DiscoveryClient(request.Authority, clientHandler) { Policy = new DiscoveryPolicy { RequireHttps = false } }; var response = await client.GetAsync(); if (response.IsError) { return(authTokenResponse = new AuthTokenResponse("", false, response.Error)); } TokenResponse tokenResponse; var tokenClient = new TokenClient(response.TokenEndpoint, request.Client, request.Secret, clientHandler); if (authType == AuthType.byCredential) { tokenResponse = await tokenClient.RequestClientCredentialsAsync(request.Api); } else { tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(request.UserName, request.Password, request.Api); } if (tokenResponse.IsError) { authTokenResponse = new AuthTokenResponse("", tokenResponse.IsError, tokenResponse.Error); } return(new AuthTokenResponse(tokenResponse.AccessToken, true, null)); }
/// <summary> /// Send a request to the versioned Nexmo API. /// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter. /// </summary> /// <param name="method">HTTP method (POST, PUT, DELETE, etc)</param> /// <param name="uri">The URI to communicate with</param> /// <param name="payload">Parameters required by the endpoint (do not include credentials)</param> /// <param name="authType">Authorization type used on the API</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception> public static T DoRequestWithJsonContent <T>(string method, Uri uri, object payload, AuthType authType, Credentials creds) { var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"]; var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]; var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower(); var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"]; var logger = Logger.LogProvider.GetLogger(LOGGER_CATEGORY); var req = new HttpRequestMessage { RequestUri = uri, Method = new HttpMethod(method), }; SetUserAgent(ref req, creds); if (authType == AuthType.Basic) { var authBytes = Encoding.UTF8.GetBytes(apiKey + ":" + apiSecret); req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authBytes)); } else if (authType == AuthType.Bearer) { // attempt bearer token auth req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Jwt.CreateToken(appId, appKeyPath)); } else if (authType == AuthType.Query) { var sb = BuildQueryString(new Dictionary <string, string>(), creds); req.RequestUri = new Uri(uri + (sb.Length != 0 ? "?" + sb : "")); } else { throw new ArgumentException("Unkown Auth Type set for function"); } var json = JsonConvert.SerializeObject(payload, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }); logger.LogDebug($"Request URI: {uri}"); logger.LogDebug($"JSON Payload: {json}"); var data = Encoding.UTF8.GetBytes(json); req.Content = new ByteArrayContent(data); req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var json_response = SendHttpRequest(req).JsonResponse; return(JsonConvert.DeserializeObject <T>(json_response)); }
/// <summary> /// Send a request to the Nexmo API using the specified HTTP method and the provided parameters. /// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter. /// </summary> /// <param name="method">HTTP method (POST, PUT, DELETE, etc)</param> /// <param name="uri">The URI to communicate with</param> /// <param name="parameters">Parameters required by the endpoint (do not include credentials)</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception> /// <returns></returns> public static NexmoResponse DoRequestWithUrlContent(string method, Uri uri, Dictionary <string, string> parameters, AuthType authType = AuthType.Query, Credentials creds = null) { var logger = Logger.LogProvider.GetLogger(LOGGER_CATEGORY); var sb = new StringBuilder(); // if parameters is null, assume that key and secret have been taken care of if (null != parameters) { sb = GetQueryStringBuilderFor(parameters, authType, creds); } var req = new HttpRequestMessage { RequestUri = uri, Method = new HttpMethod(method) }; if (authType == AuthType.Basic) { var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower(); var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"]; var authBytes = Encoding.UTF8.GetBytes(apiKey + ":" + apiSecret); req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authBytes)); } SetUserAgent(ref req, creds); var data = Encoding.ASCII.GetBytes(sb.ToString()); req.Content = new ByteArrayContent(data); req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded"); logger.LogDebug($"{method} {uri} {sb}"); return(SendHttpRequest(req)); }
internal SystemAssignedIdentityAuthInfo(AuthType authType) : base(authType) { AuthType = authType; }
/// <summary> /// Creates a new bucket on the cluster /// </summary> /// <param name="name">Required parameter. Name for new bucket.</param> /// <param name="ramQuota">The RAM quota in megabytes. The default is 100.</param> /// <param name="bucketType">Required parameter. Type of bucket to be created. “Memcached” configures as Memcached bucket. “Couchbase” configures as Couchbase bucket</param> /// <param name="replicaNumber">The number of replicas of each document: minimum 0, maximum 3.</param> /// <param name="authType">The authentication type.</param> /// <param name="indexReplicas">Disable or enable indexes for bucket replicas.</param> /// <param name="flushEnabled">Enables the flush functionality on the specified bucket.</param> /// <param name="parallelDbAndViewCompaction">Indicates whether database and view files on disk can be compacted simultaneously.</param> /// <param name="saslPassword">Optional Parameter. String. Password for SASL authentication. Required if SASL authentication has been enabled.</param> /// <param name="threadNumber">Optional Parameter. Integer from 2 to 8. Change the number of concurrent readers and writers for the data bucket. </param> /// <returns>A boolean value indicating the result.</returns> public Task <IResult> CreateBucketAsync(string name, uint ramQuota = 100, BucketTypeEnum bucketType = BucketTypeEnum.Couchbase, ReplicaNumber replicaNumber = ReplicaNumber.Two, AuthType authType = AuthType.Sasl, bool indexReplicas = false, bool flushEnabled = false, bool parallelDbAndViewCompaction = false, string saslPassword = "", ThreadNumber threadNumber = ThreadNumber.Three) { return(CreateBucketAsync(name, 0, ramQuota, bucketType, replicaNumber, authType, indexReplicas, flushEnabled, parallelDbAndViewCompaction, saslPassword, threadNumber)); }
private static AuthenticationType ConvertAuth(AuthType t) { return(t == AuthType.Password ? AuthenticationType.Password : t == AuthType.PublicKey ? AuthenticationType.PublicKey : AuthenticationType.KeyboardInteractive); }
public LoginEvent(AuthType authType, string v) { AuthType = authType; Username = v; }
/// <summary> /// Allows you to specify an authentication method for the /// connection. If this method is not called, the authentication method /// will be resolved by the <see cref="LdapConnection"/>. /// </summary> /// <param name="authType"> /// The type of authentication to use. /// </param> /// <returns></returns> public ILdapConnectionFactoryConfiguration AuthenticateBy(AuthType authType) { AuthType = authType; return(this); }
public static DatabaseClient NewClient(string _host, string _port, string _username, string _password, string _realm, AuthType _authType) { if (_host == null) { throw new System.ArgumentException("host parameter cannot be null", _host); } else if (_port == null) { throw new System.ArgumentException("port parameter cannot be null", _port); } else if (_username == null) { throw new System.ArgumentException("username parameter cannot be null", _username); } else if (_password == null) { throw new System.ArgumentException("password parameter cannot be null", _password); } else if (_realm == null) { throw new System.ArgumentException("realm parameter cannot be null", _realm); } DatabaseClientImpl DbClient = new DatabaseClientImpl(); DbClient.SetConnection(_host, _port, _username, _password, _realm, _authType); return(DbClient); }
internal ApiConnector(PenneoConnector con, RestResources restResources, string endpoint, Dictionary <string, string> headers, string user, string key, string secret, AuthType authType) { _con = con; _restResources = restResources; _endpoint = endpoint; _headers = headers; _user = user; _key = key; _secret = secret; _authType = authType; Init(); }
internal UserAssignedIdentityAuthInfo(AuthType authType, string clientId, string subscriptionId) : base(authType) { ClientId = clientId; SubscriptionId = subscriptionId; AuthType = authType; }
public SmtpNoSslClient(string serverName, int port, MailAddress mailFrom, string password, AuthType type) : base(serverName, port, mailFrom, password) { writer = new StreamWriter(netStream); Auth(mailFrom.Address, password, type); }
public void SetAuth(AuthType authType, string authToken) { this.ApiAuth = new SamAuth(authType, authToken); }
public static bool IsIncludedIn(this AuthType first, AuthType second) { return((first & second) != 0); }
public RestifizerRequest WithBearerAuth() { this.authType = AuthType.Bearer; return(this); }
/// <summary> /// Create auth using an authorization header. /// </summary> /// <param name="header"></param> public UrlPdfPrinterAuth(string header) { _header = header; _type = AuthType.Header; }
/// <summary> /// Authenticates user. /// </summary> /// <param name="session">Reference to current pop3 session.</param> /// <param name="userName">User name.</param> /// <param name="passwData"></param> /// <param name="data"></param> /// <param name="authType"></param> /// <returns></returns> internal virtual bool OnAuthUser(FTP_Session session, string userName, string passwData, string data, AuthType authType) { AuthUser_EventArgs oArg = new AuthUser_EventArgs(session, userName, passwData, data, authType); if (this.AuthUser != null) { this.AuthUser(this, oArg); } return(oArg.Validated); }
/// <summary> /// Create auth using a cookie. /// </summary> /// <param name="cookie"></param> public UrlPdfPrinterAuth(Cookie cookie) { _cookie = cookie; _type = AuthType.Cookie; }
/// <summary> /// Internal method for Make API Calls /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="apiEndpoint"></param> /// <param name="request"></param> /// <param name="authType"></param> /// <param name="resultCallback"></param> /// <param name="errorCallback"></param> /// <param name="customData"></param> protected internal static void MakeApiCall <TResult>(string apiEndpoint, PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback, Action <PlayFabError> errorCallback, object customData = null, bool allowQueueing = false) where TResult : PlayFabResultCommon { InitializeHttp(); SendEvent(request, null, ApiProcessingEventType.Pre); var reqContainer = new CallRequestContainer(); #if PLAYFAB_REQUEST_TIMING reqContainer.Timing.StartTimeUtc = DateTime.UtcNow; reqContainer.Timing.ApiEndpoint = apiEndpoint; #endif reqContainer.ApiEndpoint = apiEndpoint; reqContainer.FullUrl = PlayFabSettings.GetFullUrl(apiEndpoint); reqContainer.CustomData = customData; reqContainer.Payload = Encoding.UTF8.GetBytes(JsonWrapper.SerializeObject(request, PlayFabUtil.ApiSerializerStrategy)); reqContainer.AuthKey = authType; reqContainer.ApiRequest = request; reqContainer.ErrorCallback = errorCallback; // These closures preserve the TResult generic information in a way that's safe for all the devices reqContainer.DeserializeResultJson = () => { reqContainer.ApiResult = JsonWrapper.DeserializeObject <TResult>(reqContainer.JsonResponse, PlayFabUtil.ApiSerializerStrategy); }; reqContainer.InvokeSuccessCallback = () => { if (resultCallback != null) { resultCallback((TResult)reqContainer.ApiResult); } }; if (allowQueueing && _apiCallQueue != null && !_internalHttp.SessionStarted) { for (var i = _apiCallQueue.Count - 1; i >= 0; i--) { if (_apiCallQueue[i].ApiEndpoint == apiEndpoint) { _apiCallQueue.RemoveAt(i); } } _apiCallQueue.Add(reqContainer); } else { _internalHttp.MakeApiCall(reqContainer); } }
/// <summary> /// Creates a new instance of the web test properties inheriting the <see cref="WebTestProperties"/> class. /// </summary> /// <param name="testLocations"><see cref="TestLocations"/> value.</param> /// <param name="testStatus"><see cref="TestStatus"/> value.</param> /// <param name="testFrequency"><see cref="TestFrequency"/> value.</param> /// <param name="testTimeout"><see cref="TestTimeout"/> value.</param> /// <param name="parseDependentRequests">Value indicating whether to parse dependent requests or not.</param> /// <param name="retriesForWebTestFailure"><see cref="RetriesForWebTestFailure"/> value.</param> /// <param name="expectedHttpStatusCode">HTTP status code expected. Default value is <c>200</c>.</param> /// <param name="authType"><see cref="AuthType"/> value.</param> /// <param name="accessToken">Access token value.</param> /// <param name="text">Text to find in the validation rule.</param> public void CreateWebTestProperties(TestLocations testLocations, TestStatus testStatus, TestFrequency testFrequency, TestTimeout testTimeout, bool parseDependentRequests, RetriesForWebTestFailure retriesForWebTestFailure, int expectedHttpStatusCode = 200, AuthType authType = AuthType.None, string accessToken = null, string text = null) { WebTestProperties properties; switch (this._testType) { case TestType.UrlPingTest: properties = this.CreatePingWebTestProperties(testLocations, testStatus, testFrequency, testTimeout, parseDependentRequests, retriesForWebTestFailure, expectedHttpStatusCode, authType, accessToken, text); break; case TestType.MultiStepTest: properties = new MultiStepWebTestProperties(); break; default: properties = null; break; } this.Properties = properties; }