Example #1
0
        private SearchInfoRequest PrepareEnrichmentRequest()
        {
            string serviceUrl;
            string apiKey;

            GetRequiredParameters(out serviceUrl, out apiKey);
#if NETFRAMEWORK
            _restClient.BaseUrl = serviceUrl;
#else
            _restClient.BaseUrl = new Uri(serviceUrl);
#endif
            _restClient.AddDefaultHeader("ApiKey", apiKey);
            int maxSocialLinksCount  = SysSettings.GetValue(UserConnection, "EnrichmentSocialLinksLimit", 3);
            int maxPhoneNumbersCount = SysSettings.GetValue(UserConnection, "EnrichmentPhoneNumbersLimit", 3);
            int maxEmailsCount       = SysSettings.GetValue(UserConnection, "EnrichmentEmailsLimit", 3);
            var requestBody          = new SearchInfoRequest {
                ApiKey = apiKey,
                Config = new SearchInfoConfiguration {
                    MaxSocialLinksCount = maxSocialLinksCount,
                    MaxPhoneNumberCount = maxPhoneNumbersCount,
                    MaxEmailsCount      = maxEmailsCount
                }
            };
            return(requestBody);
        }
        public BaseClient(string apiKey)
        {
            if (String.IsNullOrEmpty(apiKey))
            {
                throw new ArgumentException($"apiKey is required. You passed in {apiKey}");
            }

            ApiKey                   = apiKey;
            RestClient               = new RestClient();
            RestClient.BaseUrl       = new Uri(ApiUrl);
            RestClient.Authenticator = new HttpBasicAuthenticator(ApiKey, "");

            // AddDefaultHeader does not work for user-agent
            var libVersion = typeof(Recurly.Client).Assembly.GetName().Version;

            RestClient.UserAgent = $"Recurly/{libVersion}; .NET";

            Array.ForEach(BinaryTypes, contentType =>
                          RestClient.AddHandler(contentType, () => { return(new Recurly.FileSerializer()); })
                          );
            RestClient.AddHandler("application/json", () => { return(new JsonSerializer()); });

            // These are the default headers to send on every request
            RestClient.AddDefaultHeader("Accept", $"application/vnd.recurly.{ApiVersion}");
            RestClient.AddDefaultHeader("Content-Type", "application/json");
        }
        public LanguageAnalyzer(string key)
        {
            _client = new RestClient("https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0");

            _client.AddDefaultHeader("Ocp-Apim-Subscription-Key", key);
            _client.AddDefaultHeader("Content-Type", "application/json");
            _client.AddDefaultHeader("Accept", "application/json");
        }
Example #4
0
 public AuditService(IConfigurationHelper configurationHelper)
 {
     _configurationHelper = configurationHelper;
     _restClient          = new RestClient();
     _restClient.BaseUrl  = new Uri(_configurationHelper.OssIndexUri);
     _restClient.AddDefaultHeader("accept", "application/vnd.ossindex.component-report.v1+json");
     _restClient.AddDefaultHeader("Content-Type", "application/json");
     _restClient.Authenticator = new SimpleAuthenticator("username", _configurationHelper.Username, "password", _configurationHelper.ApiKey);
 }
