static public void Main ()
    {
        Console.WriteLine ("Trying to send");
        var username = "******";
        var password = "******";
        var postData = new List<KeyValuePair<string, string>>()
            {
            new KeyValuePair<string, string>("from", "+4676865201"),
            new KeyValuePair<string, string>("to", "+46723175800"),
            new KeyValuePair<string, string>("voice_start", '{"connect":"+461890510"}')
            };
                                
        string creds = string.Format("{0}:{1}", username, password);
        byte[] bytes = Encoding.ASCII.GetBytes(creds);
        var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
        var content = new FormUrlEncodedContent(postData);
        
        HttpClient Client = new HttpClient();
        Client.DefaultRequestHeaders.Authorization = header;
            
        var responseMessage =  Client.Post("https://api.46elks.com/a1/Calls", content);
        var response = esponseMessage.Content.ReadAsString();
        Console.WriteLine (response);
    }
}
        /// <summary>
        /// Illustrates how to get token without OAuth2Client helper
        /// </summary>
        /// <returns></returns>
        public static string GetTokenExplained()
        {
            //data to post to the token endpoint
            var fields = new Dictionary<string, string>
            {
                { "scope", "bimtoolkitapi" },
                { "grant_type", "client_credentials" }
            };

            //setup basic authentication
            string creds = String.Format("{0}:{1}", _clientId, _clientSecret);
            byte[] bytes = Encoding.ASCII.GetBytes(creds);
            var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));

            //configure client
            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = header;
            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["Authority"] + "/connect/token");

            //get response and parse as json
            var response = client.PostAsync(string.Empty, new FormUrlEncodedContent(fields)).Result;
            string raw = response.Content.ReadAsStringAsync().Result;
            var json = JObject.Parse(raw);

            //try to get the access token from the json response
            JToken token;
            if (json.TryGetValue("access_token", out token))
            {
                return token.ToString();
            }

            return "";
        }
        public async Task<Client> ValidateClientAsync(NameValueCollection parameters, AuthenticationHeaderValue header)
        {
            Logger.Info("Start client validation");

            // validate client credentials on the wire
            var credential = ValidateHttpRequest(header, parameters);

            if (credential.IsMalformed || !credential.IsPresent)
            {
                LogError("No or malformed client credential found.");
                return null;
            }

            _log.ClientId = credential.ClientId;
            _log.ClientCredentialType = credential.Type;

            // validate client against configuration store
            var client = await ValidateClientCredentialsAsync(credential);
            if (client == null)
            {
                return null;
            }

            _log.ClientName = client.ClientName;

            LogSuccess();
            return client;
        }
 public AzureMLAuthenticatedHttpClient(IAzureMLFrequentlyBoughtTogetherConfig config)
 {
     //Basic Auth requires a user name, even though it's not used. We use the key as user name.
     var accountKey = Encoding.ASCII.GetBytes($"{config.AccountKey}:{config.AccountKey}");
     var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(accountKey));
     DefaultRequestHeaders.Authorization = header;
 }
        public void ToString_UseBothNoParameterAndSetParameter_AllSerializedCorrectly()
        {
            using (HttpResponseMessage response = new HttpResponseMessage())
            {
                string input = string.Empty;

                AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Digest",
                    "qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"");

                Assert.Equal(
                    "Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"",
                    auth.ToString());
                response.Headers.ProxyAuthenticate.Add(auth);
                input += auth.ToString();

                auth = new AuthenticationHeaderValue("Negotiate");
                Assert.Equal("Negotiate", auth.ToString());
                response.Headers.ProxyAuthenticate.Add(auth);
                input += ", " + auth.ToString();

                auth = new AuthenticationHeaderValue("Custom", ""); // empty string should be treated like 'null'.
                Assert.Equal("Custom", auth.ToString());
                response.Headers.ProxyAuthenticate.Add(auth);
                input += ", " + auth.ToString();

                string result = response.Headers.ProxyAuthenticate.ToString();
                Assert.Equal(input, result);
            }
        }
