コード例 #1
0
        public async Task <DavItem> Upload(Uri url, StorageFile file)
        {
            if (!url.IsAbsoluteUri)
            {
                url = new Uri(_serverUrl, url);
            }

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.CostPolicy = ExecutionContext.Instance.IsBackgroundTask
                ? BackgroundTransferCostPolicy.UnrestrictedOnly
                : BackgroundTransferCostPolicy.Always;
            uploader.Method = "PUT";
            var buffer = CryptographicBuffer.ConvertStringToBinary(_credential.UserName + ":" + _credential.Password, BinaryStringEncoding.Utf8);
            var token  = CryptographicBuffer.EncodeToBase64String(buffer);
            var value  = new HttpCredentialsHeaderValue("Basic", token);

            uploader.SetRequestHeader("Authorization", value.ToString());

            var upload = uploader.CreateUpload(url, file);
            Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(async operation => await OnUploadProgressChanged(operation));
            var task  = upload.StartAsync().AsTask(progressCallback);
            var task2 = await task.ContinueWith(OnUploadCompleted);

            return(await task2);
        }
コード例 #2
0
        /// <summary>
        /// HTTP Get request for stream service.
        /// </summary>
        /// <param name="requestUri">Uri to make OAuth request.</param>
        /// <param name="tokens">Tokens to pass in request.</param>
        /// <param name="callback">Function invoked when stream available.</param>
        /// <returns>awaitable task</returns>
        public async Task ExecuteGetStreamAsync(Uri requestUri, TwitterOAuthTokens tokens, TwitterStreamCallbacks.RawJsonCallback callback)
        {
            using (var request = new HttpHelperRequest(requestUri, HttpMethod.Get))
            {
                var requestBuilder = new TwitterOAuthRequestBuilder(requestUri, tokens);

                request.Headers.Authorization = HttpCredentialsHeaderValue.Parse(requestBuilder.AuthorizationHeader);

                using (var response = await HttpHelper.Instance.GetInputStreamAsync(request).ConfigureAwait(false))
                {
                    var responseStream = await response.GetStreamResultAsync().ConfigureAwait(false);

                    using (var reader = new StreamReader(responseStream.AsStreamForRead()))
                    {
                        while (!_abort && !reader.EndOfStream)
                        {
                            var result = reader.ReadLine();

                            if (!string.IsNullOrEmpty(result))
                            {
                                callback?.Invoke(result);
                            }
                        }
                    }
                }
            }
        }