Example #5
0
        internal RestClientManager(SnipeItApi api, IRestClient client)
        {
            this.Api    = api;
            this.Client = client;

            Client.AddDefaultHeader("Accept", "application/json");
            Client.AddDefaultHeader("Cache-Control", "no-cache");
            Client.AddDefaultHeader("Content-type", "application/json");
        }
        /// <summary>
        /// This should be called before any call to <see cref="IRestClient"/>,
        /// it sets up the auth token and default headers per the AMS V2 API specification.
        /// </summary>
        private void ConfigureRestClient()
        {
            if (!isConfigured)
            {
                Exception exceptionInLock = null;
                lock (configLock)
                {
                    if (!isConfigured)
                    {
                        try
                        {
                            string amsRestApiEndpoint = GetAmsRestApiEndpoint();
                            _restClient = new RestClient(amsRestApiEndpoint);

                            // Acquire a token for AMS.
                            // Ref: https://docs.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=dotnet#asal
                            var    azureServiceTokenProvider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();
                            string amsAccessToken            = azureServiceTokenProvider.GetAccessTokenAsync(AmsRestApiResource).Result;

                            _restClient.Authenticator = new JwtAuthenticator(amsAccessToken);

                            _restClient.UseNewtonsoftJson(
                                new Newtonsoft.Json.JsonSerializerSettings()
                            {
                                ContractResolver = new DefaultContractResolver(),
                            });

                            _restClient.AddDefaultHeader("Content-Type", $"{ContentType.Json};odata=verbose");
                            _restClient.AddDefaultHeader("Accept", $"{ContentType.Json};odata=verbose");
                            _restClient.AddDefaultHeader("DataServiceVersion", "3.0");
                            _restClient.AddDefaultHeader("MaxDataServiceVersion", "3.0");
                            _restClient.AddDefaultHeader("x-ms-version", "2.19");
                        }
                        catch (Exception e)
                        {
                            exceptionInLock = e;
                            _log.LogError(e, $"Failed in {nameof(ConfigureRestClient)}.\nException.Message:\n{e.Message}\nInnerException.Message:\n{e.InnerException?.Message}");
                        }
                        finally
                        {
                            isConfigured = true;
                        }
                    }
                }

                if (exceptionInLock != null)
                {
                    throw exceptionInLock;
                }
            }

            return;
        }
        public NameComClient(IRestClient client, string userName, string token)
        {
            _client = client;
            _client.AddDefaultHeader("Api-Username", userName);
            _client.AddDefaultHeader("Api-Token", token);

            //server returns invalid header for json content
            //Content-Type: text/html; charset=UTF-8
            //instead of
            //Content-Type: application/json; charset=UTF-8
            _client.RemoveHandler("text/html");
            _client.AddHandler("text/html", new JsonDeserializer());
        }
        /// <summary>
        /// Configures the RestSharp RestClient.
        /// </summary>
        private void ConfigureRestClient()
        {
            if (!isConfigured)
            {
                Exception exceptionInLock = null;
                lock (configLock)
                {
                    if (!isConfigured)
                    {
                        try
                        {
                            var amsAccessToken = _tokenCredential.GetToken(
                                new TokenRequestContext(
                                    scopes: new[] { "https://rest.media.azure.net/.default" },
                                    parentRequestId: null),
                                default);

                            _restClient.Authenticator = new JwtAuthenticator(amsAccessToken.Token);

                            _restClient.UseNewtonsoftJson(
                                new Newtonsoft.Json.JsonSerializerSettings()
                            {
                                ContractResolver = new DefaultContractResolver(),
                            });

                            _restClient.AddDefaultHeader("Content-Type", $"{ContentType.Json};odata=verbose");
                            _restClient.AddDefaultHeader("Accept", $"{ContentType.Json};odata=verbose");
                            _restClient.AddDefaultHeader("DataServiceVersion", "3.0");
                            _restClient.AddDefaultHeader("MaxDataServiceVersion", "3.0");
                            _restClient.AddDefaultHeader("x-ms-version", "2.19");
                        }
                        catch (Exception e)
                        {
                            exceptionInLock = e;
                            _log.LogError(e, $"Failed to {nameof(ConfigureRestClient)}");
                        }
                        finally
                        {
                            isConfigured = true;
                        }
                    }
                }

                if (exceptionInLock != null)
                {
                    throw exceptionInLock;
                }
            }

            return;
        }
Example #9
0
        public async Task <bool> ValidateToken(string token)
        {
            var ssoApiUrl = _ssoApiModel.Value.Url;
            var endPoint  = _ssoApiModel.Value.Endpoint.ValidateToken;

            _client.AddDefaultHeader("Authorization", token);
            _request.Parameters.Clear();
            _request.Resource = ssoApiUrl + endPoint;
            _request.Method   = Method.POST;
            _request.AddHeader("Content-type", "application/json");
            var response = await _client.ExecuteAsync(_request);

            return(response.StatusCode == HttpStatusCode.OK);
        }