Beispiel #6
0
        public IEnumerable<Models.Contact> GetContacts()
        {
            try
            {
                var header = Request.Headers;
                IEnumerable<string> email;
                IEnumerable<string> pass;
                header.TryGetValues("e", out email);
                header.TryGetValues("p", out pass);
                var credentials = header.Authorization;

                var e = email.FirstOrDefault();
                var p = pass.FirstOrDefault();
                var base64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", e, p)));
                var temp = new AuthenticationHeaderValue("Basic", base64);
                if(temp.Parameter != credentials.Parameter)
                {
                    return null;
                }
                e = RSAUtil.RsaDecryptWithPrivate(e);
                p = RSAUtil.RsaDecryptWithPrivate(p);
                if (e != null && p != null)
                {
                    return Office365Data.Instance().GetContacts(e, p);
                }
            }
            catch
            {
                return null;
            }
            return null;
        }
        public static IDictionary<string, string> ParseAuthHeader(AuthenticationHeaderValue header)
        {
            if(header == null) {
                return null;
            }

            var retVal = new Dictionary<string, string>();
            var raw = header.Parameter;
            var regex = new Regex("(\\w+)=((\\w+)|\"([^\"]+))");
            var matches = regex.Matches(raw);
            if(matches.Count > 0) { 
                var groups = matches[0].Groups;
                var key = groups[1].Value;
                var k = groups[3];
                if(!k.Success) {
                    k = groups[4];
                }

                retVal[key] = k.Value;
                retVal["Scheme"] = header.Scheme;
            }

            retVal["WWW-Authenticate"] = header.ToString();
            return retVal;
        }
 private string[] GetCredentials(AuthenticationHeaderValue authHeader)
 {
     var raw = authHeader.Parameter;
     var encoding = Encoding.ASCII;
     var credentials = encoding.GetString(Convert.FromBase64String(raw));
     return credentials.Split(':');
 }
        private AuthenticationHeaderValue(AuthenticationHeaderValue source)
        {
            Debug.Assert(source != null);

            _scheme = source._scheme;
            _parameter = source._parameter;
        }
 public static AuthenticationHeaderValue Create(Guid userProviderKey)
 {
     string authInfo = userProviderKey + ":" + string.Empty;
     authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
     var authenticationHeaderValue = new AuthenticationHeaderValue("Basic", authInfo);
     return authenticationHeaderValue;
 }
        private Credentials ExtractCredentials(AuthenticationHeaderValue authHeader)
        {
            try
            {
                if (authHeader == null)
                {
                    return null;
                }

                var encodedUserPass = authHeader.Parameter.Trim();

                Credentials credentials;

                if (!Credentials.TryParse(Crypto.DecryptStringAES(encodedUserPass, "authentication"), out credentials))
                {
                    return null;
                }

                return credentials;
            }
            catch
            {
                return null;
            }
        }
        private AuthenticationHeaderValue(AuthenticationHeaderValue source)
        {
            Contract.Requires(source != null);

            _scheme = source._scheme;
            _parameter = source._parameter;
        }
        private string ExtractCredential(AuthenticationHeaderValue authorizationHeaderValue)
        {
            if (authorizationHeaderValue.IsNull())
                return string.Empty;

            return authorizationHeaderValue.GetBearerToken();
        }
        public static AuthenticationHeaderValue Get( String collectionIdentifier )
        {
            // Create authentication headers dictionary if not present
            if ( authenticationHeaders == null )
            {
                authenticationHeaders = new Dictionary<String, AuthenticationHeaderValue>();
            }

            // Try to get authentication header from dictionary
            if ( authenticationHeaders.ContainsKey( collectionIdentifier ) )
            {
                return authenticationHeaders[collectionIdentifier];
            }

            // Try to get authentication header from app storage
            String scheme = StorageUtils.GetValue<String>( collectionIdentifier + "_scheme" );
            String parameter = StorageUtils.GetValue<String>( collectionIdentifier + "_parameter" );

            if ( scheme == null || parameter == null )
            {
                return null;
            }

            AuthenticationHeaderValue authenticationHeader = new AuthenticationHeaderValue( scheme, parameter );

            // Add authentication header to dictionary
            authenticationHeaders[collectionIdentifier] = authenticationHeader;

            return authenticationHeader;
        }
        public void TrottlingAuthenticate()
        {
            Database.SetInitializer(new ManahostManagerInitializer());
            using (ManahostManagerDAL prectx = new ManahostManagerDAL())
            {
                prectx.Database.Delete();
            }
            using (var server = TestServer.Create<WebApiApplicationThrottle>())
            {
                HttpResponseMessage response = null;
                response = server.CreateRequest("/token").And((x) => x.Content = new StringContent(string.Format("grant_type=password&username={0}&password={1}&client_id=UNITTEST&client_secret=BLAHBLAHCAR", ControllerUtils.username, ControllerUtils.password), Encoding.UTF8, "application/x-www-form-urlencoded")).PostAsync().Result;
                Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, "STATUS AUTHENTIFICATIOn");

                TokenAuth token = response.Content.ReadAsAsync<TokenAuth>().Result;
                AuthenticationHeaderValue headerValueAuthentication = new AuthenticationHeaderValue("Bearer", token.access_token);

                for (int i = 0; i < 4000; i++)
                {
                    response = server.CreateRequest("/api/Account").AddHeader("Authorization", headerValueAuthentication.ToString()).GetAsync().Result;
                    Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, string.Format("STATUS Account GET I : {0}", i));
                }
                response = server.CreateRequest("/api/Account").AddHeader("Authorization", headerValueAuthentication.ToString()).GetAsync().Result;
                Assert.AreEqual((int)response.StatusCode, 429, "STATUS 429");
            }
        }
        static async Task TryRequestAsync(HttpClient client, AuthenticationHeaderValue authorization)
        {
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, ServerAddress))
            {
                request.Headers.Authorization = authorization;
                using (HttpResponseMessage response = await client.SendAsync(request))
                {
                    Console.WriteLine("{0} {1}", (int)response.StatusCode, response.ReasonPhrase);

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        return;
                    }

                    Console.WriteLine();

                    HomeModel model = await response.Content.ReadAsAsync<HomeModel>();
                    Console.WriteLine("UserName: {0}", model.UserName);
                    Console.WriteLine("Claims:");

                    foreach (ClaimModel claim in model.Claims)
                    {
                        Console.WriteLine("{0} => {1}", claim.Type, claim.Value);
                    }
                }
            }
        }
 public override void OnAuthorization(HttpActionContext actionContext)
 {
     AuthenticationHeaderValue headerValue = actionContext.Request.Headers.Authorization;
     if (null != headerValue && headerValue.Scheme == "Basic")
     {
         string credential = Encoding.Default.GetString(Convert.FromBase64String(headerValue.Parameter));
         string[] split = credential.Split(':');
         if (split.Length == 2)
         {
             string userName = split[0];
             string password;
             if (userAccounters.TryGetValue(userName, out password))
             {
                 if (password == split[1])
                 {
                     GenericIdentity identity = new GenericIdentity(userName);
                     actionContext.ControllerContext.RequestContext.Principal = new GenericPrincipal(identity, new string[0]);
                     return;
                 }
             }
         }
     }
     HttpResponseMessage response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
     string parameter = string.Format("realm=\"{0}\"", actionContext.Request.RequestUri.DnsSafeHost);
     AuthenticationHeaderValue challenge = new AuthenticationHeaderValue("Basic", parameter);
     response.Headers.WwwAuthenticate.Add(challenge);
     actionContext.Response = response;
 }