コード例 #3
0
ファイル: MainPage.xaml.cs プロジェクト: bk147/ZWaveTests
        public MainPage()
        {
            this.InitializeComponent();

            filter = new HttpBaseProtocolFilter();
            filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
            httpClient = new HttpClient(filter);

            string username = "******";
            string password = "******";
            var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(username + ":" + password, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
            string base64token = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(buffer);
            HttpCredentialsHeaderValue authHeader = new HttpCredentialsHeaderValue("Basic", base64token);

//            var ah = new HttpCredentialsHeaderValue("Authentication", "Basic YWRtaW46YWRtaW4=")
            httpClient.DefaultRequestHeaders.Authorization = authHeader;

// Took some time to figure out a "bug"? when using "deflate" which is default...
            //            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "deflate");   //Problem here...
            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
//            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "");

                // We're not using this at the moment...
            cts = new CancellationTokenSource();
        }
コード例 #4
0
        private HttpCredentialsHeaderValue GetAuthorizationHeader(DigestAuthParameters authParameters)
        {
            string nonceCounterString = string.Format("{0:x08}", authParameters.NonceCounter++);

            var authorizationHeader = new HttpCredentialsHeaderValue("Digest");

            authorizationHeader.Parameters.Add(new HttpNameValueHeaderValue("username", UserName));
            authorizationHeader.Parameters.Add(new HttpNameValueHeaderValue("realm", authParameters.Realm));
            authorizationHeader.Parameters.Add(new HttpNameValueHeaderValue("qop", "auth"));
            authorizationHeader.Parameters.Add(new HttpNameValueHeaderValue("uri", authParameters.Uri));
            authorizationHeader.Parameters.Add(new HttpNameValueHeaderValue("nonce", authParameters.Nonce));
            authorizationHeader.Parameters.Add(new HttpNameValueHeaderValue("nc", nonceCounterString));
            authorizationHeader.Parameters.Add(new HttpNameValueHeaderValue("cnonce", authParameters.Cnonce));
            authorizationHeader.Parameters.Add(new HttpNameValueHeaderValue("algorithm", authParameters.Algorithm));
            if (!String.IsNullOrEmpty(authParameters.Opaque))
            {
                authorizationHeader.Parameters.Add(new HttpNameValueHeaderValue("opaque", authParameters.Opaque));
            }

            var    a1 = string.Format("{0}:{1}:{2}", UserName, authParameters.Realm, Password);
            string a2 = string.Format("POST:{0}", authParameters.Uri);

            string ha1 = GetMD5HashBinHex(a1);
            string ha2 = GetMD5HashBinHex(a2);

            string a = string.Format("{0}:{1}:{4}:{2}:auth:{3}", ha1, authParameters.Nonce, authParameters.Cnonce, ha2,
                                     nonceCounterString);
            string responseVal = GetMD5HashBinHex(a);

            authorizationHeader.Parameters.Add(new HttpNameValueHeaderValue("response", responseVal));
            return(authorizationHeader);
        }
コード例 #5
0
        public override void PrepareHttpClientFilter(HttpBaseProtocolFilter httpClientFilter)
        {
            base.PrepareHttpClientFilter(httpClientFilter);

            if (User != null)
            {
                string preemptiveFlag = Session.GetValue(SessionParameter.PreemptivAuthentication) as string;
                if (preemptiveFlag != null && preemptiveFlag.ToLowerInvariant().Equals("true"))
                {
                    var userPassword = Encoding.UTF8.GetBytes(User + ":" + Password);
                    AuthenticationHeader = new HttpCredentialsHeaderValue("Basic", Convert.ToBase64String(userPassword));
                }
                else
                {
                    httpClientFilter.ServerCredential = new PasswordCredential("cmis", User, Password);
                }
            }
            else if (BearerToken != null)
            {
                AuthenticationHeader = new HttpCredentialsHeaderValue("Bearer", BearerToken);
            }

            if (ProxyUser != null)
            {
                var userPassword = Encoding.UTF8.GetBytes(ProxyUser + ":" + ProxyPassword);
                ProxyAuthenticationHeader = new HttpCredentialsHeaderValue("Basic", Convert.ToBase64String(userPassword));
            }

            if (CsrfHeader != null)
            {
                CsrfHeaderName = CsrfHeader;
            }
        }
コード例 #6
0
 public HttpCallHeaders(string authorization, Dictionary <string, string> headers)
 {
     if (!String.IsNullOrWhiteSpace(authorization))
     {
         Authorization = new HttpCredentialsHeaderValue("Bearer", authorization);
     }
     Headers = headers;
 }
コード例 #7
0
        /// <summary>
        /// HTTP Get request to specified Uri.
        /// </summary>
        /// <param name="requestUri">Uri to make OAuth request.</param>
        /// <param name="tokens">Tokens to pass in request.</param>
        /// <returns>String result.</returns>
        public async Task <string> ExecuteGetAsync(Uri requestUri, TwitterOAuthTokens tokens)
        {
            using (var request = new HttpHelperRequest(requestUri, HttpMethod.Get))
            {
                var requestBuilder = new TwitterOAuthRequestBuilder(requestUri, tokens, "GET");

                request.Headers.Authorization = HttpCredentialsHeaderValue.Parse(requestBuilder.AuthorizationHeader);

                using (var response = await HttpHelper.Instance.SendRequestAsync(request).ConfigureAwait(false))
                {
                    return(ProcessErrors(await response.GetTextResultAsync().ConfigureAwait(false)));
                }
            }
        }
コード例 #8
0
        // Generate an authorization header.
        public HttpCredentialsHeaderValue AuthorizationHeader(
            string method,
            DateTime now,
            HttpRequestMessage request,
            long contentLength,
            string ifMatch = "",
            string md5     = "")
        {
            string MessageSignature;

            if (this.IsTableStorage)
            {
                MessageSignature = string.Format(
                    "{0}\n\n{1}\n{2}\n{3}",
                    method,
                    "application/atom+xml",
                    now.ToString("R", CultureInfo.InvariantCulture),
                    this.GetCanonicalizedResource(request.RequestUri, this.StorageAccount));
            }
            else
            {
                MessageSignature = string.Format(
                    "{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}",
                    method,
                    (method == "GET" || method == "HEAD") ? string.Empty : contentLength.ToString(),
                    ifMatch,
                    this.GetCanonicalizedHeaders(request),
                    this.GetCanonicalizedResource(request.RequestUri, this.StorageAccount),
                    md5);
            }

            // Debug.WriteLine(MessageSignature);
            var key = CryptographicBuffer.DecodeFromBase64String(this.StorageKey);
            var msg = CryptographicBuffer.ConvertStringToBinary(MessageSignature, BinaryStringEncoding.Utf8);

            var objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);

            // CryptographicKey cryptKey = objMacProv.CreateKey(key);
            // var buff = CryptographicEngine.Sign(cryptKey, msg);
            var hash = objMacProv.CreateHash(key);

            hash.Append(msg);

            var authorizationHeader = new HttpCredentialsHeaderValue(
                "SharedKey",
                this.StorageAccount + ":" + CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset()));

            // Debug.WriteLine(authorizationHeader.ToString());
            return(authorizationHeader);
        }