Example #10
0
        public object QueryWorkPackage()
        {
            SetParameters();

            _restRequest.Parameters.Clear();

            _restClient.BaseUrl = new Uri(StringUri);
            _restRequest.AddHeader("Content-type", "application/json");

            //-------------ACESSO POR TOKEN-------------------\\
            //_restClient.AddDefaultHeader("Authorization", string.Format("Bearer {0}", AccessToken));

            //-------------ACESSO POR USUÁRIO E SENHA-------------------\\
            //_restClient.AddDefaultHeader("Authorization", string.Format("Bearer {0}, {1}", AuthUser[0].Trim().ToLower(), AuthUser[1].Trim().ToLower()));

            //-------------ACESSO POR TOKEN-------------------\\
            _restClient.AddDefaultHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes($"apikey:{AccessToken}")));
            _restRequest.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes($"apikey:{AccessToken}")));

            _restRequest.Credentials   = credential;
            _restRequest.Resource      = queryWorkPackage;
            _restRequest.RequestFormat = DataFormat.Json;

            var result = _restClient.Get <WorkPackage>(_restRequest);

            return(result);
        }
        /// <summary>
        /// Add the current CorrelatorSharp.ActivityScope identifier as a default http header (X-Correlator-Id).
        ///
        /// Be aware this will add a default header at the call time, and will not be refreshed at the point of execution of any requests.
        /// Please take note of the lifetime and scope of the IRestClient instance before using.
        /// </summary>
        /// <param name="client">The RestSharp.IRestClient</param>
        public static void AddCorrelationHeader(this IRestClient client)
        {
            var scope = ActivityScope.Current ?? ActivityScope.New(client.BaseUrl.ToString());

            client.AddDefaultHeader(Headers.CorrelationId, scope.Id);

            if (string.IsNullOrWhiteSpace(scope.ParentId) == false)
            {
                client.AddDefaultHeader(Headers.CorrelationParentId, scope.ParentId);
            }

            if (string.IsNullOrWhiteSpace(scope.Name) == false)
            {
                client.AddDefaultHeader(Headers.CorrelationName, scope.Name);
            }
        }
Example #12
0
 /// <summary>
 ///     Set the default access token to be used on each request. If the token is null, no action is performed.
 /// </summary>
 /// <param name="token">The access token to be set as the default</param>
 private void SetAuthorizationToken(AccessToken token)
 {
     if (_restClient.DefaultParameters.All(x => x.Name != "Authorization"))
     {
         _restClient.AddDefaultHeader("Authorization", $"Bearer {token.Token}");
     }
 }
Example #13
0
        private void InitClients(string apiKey)
        {
            var jsonSerializerSettings = new JsonSerializerSettings()
            {
                Error      = OnError,
                Converters = new List <JsonConverter>
                {
                    new StringEnumConverter(),
                    new IsoDateTimeConverter()
                    {
                        DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
                    }
                },
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
            };

            _client = new RestClient(BaseUrl);

            _client.ThrowOnAnyError             = true;
            _client.ThrowOnDeserializationError = true;

            _client.AddDefaultHeader(ApiKeyHeaderName, apiKey);
            _client.UseNewtonsoftJson(jsonSerializerSettings);



            _experimentalClient = new RestClient(ExperimentalApiUrl);
            _experimentalClient.AddDefaultHeader(ApiKeyHeaderName, apiKey);
            _client.UseNewtonsoftJson(jsonSerializerSettings);
        }
Example #14
0
        public async Task <IEnumerable <DesignDto> > GetStates(string userId)
        {
            var baseUrl = _settings.Url + $"api/users/{userId}/states";

            _client = new RestClient(baseUrl);
            _client.AddDefaultHeader("X-CustomersCanvasAPIKey", _settings.ApiKey);

            var request  = new RestRequest(Method.GET);
            var response = await _client.ExecuteAsync <IEnumerable <CanvasState> >(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK || response.ErrorException != null)
            {
                return(null);
            }

            var result = new List <DesignDto>();
            var states = response.Data.Select(x => x.StateId);

            baseUrl = _settings.Url + "api/Preview/GeneratePreview";
            var client = new RestClient(baseUrl);

            client.AddDefaultHeader("X-CustomersCanvasAPIKey", _settings.ApiKey);
            foreach (var state in states)
            {
                var preview = await GetPreviewForState(client, userId, state);

                result.Add(new DesignDto()
                {
                    Id      = state,
                    Preview = preview
                });
            }

            return(result);
        }