Beispiel #18
0
        public static async Task<bool> SubmitComment(string issueNumber, string commentString)
        {
            // https://developer.atlassian.com/jiradev/api-reference/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-add-comment
            // https://grantadesign.atlassian.net/rest/api/latest/project/10000
            // https://grantadesign.atlassian.net/rest/api/latest/issue/MI-9111/editmeta/

            var credentials = new NetworkCredential(Constants.UserName, Constants.Password);
            var handler = new HttpClientHandler {Credentials = credentials, PreAuthenticate = true};
            using (var client = new HttpClient(handler))
            {
                var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", Constants.UserName, Constants.Password))));
                client.DefaultRequestHeaders.Authorization = authHeader;
                client.BaseAddress = new Uri("https://grantadesign.atlassian.net/rest/api/latest/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var jiraComment = new JiraComment { Body = commentString };
                var response = await client.PostAsJsonAsync("issue/" + issueNumber + "/comment", jiraComment);
                if (response.IsSuccessStatusCode)
                {
                    return true;
                }

                return false;
            }
        }
 public void Ctor_SetSchemeOnly_MatchExpectation()
 {
     // Just verify that this ctor forwards the call to the overload taking 2 parameters.
     AuthenticationHeaderValue auth = new AuthenticationHeaderValue("NTLM");
     Assert.Equal("NTLM", auth.Scheme);
     Assert.Null(auth.Parameter);
 }
 public AzureMLAuthenticatedHttpClient(IAzureMLFrequentlyBoughtTogetherConfig config)
 {
     //HACK: Should prefix key with 'AccountKey:'
     var accountKey = Encoding.ASCII.GetBytes(config.AccountKey);
     var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(accountKey));
     DefaultRequestHeaders.Authorization = header;
 }
 private GitHubSoapBrokerImpl()
 {
     _httpClient = new HttpClient();
     var bytes = Encoding.ASCII.GetBytes("spf-uc06:spf1234");
     var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
     _httpClient.DefaultRequestHeaders.Authorization = authHeader;
 }
 private static NetworkCredential ExtractCredential(AuthenticationHeaderValue authorizationHeader)
 {
     string parameter = authorizationHeader.Parameter.Trim();
     string userNameAndPassword = Encoding.ASCII.GetString(Convert.FromBase64String(parameter));
     string[] credentials = userNameAndPassword.Split(':');
     return new NetworkCredential(credentials[0], credentials[1], "DOMAIN");
 }
        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            var challenge = new AuthenticationHeaderValue("Basic");
            context.Result = new AddChallengeOnUnauthorizedResult(challenge, context.Result);

            return Task.FromResult(0);
        }
 /// <summary>
 /// <see cref="Sif.Framework.Service.Authentication.IAuthenticationService.VerifyAuthenticationHeader(System.Net.Http.Headers.AuthenticationHeaderValue, System.Boolean)">VerifyAuthenticationHeader</see>
 /// </summary>
 public override bool VerifyAuthenticationHeader(AuthenticationHeaderValue header)
 {
     string storedSessionToken = sessionService.RetrieveSessionToken(settings.ApplicationKey, settings.SolutionId, settings.UserToken, settings.UserToken);
     string sessionToken;
     bool verified = VerifyAuthenticationHeader(header, false, out sessionToken);
     return (verified && sessionToken.Equals(storedSessionToken));
 }
 /// <summary>
 /// Submits the feedback.
 /// </summary>
 /// <param name="userFeedback">The user feedback.</param>
 /// <param name="accessToken">The access token.</param>
 public async void SubmitFeedback(UserFeedback userFeedback, string accessToken)
 {
     if (userFeedback != null && !string.IsNullOrEmpty(accessToken))
     {
         var authenticationHeaderValue = new AuthenticationHeaderValue(AuthorizationScheme, accessToken);
         await Task.Run(() => this.httpClientHelper.PostResponseData<UserFeedback>(this.GetUri(SubmitFeedbackResource), userFeedback, authenticationHeaderValue));
     }
 }
 public string[] GetCredentialParts(AuthenticationHeaderValue authHeader)
 {
     var encodedCredentials = authHeader.Parameter;
     var credentialBytes = Convert.FromBase64String(encodedCredentials);
     var credentials = Encoding.ASCII.GetString(credentialBytes);
     var credentialParts = credentials.Split(AuthorizationHeaderSeparator);
     return credentialParts;
 }