コード例 #9
0
        /// <summary>
        /// HTTP Post request to specified Uri.
        /// </summary>
        /// <param name="requestUri">Uri to make OAuth request.</param>
        /// <param name="tokens">Tokens to pass in request.</param>
        /// <param name="boundary">Boundary used to separate data.</param>
        /// <param name="content">Data to post to server.</param>
        /// <returns>String result.</returns>
        public async Task <string> ExecutePostMultipartAsync(Uri requestUri, TwitterOAuthTokens tokens, string boundary, byte[] content)
        {
            JToken mediaId = null;

            try
            {
                using (var multipartFormDataContent = new HttpMultipartFormDataContent(boundary))
                {
                    using (var byteContent = new HttpBufferContent(content.AsBuffer()))
                    {
                        multipartFormDataContent.Add(byteContent, "media");

                        using (var request = new HttpHelperRequest(requestUri, HttpMethod.Post))
                        {
                            var requestBuilder = new TwitterOAuthRequestBuilder(requestUri, tokens, "POST");

                            request.Headers.Authorization = HttpCredentialsHeaderValue.Parse(requestBuilder.AuthorizationHeader);

                            request.Content = multipartFormDataContent;

                            using (var response = await HttpHelper.Instance.SendRequestAsync(request).ConfigureAwait(false))
                            {
                                string jsonResult = await response.GetTextResultAsync().ConfigureAwait(false);

                                JObject jObj = JObject.Parse(jsonResult);
                                mediaId = jObj["media_id_string"];
                            }
                        }
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                // known issue
                // http://stackoverflow.com/questions/39109060/httpmultipartformdatacontent-dispose-throws-objectdisposedexception
            }

            return(mediaId.ToString());
        }
コード例 #10
0
        public List <UploadOperation> CreateUpload(DavItem item, List <StorageFile> files)
        {
            List <UploadOperation> result   = new List <UploadOperation>();
            BackgroundUploader     uploader = new BackgroundUploader();

            uploader.Method = "PUT";
            var buffer = CryptographicBuffer.ConvertStringToBinary(Configuration.UserName + ":" + Configuration.Password, BinaryStringEncoding.Utf8);
            var token  = CryptographicBuffer.EncodeToBase64String(buffer);
            var value  = new HttpCredentialsHeaderValue("Basic", token);

            uploader.SetRequestHeader("Authorization", value.ToString());
            foreach (var storageFile in files)
            {
                var uri = new Uri(item.EntityId.TrimEnd('/'), UriKind.RelativeOrAbsolute);
                uri = new Uri(uri + "/" + storageFile.Name, UriKind.RelativeOrAbsolute);
                if (!uri.IsAbsoluteUri)
                {
                    uri = CreateItemUri(uri);
                }
                UploadOperation upload = uploader.CreateUpload(uri, storageFile);
                result.Add(upload);
            }
            return(result);
        }
コード例 #11
0
        // Generate an authorization header.
        public HttpCredentialsHeaderValue AuthorizationHeader(
            string method, 
            DateTime now, 
            HttpRequestMessage request, 
            long contentLength, 
            string ifMatch = "", 
            string md5 = "")
        {
            string MessageSignature;

            if (this.IsTableStorage)
            {
                MessageSignature = string.Format(
                    "{0}\n\n{1}\n{2}\n{3}",
                    method,
                    "application/atom+xml",
                    now.ToString("R", CultureInfo.InvariantCulture),
                    this.GetCanonicalizedResource(request.RequestUri, this.StorageAccount));
            }
            else
            {
                MessageSignature = string.Format(
                    "{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}",
                    method,
                    (method == "GET" || method == "HEAD") ? string.Empty : contentLength.ToString(),
                    ifMatch,
                    this.GetCanonicalizedHeaders(request),
                    this.GetCanonicalizedResource(request.RequestUri, this.StorageAccount),
                    md5);
            }

            // Debug.WriteLine(MessageSignature);
            var key = CryptographicBuffer.DecodeFromBase64String(this.StorageKey);
            var msg = CryptographicBuffer.ConvertStringToBinary(MessageSignature, BinaryStringEncoding.Utf8);

            var objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);

            // CryptographicKey cryptKey = objMacProv.CreateKey(key);
            // var buff = CryptographicEngine.Sign(cryptKey, msg);
            var hash = objMacProv.CreateHash(key);
            hash.Append(msg);

            var authorizationHeader = new HttpCredentialsHeaderValue(
                "SharedKey",
                this.StorageAccount + ":" + CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset()));

            // Debug.WriteLine(authorizationHeader.ToString());
            return authorizationHeader;
        }
コード例 #12
0
 public void SetTokenAsAuthField(string token)
 {
     _client.DefaultRequestHeaders.Authorization = HttpCredentialsHeaderValue.Parse($"Bearer {token}");
 }