Example #15
0
        public AgsClient(string host, string instance, int?port, bool useSSL, string username, string password)
        {
            bool anonymous = String.IsNullOrWhiteSpace(username);

            var builder = new UriBuilder()
            {
                Scheme = useSSL ? "https" : "http",
                Host   = host,
                Port   = port ?? 80,
                Path   = instance,
            };

            Uri baseUrl = builder.Uri;

            restSharpClient = new RestClient(baseUrl).UseSerializer(() => new JsonNetSerializer());
            restSharpClient.AddDefaultHeader("Content-Type", "application/x-www-form-urlencoded");

            if (!anonymous) // try to get a token
            {
                credentials = new Credentials {
                    username = username, password = password
                };

                //1. check if token based security available
                ServerInfoResource serverInfo = new ServerInfoRequest().Execute(this);
                if ((serverInfo.authInfo != null) && (serverInfo.authInfo.isTokenBasedSecurity))
                {
                    tokenServiceUrl = serverInfo.authInfo.tokenServicesUrl;
                    refreshToken(credentials, client_id_type, null, null, token_request_expiration_minutes);
                    useToken = true;
                }
            }
        }
Example #16
0
        public OnPayApi(string accessToken)
        {
            _accessToken = accessToken;

            _resourceClient = new RestClient("https://api.onpay.io/");
            _resourceClient.AddDefaultHeader("Authorization", "Bearer " + _accessToken);
        }
Example #17
0
        public McAfeeApi(IMcAfeeConfiguration configuration)
        {
            Guard.AgainstNull(configuration, nameof(configuration));

            _configuration = configuration;
            _url           = configuration.Url;

            if (!_url.EndsWith("/"))
            {
                _url += "/";
            }

            _client = new RestClient(configuration.Url);

            _client.AddDefaultHeader("Accept", "application/vnd.ve.v1.0+json");

            var cancellationToken = _cancellationTokenSource.Token;

            _task = Task.Run(() =>
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    Heartbeat();

                    ThreadSleep.While(1000, cancellationToken);

                    if (DateTime.Now > _nextLogin)
                    {
                        Logout();
                    }
                }
            });

            _log = Log.For(this);
        }
Example #18
0
        private void InitClients(string apiKey, string apiUrl, string experimentalApiUrl, string reportsApi)
        {
            var jsonSerializerSettings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,

                Converters = new List <JsonConverter> {
                    new StringEnumConverter(),
                    new IsoDateTimeConverter()
                    {
                        DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
                    },
                },
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
            };

            _client = new RestClient(apiUrl);
            _client.AddDefaultHeader(ApiKeyHeaderName, apiKey);
            _client.UseNewtonsoftJson(jsonSerializerSettings);

            _experimentalClient = new RestClient(experimentalApiUrl);
            _experimentalClient.AddDefaultHeader(ApiKeyHeaderName, apiKey);
            _experimentalClient.UseNewtonsoftJson(jsonSerializerSettings);

            _reportsClient = new RestClient(reportsApi);
            _reportsClient.AddDefaultHeader(ApiKeyHeaderName, apiKey);
            _reportsClient.UseNewtonsoftJson(jsonSerializerSettings);
        }
Example #19
0
 public PushNotificationService(IConfiguration configuration)
 {
     _configuration = configuration;
     Client         = new RestClient("https://fcm.googleapis.com/fcm/");
     Client.UseNewtonsoftJson();
     Client.AddDefaultHeader("Authorization", "key=" + _configuration["FcmApiKey"]);
 }
Example #20
0
 private void SetAuthorization(HttpContext context)
 {
     if (context.Request.Headers.TryGetValue("Authorization", out var token))
     {
         _restClient.AddDefaultHeader("Authorization", token);
     }
 }