Beispiel #27
0
 private HttpClient GetHttpClientWithBasicAuth()
 {
     var client = new HttpClient();
     var byteArray = Encoding.ASCII.GetBytes(credentials.BasicAuthCredentials);
     var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
     client.DefaultRequestHeaders.Authorization = header;
     return client;
 }
Beispiel #28
0
 /// <summary>
 /// sets authentication in hedear </summary>
 /// <param name="client"> HttpClient, gets authentication based on name and password</param>
 protected void setAuthentication(HttpClient client)
 {
     client.DefaultRequestHeaders.Accept.Clear();
     var byteArray = Encoding.ASCII.GetBytes(name + ":" + password);
     var header = new AuthenticationHeaderValue(
         "Basic", Convert.ToBase64String(byteArray));
     client.DefaultRequestHeaders.Authorization = header;
 }
        public void ParseAuthorizationHeader_should_return_null_if_header_credentials_format_is_invalid(string authParameter)
        {
            var auth = new AuthenticationHeaderValue("Basic", authParameter.ToBase64String());
            var context = GetAuthorizedExceptionContext(auth);
            var credentials = context.ParseAuthorizationHeader();

            Assert.Null(credentials);
        }
        public async Task <RoleAssignmentResponse> SetAssignmentAsync(string authToken, RoleAssignmentParams raParams)
        {
            //Visual Studio Enterprise
            string subscriptionId   = _config.subscriptionId;
            string roleAssignmentId = Guid.NewGuid().ToString();

            //Mary Smith
            string principalId   = raParams.PrincipalId;
            string rgName        = raParams.ResourceGroupName;
            string saName        = raParams.StorageAccountName;
            string containerName = raParams.ContainerName;

            string scope = $"subscriptions/{subscriptionId}/resourceGroups/{rgName}/providers/Microsoft.Storage/storageAccounts/{saName}/blobServices/default/containers/{containerName}";

            //Built-in-Role Storage Blob Data Reader
            //https://docs.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#storage-blob-data-reader
            string roleId           = "2a2b9908-6ea1-4ae2-8e65-a410df84e7d1";
            string roleDefinitionId = $"{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleId}";

            //PUT
            string assignmentUrl = $"https://management.azure.com/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentId}?api-version=2018-01-01-preview";

            var ra = new RoleAssigmentRequestBody()
            {
                properties = new RoleAssignmentProperty()
                {
                    roleDefinitionId = roleDefinitionId,
                    principalId      = principalId
                }
            };

            var client = new HttpClient();
            var authorizationHeader = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken);

            client.DefaultRequestHeaders.Authorization = authorizationHeader;
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string raString = JsonSerializer.Serialize <RoleAssigmentRequestBody>(ra);
            var    content  = new StringContent(raString, Encoding.UTF8, "application/json");

            var response = await client.PutAsync(assignmentUrl, content);

            var responseBody = response.Content.ReadAsStringAsync().Result;

            var raResponse = new RoleAssignmentResponse();

            raResponse.Message = "Error: See response body";

            if (response.IsSuccessStatusCode)
            {
                raResponse         = JsonSerializer.Deserialize <RoleAssignmentResponse>(responseBody);
                raResponse.Message = "Successful Role assignment!!";
            }

            raResponse.ResponseBody = responseBody;

            return(raResponse);
        }
Beispiel #31
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            System.Net.Http.Headers.AuthenticationHeaderValue authorizationHeader = actionContext.Request.Headers.Authorization;
            var      result          = HmacResult.FailedForUnknownReason;
            var      controllingData = WebApiCachingControllingData.Data();
            var      dependencyScope = actionContext.Request.GetDependencyScope();
            var      utcNow          = DateTime.UtcNow;
            Customer customer        = null;

            try
            {
                result = IsAuthenticated(actionContext, dependencyScope, controllingData, utcNow, out customer);
            }
            catch (Exception exception)
            {
                exception.Dump();
            }

            if (result == HmacResult.Success)
            {
                // Inform core about the authentication. Note, you cannot use IWorkContext.set_CurrentCustomer here.
                HttpContext.Current.User = new SmartStorePrincipal(customer, HmacAuthentication.Scheme1);

                var response = HttpContext.Current.Response;

                response.AddHeader(WebApiGlobal.Header.AppVersion, SmartStoreVersion.CurrentFullVersion);
                response.AddHeader(WebApiGlobal.Header.Version, controllingData.Version);
                response.AddHeader(WebApiGlobal.Header.MaxTop, controllingData.MaxTop.ToString());
                response.AddHeader(WebApiGlobal.Header.Date, utcNow.ToString("o"));
                response.AddHeader(WebApiGlobal.Header.CustomerId, customer.Id.ToString());

                response.Cache.SetCacheability(HttpCacheability.NoCache);
            }
            else
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);

                var headers       = actionContext.Response.Headers;
                var authorization = actionContext.Request.Headers.Authorization;

                // See RFC-2616
                var scheme = _hmac.GetWwwAuthenticateScheme(authorization != null ? authorization.Scheme : null);
                headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(scheme));

                headers.Add(WebApiGlobal.Header.AppVersion, SmartStoreVersion.CurrentFullVersion);
                headers.Add(WebApiGlobal.Header.Version, controllingData.Version);
                headers.Add(WebApiGlobal.Header.MaxTop, controllingData.MaxTop.ToString());
                headers.Add(WebApiGlobal.Header.Date, utcNow.ToString("o"));
                headers.Add(WebApiGlobal.Header.HmacResultId, ((int)result).ToString());
                headers.Add(WebApiGlobal.Header.HmacResultDescription, result.ToString());

                if (controllingData.LogUnauthorized)
                {
                    LogUnauthorized(actionContext, dependencyScope, result, customer);
                }
            }
        }