Example #21
0
 public void ConfigureAuthorization(string personalAccessToken)
 {
     if (_restClient.DefaultParameters.All(x => x.Name != "Authorization"))
     {
         _restClient.AddDefaultHeader("Authorization", $"Bearer {personalAccessToken}");
     }
 }
Example #22
0
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            client.AddDefaultHeader("Authorization", AccessToken);
            request.Method = Method.POST;

            request.AddJsonBody(BodyObject);
        }
Example #23
0
 public void UpdateAuthToken(string authToken)
 {
     client.RemoveDefaultParameter(HttpRequestHeader.Authorization.ToString());
     client.AddDefaultHeader(
         HttpRequestHeader.Authorization.ToString(),
         $"{AuthenticationSchema} {authToken}");
 }
Example #24
0
 private void UpdateRequestHeadersForRefreshToken(IRestRequest request, string token)
 {
     // Update authorization parameters
     _client.RemoveDefaultParameter("Authorization");
     _client.AddDefaultHeader("Authorization", $"Bearer {token}");
     request.AddOrUpdateParameter("Authorization", $"Bearer {token}");
 }
Example #25
0
        public Client(string basePath, string accessToken)
        {
            BasePath    = basePath;
            AccessToken = accessToken;

            client = new RestClient(basePath);
            client.AddDefaultHeader("x-access-token", accessToken);
        }
        public IRestClient BuildClient()
        {
            lock (_syncLock)
            {
                if (ShouldRefreshContext())
                {
                    _context = _contextBuilder.CreateContext();
                    _client  = new RestClient(Constants.ApiUrlBase);
                    _client.AddDefaultHeader(Constants.RestClientId, Guid.NewGuid().ToString());
                    _client.AddDefaultHeader(Constants.AplosApiClientTypeHeaderKey, Constants.AplosApiClientTypeHeaderValue);
                    _client.AddDefaultHeader(Constants.AplosAuthExpiresHeaderKey, _context.Expires.ToString("O"));
                    _client.AddDefaultHeader(Constants.AuthorizationHeader, $"{Constants.AuthorizationType} {_context.AuthToken}");
                }

                return(_client);
            }
        }
Example #27
0
 public Client(string gitLabDomain, string oAuthToken)
 {
     this.gitLabDomain = !string.IsNullOrEmpty(gitLabDomain)
                         ? gitLabDomain
                         : throw new ArgumentNullException(nameof(gitLabDomain));
     client = new RestClient(this.gitLabDomain).UseSerializer(() => new JsonNetSerializer());
     client.AddDefaultHeader(HttpRequestHeader.Authorization.ToString(), $"{AuthenticationSchema} {oAuthToken}");
 }
Example #28
0
 private void InitClients(string apiKey)
 {
     _client = new RestClient(BaseUrl);
     _client.AddDefaultHeader(ApiKeyHeaderName, apiKey);
     _experimentalClient = new RestClient(ExperimentalApiUrl);
     _experimentalClient.AddDefaultHeader(ApiKeyHeaderName, apiKey);
     SimpleJson.CurrentJsonSerializerStrategy = new CamelCaseSerializerStrategy();
 }
Example #29
0
        public async Task SetDefaultHeader()
        {
            _restClient.AddDefaultHeader(new RestHeader("MyKey", "MyValue"));

            var value = await _restClient.GetAsync <string>("api/test/mykey");

            Assert.That(value, Is.EqualTo("MyValue"));
        }
Example #30
0
        static void Main(string[] args)
        {
            _token      = File.ReadAllText("authenticationtoken.txt");
            _restClient = new RestClient(HostedFunctionsApiUrl);
            _restClient.AddDefaultHeader("X-ZUMO-AUTH", _token);

            ShowRequestOptions();
        }
 public void Authenticate(IRestClient client, IRestRequest request)
 {
     client.AddDefaultHeader("Authorization", clientId);
 }
 public void Authenticate(IRestClient client, IRestRequest request)
 {
     client.AddDefaultHeader("X-TM-Username", Username);
     client.AddDefaultHeader("X-TM-Key", Token);
 }
Example #33
0
 public void Authenticate(IRestClient client, IRestRequest request)
 {
     client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", token));
 }