Beispiel #32
0
    static void Main(string[] args)
    {
        string urlPath           = "C:\\Users\\victo\\Desktop\\testfiles\\token2url.txt";
        string paramPath         = "C:\\Users\\victo\\Desktop\\testfiles\\token2param.txt";
        string tokenURL          = Methods.readFile(urlPath);
        string requestParameters = Methods.readFile(paramPath);

        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

        HttpContent httpContent = new StringContent(requestParameters, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");

        string message = (Methods.postRequest(client, tokenURL, httpContent)).Result;

        Token  token      = JsonSerializer.Deserialize <Token>(message);
        string jsonString = JsonSerializer.Serialize(token);

        string accessToken        = token.access_token;
        string vehiclesRequestURL = Methods.readFile("C:\\Users\\victo\\Desktop\\testfiles\\token2vehicles.txt");

        client.DefaultRequestHeaders.Accept.Clear();
        System.Net.Http.Headers.AuthenticationHeaderValue authenticationHeader = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
        client.DefaultRequestHeaders.Authorization = authenticationHeader;
        message = (Methods.getRequest(client, vehiclesRequestURL)).Result;

        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Vehicles));
        string xmldocpath = "C:\\Users\\victo\\Desktop\\testfiles\\vehiclesxml.xml";

        System.IO.File.WriteAllText(xmldocpath, message);
        System.IO.StringReader stringReader = new System.IO.StringReader(message);
        Vehicles vehicles = (Vehicles)serializer.Deserialize(stringReader);

        Methods.InsertVehiclesData(vehicles);
        Methods.readVehiclesData();
    }
 public static bool TryParse(string input, out AuthenticationHeaderValue parsedValue)
 {
 }
        internal static int GetAuthenticationLength(string?input, int startIndex, out object?parsedValue)
        {
            Debug.Assert(startIndex >= 0);

            parsedValue = null;

            if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
            {
                return(0);
            }

            // Parse the scheme string: <scheme> in '<scheme> <parameter>'
            int schemeLength = HttpRuleParser.GetTokenLength(input, startIndex);

            if (schemeLength == 0)
            {
                return(0);
            }

            string?targetScheme = null;

            switch (schemeLength)
            {
            // Avoid allocating a scheme string for the most common cases.
            case 5: targetScheme = "Basic"; break;

            case 6: targetScheme = "Digest"; break;

            case 4: targetScheme = "NTLM"; break;

            case 9: targetScheme = "Negotiate"; break;
            }

            string scheme = targetScheme != null && string.CompareOrdinal(input, startIndex, targetScheme, 0, schemeLength) == 0 ?
                            targetScheme :
                            input.Substring(startIndex, schemeLength);

            int current          = startIndex + schemeLength;
            int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);

            current = current + whitespaceLength;

            if ((current == input.Length) || (input[current] == ','))
            {
                // If we only have a scheme followed by whitespace, we're done.
                parsedValue = new AuthenticationHeaderValue(scheme);
                return(current - startIndex);
            }

            // We need at least one space between the scheme and parameters. If there is no whitespace, then we must
            // have reached the end of the string (i.e. scheme-only string).
            if (whitespaceLength == 0)
            {
                return(0);
            }

            // If we get here, we have a <scheme> followed by a whitespace. Now we expect the following:
            // '<scheme> <blob>[,<name>=<value>]*[, <otherscheme>...]*': <blob> potentially contains one
            // or more '=' characters, optionally followed by additional name/value pairs, optionally followed by
            // other schemes. <blob> may be a quoted string.
            // We look at the value after ',': if it is <token>=<value> then we have a parameter for <scheme>.
            // If we have either a <token>-only or <token><whitespace><blob> then we have another scheme.
            int parameterStartIndex = current;
            int parameterEndIndex   = current;

            if (!TrySkipFirstBlob(input, ref current, ref parameterEndIndex))
            {
                return(0);
            }

            if (current < input.Length)
            {
                if (!TryGetParametersEndIndex(input, ref current, ref parameterEndIndex))
                {
                    return(0);
                }
            }

            string parameter = input.Substring(parameterStartIndex, parameterEndIndex - parameterStartIndex + 1);

            parsedValue = new AuthenticationHeaderValue(scheme, parameter);
            return(current - startIndex);
        }
        internal static int GetAuthenticationLength(string input, int startIndex, out object parsedValue)
        {
            Contract.Requires(startIndex >= 0);

            parsedValue = null;

            if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
            {
                return(0);
            }

            // Parse the scheme string: <scheme> in '<scheme> <parameter>'
            int schemeLength = HttpRuleParser.GetTokenLength(input, startIndex);

            if (schemeLength == 0)
            {
                return(0);
            }

            AuthenticationHeaderValue result = new AuthenticationHeaderValue();

            result._scheme = input.Substring(startIndex, schemeLength);

            int current          = startIndex + schemeLength;
            int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);

            current = current + whitespaceLength;

            if ((current == input.Length) || (input[current] == ','))
            {
                // If we only have a scheme followed by whitespaces, we're done.
                parsedValue = result;
                return(current - startIndex);
            }

            // We need at least one space between the scheme and parameters. If there are no whitespaces, then we must
            // have reached the end of the string (i.e. scheme-only string).
            if (whitespaceLength == 0)
            {
                return(0);
            }

            // If we get here, we have a <scheme> followed by a whitespace. Now we expect the following:
            // '<scheme> <blob>[,<name>=<value>]*[, <otherscheme>...]*': <blob> potentially contains one
            // or more '=' characters, optionally followed by additional name/value pairs, optionally followed by
            // other schemes. <blob> may be a quoted string.
            // We look at the value after ',': if it is <token>=<value> then we have a parameter for <scheme>.
            // If we have either a <token>-only or <token><whitespace><blob> then we have another scheme.
            int parameterStartIndex = current;
            int parameterEndIndex   = current;

            if (!TrySkipFirstBlob(input, ref current, ref parameterEndIndex))
            {
                return(0);
            }

            if (current < input.Length)
            {
                if (!TryGetParametersEndIndex(input, ref current, ref parameterEndIndex))
                {
                    return(0);
                }
            }

            result._parameter = input.Substring(parameterStartIndex, parameterEndIndex - parameterStartIndex + 1);
            parsedValue       = result;
            return(current - startIndex);
        }
Beispiel #36
0
        /// <summary>
        /// Mobile Box New
        /// </summary>
        /// <param name="savedInstanceState"></param>
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.activity_auth);

            btn_register = FindViewById <Button>(Resource.Id.btn_register);
            btn_auth     = FindViewById <Button>(Resource.Id.btn_auth);
            btn_back_a   = FindViewById <ImageButton>(Resource.Id.btn_back_a);

            s_login     = FindViewById <EditText>(Resource.Id.s_login);
            s_pass      = FindViewById <EditText>(Resource.Id.s_pass);
            is_remember = FindViewById <CheckBox>(Resource.Id.is_remember);
            preloader   = FindViewById <ProgressBar>(Resource.Id.loader);


            btn_back_a.Click += (s, e) =>
            {
                Finish();
            };



            string dir_path           = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string file_data_remember = "";
            // Проверяю запомнил ли пользователя.
            string check = CrossSettings.Current.GetValueOrDefault("check", "");

            if (check == "1")
            {
                s_login.Text = CrossSettings.Current.GetValueOrDefault("login", "");
                s_pass.Text  = CrossSettings.Current.GetValueOrDefault("password", "");
            }

            is_remember.Checked = true;



            //        if (file_data_remember.Substring(0, 1) == "1")
            //        {
            //preloader.Visibility = Android.Views.ViewStates.Visible;
            //file_data_remember = file_data_remember.Remove(0, 1);
            //            AuthResponseData o_data = JsonConvert.DeserializeObject<AuthResponseData>(file_data_remember);

            //            StaticUser.AddInfoAuth(o_data);

            //preloader.Visibility = Android.Views.ViewStates.Gone;

            //// Переход на главную страницу.
            //Intent homeActivity = new Intent(this, typeof(Home.HomeActivity));
            //            StartActivity(homeActivity);
            //            //this.Finish();
            //        }
            //        else
            //        {
            // Переход к форме регистрации.
            btn_register.Click += (s, e) =>
            {
                Intent registerActivity = new Intent(this, typeof(Auth.RegisterActivity));
                StartActivity(registerActivity);
            };

            btn_auth.Click += async delegate
            {
                try
                {
                    preloader.Visibility = Android.Views.ViewStates.Visible;
                    // Авторизируюсь клиентом.

                    AuthModel auth = new AuthModel
                    {
                        Email    = s_login.Text,
                        Password = s_pass.Text,
                    };



                    var myHttpClient = new HttpClient();
                    var _authHeader  = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", auth.Email, auth.Password))));

                    myHttpClient.DefaultRequestHeaders.Authorization = _authHeader;

                    var uri = new Uri("http://iot.tmc-centert.ru/api/auth/login?email=" + auth.Email + "&password="******"Email", auth.Email },
                     *  { "Password", auth.Password }
                     * });
                     */
                    // Поучаю ответ об авторизации [успех или нет]
                    HttpResponseMessage response = await myHttpClient.PostAsync(uri.ToString(), new StringContent(JsonConvert.SerializeObject(auth), Encoding.UTF8, "application/json"));

                    string s_result;
                    using (HttpContent responseContent = response.Content)
                    {
                        s_result = await responseContent.ReadAsStringAsync();
                    }

                    AuthApiData <AuthResponseData> o_data = JsonConvert.DeserializeObject <AuthApiData <AuthResponseData> >(s_result);


                    //ClearField();
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        if (o_data.Status == "0")
                        {
                            Toast.MakeText(this, o_data.Message, ToastLength.Long).Show();

                            AuthResponseData o_user_data = new AuthResponseData();
                            o_user_data = o_data.ResponseData;

                            if (is_remember.Checked == true)
                            {
                                CrossSettings.Current.AddOrUpdateValue("check", "1");
                                CrossSettings.Current.AddOrUpdateValue("login", s_login.Text);
                                CrossSettings.Current.AddOrUpdateValue("password", s_pass.Text);
                            }
                            else
                            {
                                CrossSettings.Current.AddOrUpdateValue("check", "0");
                            }

                            StaticUser.Email = s_login.Text;
                            StaticUser.AddInfoAuth(o_user_data);

                            //пример ContainerSelection

                            //using (FileStream fs = new FileStream(dir_path + "user_data.txt", FileMode.OpenOrCreate))
                            //{
                            //    await System.Text.Json.JsonSerializer.SerializeAsync<AuthResponseData>(fs, o_user_data);
                            //}

                            using (FileStream file = new FileStream(dir_path + "user_data.txt", FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                // преобразуем строку в байты
                                byte[] array = Encoding.Default.GetBytes(JsonConvert.SerializeObject(o_user_data));    // 0 связан с запоминанием
                                // запись массива байтов в файл
                                file.Write(array, 0, array.Length);
                            }

                            //var role = o_data.ResponseData.Role;
                            //Начинаю собирать информацию о клиенте
                            preloader.Visibility = Android.Views.ViewStates.Invisible;
                            // Переход на страницу водителя.
                            if (o_data.ResponseData.Role == "driver")
                            {
                                Intent Driver = new Intent(this, typeof(Auth.DriverActivity));
                                StartActivity(Driver);
                                this.Finish();
                            }
                            else if (o_data.ResponseData.Role == "user")
                            {
                                Intent UserActivity = new Intent(this, typeof(Auth.ActivityUserBox));
                                StartActivity(UserActivity);
                                this.Finish();
                            }
                        }
                        else
                        {
                            Toast.MakeText(this, o_data.Message, ToastLength.Long).Show();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Toast.MakeText(this, "" + ex.Message, ToastLength.Long).Show();
                }
            };
        }
Beispiel #37
-11
        public static async Task<string> Call(string url, string user,string password, string parameters="")
        {
            string returnValue = "";

            try
            {
                using (var client = new HttpClient())
                {
                    //generate url

                    client.BaseAddress = new Uri(url);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    //[email protected]:WSTest
                    var byteArray = Encoding.ASCII.GetBytes(user+":"+password);

                    // "basic "+ Convert.ToBase64String(byteArray)
                    AuthenticationHeaderValue ahv = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                    client.DefaultRequestHeaders.Authorization = ahv;

                    string requesturl = url + parameters;
                    HttpResponseMessage response = await client.GetAsync(requesturl);
                    response.EnsureSuccessStatusCode();
                    returnValue = ((HttpResponseMessage)response).Content.ReadAsStringAsync().Result;
                }
                return returnValue;
            }
            catch (Exception e)
            {
                throw (e);
            }
        }