Beispiel #1
0
        private static CredentialCache UriAuthenticationTypeCredentialCache()
        {
            CredentialCache cc = new CredentialCache();

            cc.Add(uriPrefix1, authenticationType1, credential1);
            cc.Add(uriPrefix1, authenticationType2, credential2);

            cc.Add(uriPrefix2, authenticationType1, credential3);
            cc.Add(uriPrefix2, authenticationType2, credential4);

            return cc;
        }
Beispiel #2
0
        private static CredentialCacheCount CreateUriCredentialCacheCount(CredentialCache cc = null, int count = 0)
        {
            cc = cc ?? new CredentialCache();

            cc.Add(uriPrefix1, authenticationType1, credential1); count++;
            cc.Add(uriPrefix1, authenticationType2, credential2); count++;

            cc.Add(uriPrefix2, authenticationType1, credential3); count++;
            cc.Add(uriPrefix2, authenticationType2, credential4); count++;

            return new CredentialCacheCount(cc, count);
        }
 private static CredentialCache GetCredential()
 {
     string url = @"http://github.com/api/v3/users";
     //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
     CredentialCache credentialCache = new CredentialCache();
     //credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["gitHubUser"], ConfigurationManager.AppSettings["gitHubUserPassword"]));
     credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential("huj", "Savit5ch"));
     return credentialCache;
 }
Beispiel #4
0
        private static CredentialCache HostPortAuthenticationTypeCredentialCache()
        {
            CredentialCache cc = new CredentialCache();

            cc.Add(host1, port1, authenticationType1, credential1);
            cc.Add(host1, port1, authenticationType2, credential2);
            cc.Add(host1, port2, authenticationType1, credential3);
            cc.Add(host1, port2, authenticationType2, credential4);

            cc.Add(host2, port1, authenticationType1, credential5);
            cc.Add(host2, port1, authenticationType2, credential6);
            cc.Add(host2, port2, authenticationType1, credential7);
            cc.Add(host2, port2, authenticationType2, credential8);

            return cc;
        }
Beispiel #5
0
        private static CredentialCacheCount CreateHostPortCredentialCacheCount(CredentialCache cc = null, int count = 0)
        {
            cc = cc ?? new CredentialCache();

            cc.Add(host1, port1, authenticationType1, credential1); count++;
            cc.Add(host1, port1, authenticationType2, credential2); count++;
            cc.Add(host1, port2, authenticationType1, credential3); count++;
            cc.Add(host1, port2, authenticationType2, credential4); count++;

            cc.Add(host2, port1, authenticationType1, credential5); count++;
            cc.Add(host2, port1, authenticationType2, credential6); count++;
            cc.Add(host2, port2, authenticationType1, credential7); count++;
            cc.Add(host2, port2, authenticationType2, credential8); count++;

            return new CredentialCacheCount(cc, count);
        }
Beispiel #6
0
    /// <summary>
    /// 发送t_news到微博
    /// </summary>
    /// <param name="source">app key</param>
    /// <param name="username">用户名</param>
    /// <param name="password">密码</param>
    /// <param name="t_news">需要发送的微博内容</param>
    /// <param name="conn">数据库连接</param>
    public static void RequestWeibo(string source, string username, string password, string t_news, MySqlConnection conn)
    {
        string data = "source=" + source + "&status=" + HttpUtility.UrlEncode(t_news);

        //准备用户验证数据
        string usernamePassword = username + ":" + password;

        //准备调用的URL及需要POST的数据
        string url = "https://api.weibo.com/2/statuses/update.json";

        //准备用于发起请求的HttpWebRequest对象
        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);

        //准备用于用户验证的凭据
        CredentialCache myCache = new CredentialCache();
        myCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
        httpRequest.Credentials = myCache;
        httpRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

        //发起POST请求
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        Encoding encoding = Encoding.ASCII;
        byte[] bytesToPost = encoding.GetBytes(data);
        httpRequest.ContentLength = bytesToPost.Length;
        Stream requestStream = httpRequest.GetRequestStream();
        requestStream.Write(bytesToPost, 0, bytesToPost.Length);
        requestStream.Close();

        //获取服务端的响应内容
        try
        {
            WebResponse wr = httpRequest.GetResponse();
            Stream receiveStream = wr.GetResponseStream();
            StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
            receiveStream.Close();
        }
        catch (Exception e)
        {
            conn.Open();
            MySqlCommand cmd2 = new MySqlCommand("insert into test(msg, date) values ('" + e.ToString() + "','" + DateTime.Now.ToString() + "')", conn);
            cmd2.ExecuteNonQuery();
            conn.Close();
        }
    }
Beispiel #7
0
        private static CredentialCache CreateCredentialCache(int uriCount, int hostPortCount)
        {
            var cc = new CredentialCache();

            for (int i = 0; i < uriCount; i++)
            {
                Uri uri = new Uri(UriPrefix + i.ToString());
                cc.Add(uri, AuthenticationType, s_credential);
            }

            for (int i = 0; i < hostPortCount; i++)
            {
                string host = HostPrefix + i.ToString();
                cc.Add(host, Port, AuthenticationType, s_credential);
            }

            return cc;
        }
Beispiel #8
0
    public static void DoCredentialTest(string url)
    {
        var credential = new NetworkCredential();
        credential.UserName = "******";
        credential.Password =  "******" ;
        var clientHandler = new HttpClientHandler();
        var cc = new CredentialCache();
        cc.Add(new Uri("http://httpbin.org"), "Basic", credential);

        clientHandler.Credentials = cc;
        clientHandler.PreAuthenticate = true;
        var httpClient = new HttpClient(clientHandler);

        httpClient.MaxResponseContentBufferSize = 256000;
        httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

        try{
        var responseTask = httpClient.GetAsync(url);
        responseTask.Wait();
            HttpResponseMessage response = responseTask.Result;
        //    response.EnsureSuccessStatusCode();

        if(response.Content != null) {
        var readTask = response.Content.ReadAsStreamAsync();
        readTask.Wait();
        Console.WriteLine(readTask.Result);
        }
        else
        {
        Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
        }

        }
        catch(Exception e)
        {
            Console.WriteLine(e);
            return ;
        }

        return;
    }
Beispiel #9
0
        private CredentialCache GetCredentials(string sAuthentication, string User, string Password, string Domain, string Url)
        {
            NetworkCredential oNetworkCredential = null;
            CredentialCache   oCredentialCache   = null;

            oCredentialCache = new CredentialCache();

            Uri oUri = new Uri(Url);



            if (sAuthentication == "Anonymous")
            {
                oCredentialCache = null;
                //oNetworkCredential = new NetworkCredential();
            }
            else
            {
                if (sAuthentication != "DefaultCredentials" && sAuthentication != "DefaultNetworkCredentials")
                {
                    if (txtDomain.Text.Trim().Length == 0)
                    {
                        oNetworkCredential = new NetworkCredential(User, Password);
                    }
                    else
                    {
                        oNetworkCredential = new NetworkCredential(User, Password, Domain);
                    }
                    oCredentialCache.Add(oUri, sAuthentication, oNetworkCredential);
                    //oCredentialCache.Add(oUri, "Basic", oNetworkCredential);
                    //oCredentialCache.Add(oUri, "NTLM", oNetworkCredential);
                    //oCredentialCache.Add(oUri, "Digest", oNetworkCredential);
                }
                else
                {
                }
            }

            return(oCredentialCache);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        /// <param name="domain">域</param>
        /// <param name="loginUrl">登录地址</param>
        /// <param name="IsLogin">不使用缓存,重新登录</param>
        public void LogLan(string userName, string passWord, string domain, string loginUrl = "", bool IsLogin = false)
        {
            if (string.IsNullOrEmpty(loginUrl))
            {
                loginUrl = LoginUrl;
            }
            else
            {
                LoginUrl = loginUrl;
            }

            HttpWebRequest  WRequest;
            HttpWebResponse WResponse;

            if (IsLogin)
            {
                myCredCache = null;
            }
            if (myCredCache == null)
            {
                myCredCache = new CredentialCache();
            }
            if (myCredCache.GetCredential(new Uri(LoginUrl), "NTLM") == null)
            {
                myCredCache.Add(new Uri(LoginUrl), "NTLM", new NetworkCredential(userName, passWord, domain));
                // Pre-authenticate the request.
                WRequest = (HttpWebRequest)HttpWebRequest.Create(LoginUrl);
                // Set the username and the password.
                WRequest.Credentials = myCredCache;
                // This property must be set to true for Kerberos authentication.

                // Keep the connection alive.

                WRequest.UserAgent = "Upload Test";
                WRequest.Method    = "HEAD";
                WRequest.Timeout   = 10000;
                WResponse          = (HttpWebResponse)WRequest.GetResponse();
                WResponse.Close();
            }
        }
Beispiel #11
0
        public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(Configuration.Http.RemoteServer remoteServer, int statusCode)
        {
            if (statusCode == 308 && (IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
            {
                // 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
                return;
            }

            Uri uri         = remoteServer.BasicAuthUriForCreds(userName: Username, password: Password);
            Uri redirectUri = remoteServer.RedirectUriForCreds(
                statusCode: statusCode,
                userName: Username,
                password: Password);

            _output.WriteLine(uri.AbsoluteUri);
            _output.WriteLine(redirectUri.AbsoluteUri);
            var credentialCache = new CredentialCache();

            credentialCache.Add(uri, "Basic", _credential);

            HttpClientHandler handler = CreateHttpClientHandler();

            if (PlatformDetection.IsUap)
            {
                // UAP does not support CredentialCache for Credentials.
                Assert.Throws <PlatformNotSupportedException>(() => handler.Credentials = credentialCache);
            }
            else
            {
                handler.Credentials = credentialCache;
                using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer, handler))
                {
                    using (HttpResponseMessage response = await client.GetAsync(redirectUri))
                    {
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        Assert.Equal(uri, response.RequestMessage.RequestUri);
                    }
                }
            }
        }
Beispiel #12
0
        // Acquire valid session_id
        public override bool getSession()
        {
            var success = false;

            if (sessionID == "")
            {
                try
                {
                    // Send dummy request to capture session cookie (if present)
                    string targetURL = "http://" + ipAddress + "/a_makeacall.htm";
                    var    request   = (HttpWebRequest)WebRequest.Create(targetURL);

                    // Since there's no ping for iOS / Mono
                    request.Timeout = 5000;
                    var cache = new CredentialCache();

                    cache.Add(new Uri(targetURL), "Digest", new NetworkCredential(username, password));
                    request.Credentials       = cache;
                    request.AllowAutoRedirect = false;

                    // Ignore obnoxious SSL failure generated by ALL Polycom devices because of self-signed certs
                    ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

                    var response = (HttpWebResponse)request.GetResponse();
                    if (response != null)
                    {
                        sessionID = response.Headers.Get("Set-cookie");
                        success   = true;
                    }
                    response.Close();
                }

                catch (Exception ex)
                {
                    throw ex;
                }
            }
            //cookieHeader = "Cookie: " + sessionID;
            return(success);
        }
Beispiel #13
0
        public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache)
        {
            int port;
            Task <LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
                out port,
                requireAuth: creds != null && creds != CredentialCache.DefaultCredentials,
                expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            const string BasicAuth = "Basic";

            if (wrapCredsInCache)
            {
                Assert.IsAssignableFrom <NetworkCredential>(creds);
                var cache = new CredentialCache();
                cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds);
                creds = cache;
            }

            using (var handler = new HttpClientHandler()
            {
                Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds)
            })
                using (var client = new HttpClient(handler))
                {
                    Task <HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer);
                    Task <string> responseStringTask        = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                    Task.WaitAll(proxyTask, responseTask, responseStringTask);

                    TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                    Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                    NetworkCredential nc           = creds?.GetCredential(proxyUrl, BasicAuth);
                    string            expectedAuth =
                        nc == null || nc == CredentialCache.DefaultCredentials ? null :
                        string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" :
                        $"{nc.Domain}\\{nc.UserName}:{nc.Password}";
                    Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
                }
        }
    public static ReturnType Delete <ReturnType>(object entityToDelete)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
            string.Format("{0}/Delete?EntityName='{1}'",
                          sUri.TrimEnd('/'),
                          typeof(ReturnType).Name)
            );
        NetworkCredential serviceCreds = new NetworkCredential(UserName, Password);
        CredentialCache   cache        = new CredentialCache();
        Uri uri = new Uri(sUri);

        cache.Add(uri, "Basic", serviceCreds);

        req.Credentials = cache;
        req.Method      = "POST";
        req.ContentType = "application/xml";
        req.Timeout     = 1000 * 60 * 15; // 15 minutes

        byte[] arr = entityToDelete.ToSerializedByteArrayUTF8();
        req.ContentLength = arr.Length;
        Stream reqStrm = req.GetRequestStream();

        reqStrm.Write(arr, 0, arr.Length);
        reqStrm.Close();

        try
        {
            HttpWebResponse resp     = (HttpWebResponse)req.GetResponse();
            var             response = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            //XDocument doc = XDocument.Load(resp.GetResponseStream());
            XDocument doc = XDocument.Parse(response);
            resp.Close();
            ReturnType oResp = doc.Root.ToString().ToBusinessEntity <ReturnType>(SourceFormatEnum.XML);
            return(oResp);
        }
        catch (WebException wex)
        {
            throw DataServiceExceptionUtil.ParseException(wex);
        }
    }
Beispiel #15
0
        static void Main(string[] args)
        {
            var userName   = Environment.GetEnvironmentVariable("Creds_UserName");
            var password   = Environment.GetEnvironmentVariable("Creds_Password");
            var reportUrl  = Environment.GetEnvironmentVariable("SSRS_Url");
            var ntlmDomain = Environment.GetEnvironmentVariable("NTLM_Domain");

            CredentialCache credentialCache = new CredentialCache();

            credentialCache.Add(
                new Uri($"https://{ntlmDomain}")
                , "NTLM"
                , new NetworkCredential(
                    userName
                    , password
                    , ntlmDomain));
            using (var httpClientHandler = new HttpClientHandler()
            {
                Credentials = credentialCache
            })
            {
                // Use ServerCertificateCustomValidationCallback with extreme caution.
                httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); };

                using (var client = new HttpClient(httpClientHandler))
                {
                    // Set up the call.
                    var requestUri = new Uri(reportUrl);
                    var payload    = "{\"DDEmail\": \"[email protected]\"}";
                    var content    = new StringContent(payload, Encoding.UTF8, "application/json");
                    // Make the call.
                    var response = client.PostAsync(requestUri, content).Result;
                    // Manipulate the results.
                    var result = response.Content.ReadAsStringAsync().Result;

                    Console.WriteLine("Server Response: " + result);
                    Console.ReadLine();
                }
            }
        }
        /// <summary>
        /// Used to modify the HTTP request based on authentication type
        /// </summary>
        /// <param name="request"></param>
        private void ModifyRequestBasedOnAuthPattern(HttpWebRequest request)
        {
            // Change the model based on used auth type
            switch (AuthType)
            {
            case AuthenticationType.DefaultCredentials:
                request.Credentials = CredentialCache.DefaultCredentials;
                break;

            case AuthenticationType.NetworkCredentials:
                NetworkCredential credential      = new NetworkCredential(User, Password, Domain);
                CredentialCache   credentialCache = new CredentialCache();
                credentialCache.Add(new Uri(TargetSiteUrl), "NTLM", credential);
                request.Credentials = credentialCache;
                break;

            case AuthenticationType.Office365:
                SharePointOnlineCredentials Credentials = new SharePointOnlineCredentials(User, this.Password);
                Uri    tenantUrlUri    = new Uri(TargetSiteUrl);
                string authCookieValue = Credentials.GetAuthenticationCookie(tenantUrlUri);
                // Create fed auth Cookie and set that to http request properly to access Office365 site
                Cookie fedAuth = new Cookie()
                {
                    Name     = "SPOIDCRL",
                    Value    = authCookieValue.TrimStart("SPOIDCRL=".ToCharArray()),
                    Path     = "/",
                    Secure   = true,
                    HttpOnly = true,
                    Domain   = new Uri(TargetSiteUrl).Host
                };
                // Hookup authentication cookie to request
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(fedAuth);
                break;

            default:

                break;
            }
        }
Beispiel #17
0
 public Auth(string rootSite,
             bool isSharepointOnline,
             string domain,
             string username,
             string password,
             string authScheme)
 {
     if (!isSharepointOnline)
     {
         NetworkCredential networkCredential;
         if (password == null && username != null)
         {
             Console.WriteLine("Please enter password for {0}", username);
             networkCredential = new NetworkCredential(username, GetPassword(), domain);
         }
         else if (username != null)
         {
             networkCredential = new NetworkCredential(username, password, domain);
         }
         else
         {
             networkCredential = CredentialCache.DefaultNetworkCredentials;
         }
         credentialsCache = new CredentialCache();
         credentialsCache.Add(new Uri(rootSite), authScheme, networkCredential);
         CredentialCache credentialCache = new CredentialCache {
             { Util.getBaseUrlHost(rootSite), Util.getBaseUrlPort(rootSite), authScheme, networkCredential }
         };
     }
     else
     {
         SecureString securePassword = new SecureString();
         foreach (char c in password)
         {
             securePassword.AppendChar(c);
         }
         sharepointOnlineCredentials = new SharePointOnlineCredentials(username, securePassword);
     }
 }
        /// <summary>
        /// Createas an http client for a robot controller or returns a cached one.
        /// The client will be logged in using default credentials.
        /// </summary>
        /// <param name="robotHostname">Hostname for robot.</param>
        /// <returns>HttpClient ready for requests to the robot.</returns>
        public static async Task <HttpClient> GetHttpClientAsync(string robotHostname)
        {
            HttpClient client;

            if (!_clients.TryGetValue(robotHostname, out client))
            {
                var credentialCache = new CredentialCache();
                credentialCache.Add(new Uri($"http://{robotHostname}/rw"), "Digest",
                                    new NetworkCredential("Default User", "robotics"));
                var httpClientHandler = new HttpClientHandler();
                client = new HttpClient(new HttpClientHandler {
                    Credentials = credentialCache
                });
                _clients.Add(robotHostname, client);

                // Log in
                var res = await client.GetAsync($"http://{robotHostname}/");

                res.EnsureSuccessStatusCode();
            }
            return(client);
        }
Beispiel #19
0
        public static Tuple <HttpWebRequest, ErrorDTO> ManageConfigurationForAPIPostCall(RequestBody Body)
        {
            HttpWebRequest request   = null;
            ErrorDTO       pageError = null;

            try
            {
                string oceaneWebApiUrl = "https://endpoint-trial.cognigy.ai/53db5906f63a38927aa4c6bed1fb763d90557198c140d86ba10e999597952d44";
                Uri    requestUri      = new Uri(oceaneWebApiUrl);
                request             = WebRequest.Create(requestUri) as HttpWebRequest;
                request.Method      = "POST";
                request.ContentType = "application/json";
                CredentialCache   myCredentials = new CredentialCache();
                NetworkCredential netCred       = new NetworkCredential();
                myCredentials.Add(requestUri, "Basic", netCred);
                request.Credentials     = myCredentials;
                request.PreAuthenticate = true;
                //handling of json body for post api call to Oceane
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    string json = JsonConvert.SerializeObject(Body);
                    streamWriter.Write(json);
                    streamWriter.Flush();
                }

                //string jsonData = string.Empty;
                //using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                //{
                //    jsonData = ApiStreamReaderForJsonBody(response.GetResponseStream());

                //}
            }
            catch (Exception exception)
            {
                var faultMessage = "some error in the code";
                pageError = SetPageError(faultMessage, "test123");
            }
            return(new Tuple <HttpWebRequest, ErrorDTO>(request, pageError));
        }
         public VebraController() {
 
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 
         NetworkCredential myCredentials = new System.Net.NetworkCredential(username,password);
         string usernamePassword = (username + password);
 
         CredentialCache cache = new CredentialCache(); 
 
         cache.Add(new Uri(url), "Basic", myCredentials); 
 
         request.Credentials = cache; 
 
         request.Headers.Add("Authorization", "Basic " + 
             Convert.ToBase64String(Encoding.ASCII.GetBytes(usernamePassword)); 
 
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         // Get the token from the response: 
         string token = response.GetResponseHeader("Token"); 
 
         response.Write(response.StatusCode); //you need to fix this
     }
        /// <summary>
        /// </summary>
        /// <param name="host"></param>
        /// <param name="oauthToken"></param>
        public void AddOAuthCredentials(Uri host, string oauthToken)
        {
            Logging.Info("Adding OAuth Credentials");
            Logging.Debug("Host: {0}", new object[] { host });

            try
            {
                var existingCredentials = CredentialCache.GetCredential(host, "Bearer");
                if (existingCredentials != null)
                {
                    CredentialCache.Remove(host, "Bearer");
                }
            }
            catch (Exception exception)
            {
                Logging.Error(exception, "Failed to add OAuth credentials");
            }
            finally
            {
                CredentialCache.Add(host, "Bearer", new OAuth2Credential(oauthToken));
            }
        }
Beispiel #22
0
        private static HttpClient GetHttpClient(Uri absoluteUri, NetworkCredential credentials)
        {
            CredentialCache credentialCache = null;
            HttpClient      httpClient      = null;

            if (credentials != null)
            {
                credentialCache = new CredentialCache();
                credentialCache.Add(absoluteUri, "Basic", credentials);
                httpClient = new HttpClient(new HttpClientHandler {
                    Credentials = credentialCache, AllowAutoRedirect = false
                });
            }
            else
            {
                httpClient = new HttpClient(new HttpClientHandler {
                    AllowAutoRedirect = false
                });
            }

            return(httpClient);
        }
Beispiel #23
0
            /// <summary>
            /// 根据用户登录信息登录并读取用户信息到DataSet
            /// 如果用户新浪通行证身份验证成功且用户已经开通微博则返回 http状态为 200;
            /// 如果是不则返回401的状态和错误信息。此方法用了判断用户身份是否合法且已经开通微博。
            /// http://open.t.sina.com.cn/wiki/index.php/Account/verify_credentials
            /// </summary>
            /// <param name="url">API URL (XML Format)http://api.t.sina.com.cn/account/verify_credentials.xml?source=AppKey
            /// </param>
            /// <returns></returns>
            internal static DataSet ReadXMLDataToDataSet(string url)
            {
                CredentialCache mycache = new CredentialCache();

                mycache.Add(new Uri(url), "Basic", new NetworkCredential(UserInfo.UserName, UserInfo.PassWord));
                WebRequest myReq = WebRequest.Create(url);

                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(UserInfo.UserNamePassWord)));
                WebResponse wr = myReq.GetResponse();
                DataSet     ds = new DataSet();

                using (Stream receiveStream = wr.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                    //string content = reader.ReadToEnd();
                    ds.ReadXml(reader);
                    reader.Close();
                }
                wr.Close();
                return(ds);
            }
 private void verifyRemoteAccess(string url, CredentialCache credentials)
 {
     try
     {
         System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
         if (credentials != null)
         {
             request.Credentials = credentials;
         }
         request.Method = "HEAD";
         System.Net.WebResponse response = request.GetResponse();
         if (response.ResponseUri.AbsoluteUri.Contains("url=")) // verify if just forwarded to a external DNS server (e.g. openDNS.com)
         {
             throw new Exception(string.Format("SCM tag {0} is not accessible", url));
         }
     }
     catch (WebException ex)
     {
         // ask for user credentials then try again
         if (ex.Response != null && (ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
         {
             LoginForm dialog = new LoginForm("Enter SCM credentials:");
             if (dialog.ShowDialog(this) == DialogResult.OK)
             {
                 CredentialCache cache = new CredentialCache();
                 cache.Add(new Uri(url), "Basic", new NetworkCredential(dialog.Username, dialog.Password));
                 verifyRemoteAccess(url, cache);
             }
             else
             {
                 throw new Exception("Sorry, but you are not authorized to access the specified URL.");
             }
         }
         else
         {
             throw new Exception("Sorry, but you have entered an invalid URL.");
         }
     }
 }
Beispiel #25
0
        public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK()
        {
            Uri uri         = HttpTestServers.BasicAuthUriForCreds(secure: false, userName: Username, password: Password);
            Uri redirectUri = HttpTestServers.RedirectUriForCreds(secure: false, userName: Username, password: Password);

            _output.WriteLine(uri.AbsoluteUri);
            _output.WriteLine(redirectUri.AbsoluteUri);
            var credentialCache = new CredentialCache();

            credentialCache.Add(uri, "Basic", _credential);

            var handler = new HttpClientHandler();

            handler.Credentials = credentialCache;
            using (var client = new HttpClient(handler))
            {
                using (HttpResponseMessage response = await client.GetAsync(redirectUri))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }
            }
        }
Beispiel #26
0
        public void Connect(string _baseAddress, string _username, string _password)
        {
            username    = _username;
            password    = _password;
            baseAddress = _baseAddress;
            baseAddress = baseAddress.Trim().TrimEnd('/');
            var credentialCache = new CredentialCache();

            credentialCache.Add(
                new Uri(baseAddress),
                "Digest",
                new NetworkCredential(username, password)
                );

            client = new HttpClient(new HttpClientHandler {
                Credentials = credentialCache, PreAuthenticate = true
            });
            client.BaseAddress = new Uri(baseAddress);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            client.DefaultRequestHeaders.ExpectContinue = false;
        }
Beispiel #27
0
        public void UsePowerBIReports()
        {
            string report = ContentManager.GetNextCatalogItem("PowerBIReport");

            var context = this.ContentManager.PortalAccessorV1.CreateContext();

            ICredentials executionCredentails = CredentialCache.DefaultNetworkCredentials;

            if (!String.IsNullOrEmpty(ReportServerInformation.DefaultInformation.ExecutionAccount))
            {
                CredentialCache myCache         = new CredentialCache();
                Uri             reportServerUri = new Uri(ReportServerInformation.DefaultInformation.ReportServerUrl);
                myCache.Add(new Uri(reportServerUri.GetLeftPart(UriPartial.Authority)), "NTLM",
                            new NetworkCredential(ReportServerInformation.DefaultInformation.ExecutionAccount,
                                                  ReportServerInformation.DefaultInformation.ExecutionAccountPwd));
                executionCredentails = myCache;
            }

            PowerBIReport pbiReport = context.CatalogItemByPath(report).GetValue() as PowerBIReport;

            PowerBIClient.SimulatePowerBIReportUsage(executionCredentails, pbiReport);
        }
Beispiel #28
0
        }// public void WriteToLogFile

        /// <summary>
        /// method to upload the contents of a file from a remote URI
        /// </summary>
        /// <param name="ftpUri"></param>
        /// <param name="user"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        public void PostFileToSite(string fileName)
        {
            try
            {
                string parsedFileName = ParseFileName(fileName);
                // contains the URI path and filename to upload to the remote server
                UriBuilder ub     = new UriBuilder(m_ServiceProviderFTPSite + "//" + parsedFileName + ".csv");
                Uri        ftpUri = ub.Uri;
                // Get the object used to communicate with the server.
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                NetworkCredential nc = new NetworkCredential(m_ServiceProviderFTPUsername, m_ServiceProviderFTPPassword);
                CredentialCache   cc = new CredentialCache();
                cc.Add(ftpUri, "Basic", nc);
                request.Credentials = cc;

                // Copy the contents of the file to the request stream.
                StreamReader sourceStream = new StreamReader(fileName);
                byte[]       fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();

                request.ContentLength = fileContents.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                WriteToLogFile("ServiceProviderCdrHandler::PostFileToSite():FilePosted:" + fileName + "-" + response.StatusDescription);

                response.Close();
            }
            catch (WebException e)
            {
                WriteToLogFile("ServiceProviderCdrHandler::PostFileToSite():ECaught:" + e.Message + "\n" + e.StackTrace);
            }
        }
Beispiel #29
0
        private void btnCopyFromDBOracleProductionWebService_Click(object sender, EventArgs e)
        {
            clearWorker();
            // first get all 'old' table names we're interested in
            Creator c = Creator.GetInstance(new DataConnectionSpec {
                ConnectionString = cboConnectionStringFrom.Text, ProviderName = getFromProviderName(), CommandTimeout = COMMAND_TIMEOUT
            });

            string fileName = txtCSVFromFile.Text;
            string toFolder = Toolkit.ResolveDirectoryPath(txtFromCsvToFolder.Text, true);

            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            backgroundWorker1.DoWork          += new DoWorkEventHandler(delegate(object sender2, DoWorkEventArgs evt) {
                _timer        = new HighPrecisionTimer("timer", true);
                c.OnProgress += new ProgressEventHandler(c_OnProgress);
                backgroundWorker1.ReportProgress(0, new ProgressEventArgs("Getting list of tables...", 0, 0));
                List <TableInfo> tables = c.LoadTableInfo(fileName, false);


                NetworkCredential cred    = new NetworkCredential("nc7bw", "sunpasswd", null);
                CredentialCache credCache = new CredentialCache();
                credCache.Add(new Uri("https://sun.ars-grin.gov:8082"), "Basic", cred);


                WebClient wc   = new WebClient();
                wc.Credentials = credCache;
                foreach (TableInfo ti in tables)
                {
                    backgroundWorker1.ReportProgress(0, new ProgressEventArgs("Downloading " + ti.TableName + "...", 0, 0));
                    try {
                        wc.DownloadFile("https://sun.ars-grin.gov:8082/npgs/dbmuqs.csvtab?in_owner=PROD&in_table=" + ti.TableName.ToUpper(), toFolder + @"\" + ti.TableName + ".txt");
                    } catch (WebException we) {
                        Debug.WriteLine(we.Message);
                    }
                }
            });
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            backgroundWorker1.RunWorkerAsync();
        }
Beispiel #30
0
        /// <summary>
        /// 重启路由
        /// </summary>
        private string reset(string url, string userName, string password, string method, string data)
        {
            CookieContainer container        = new CookieContainer();
            string          requestUriString = url;

            if (method == "GET")
            {
                requestUriString += "?" + data;
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUriString);

            request.Method = method;
            if (method == "POST")
            {
                byte[] POSTData = new UTF8Encoding().GetBytes(data);
                request.ContentLength = POSTData.Length;
                request.GetRequestStream().Write(POSTData, 0, POSTData.Length);
            }
            request.UserAgent       = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;CIBA)";
            request.CookieContainer = container;
            request.KeepAlive       = true;
            request.Accept          = "*/*";
            request.Timeout         = 3000;
            request.PreAuthenticate = true;
            CredentialCache cache = new CredentialCache();

            cache.Add(new Uri(requestUriString), "Basic", new NetworkCredential(routeInfo.UserName, routeInfo.RPassword));
            request.Credentials = cache;
            try {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Cookies = container.GetCookies(request.RequestUri);
                new StreamReader(response.GetResponseStream(), Encoding.Default).Close();
                response.Close();
                return(string.Empty);
            } catch (Exception ex) {
                return(ex.Message);
            }
        }
Beispiel #31
0
        /// <summary>Calls the ReST service using specified HTTP verb.</summary>
        /// <param name="verb">The HTTP verb.</param>
        /// <param name="url">Relative URL of the service to call.</param>
        /// <param name="accept">Enumeration of accepted media types.</param>
        /// <param name="contentType">Enumeration of possible content type media types.</param>
        /// <param name="responseType">Type of the response.</param>
        /// <param name="uriArguments">The URI template arguments.</param>
        /// <param name="bodyArguments">The body arguments.</param>
        /// <returns>Result of the call.</returns>
        protected object Call(Verb verb, string url, IEnumerable <string> accept, IEnumerable <string> contentType, Type responseType, IDictionary <string, object> uriArguments, params object[] bodyArguments)
        {
            var callUrl     = BuildUrl(url, uriArguments);
            var validAccept = (!accept.Any() ? _converterProvider.SupportedMediaTypes :
                               _converterProvider.SupportedMediaTypes.Join(accept, outer => outer, inner => inner, (outer, inner) => inner));
            var        accepted = (validAccept.Any() ? validAccept : new[] { "*/*" });
            WebRequest request  = _webRequestProvider.CreateRequest((Uri)callUrl, new Dictionary <string, string>()
            {
                { Header.Accept, String.Join(", ", accepted) }
            });

            if ((!String.IsNullOrEmpty(CredentialCache.DefaultNetworkCredentials.UserName)) && (!String.IsNullOrEmpty(CredentialCache.DefaultNetworkCredentials.Password)))
            {
                var credentials = new CredentialCache();
                credentials.Add(new Uri(callUrl.Authority), _authenticationScheme, new NetworkCredential(CredentialCache.DefaultNetworkCredentials.UserName, CredentialCache.DefaultNetworkCredentials.Password));
                request.Credentials     = credentials;
                request.PreAuthenticate = true;
            }

            request.Method = verb.ToString();
            if ((bodyArguments != null) && (bodyArguments.Length > 0))
            {
                FillRequestBody(verb, callUrl, request, contentType, accepted, bodyArguments);
            }

            var response = (HttpWebResponse)request.GetResponse();

            ParseContentRange(response, uriArguments);
            if (responseType == null)
            {
                return(null);
            }

            RequestInfo fakeRequest = new RequestInfo(verb, callUrl, response.GetResponseStream(), new BasicClaimBasedIdentity(), HeaderCollection.Parse(response.Headers.ToString()));
            var         result      = _resultBinder.BindResults(responseType, fakeRequest);

            return(result.FirstOrDefault(responseType.IsInstanceOfType));
        }
        private string GetJsonString(string tableName, string queryString, string webserviceUrl)
        {
            string webServiceUser             = "******";
            string webServicePwd              = "";
            SaveCompareServiceRequest request = new SaveCompareServiceRequest();

            request.model               = new CompareServiceModelType();
            request.model.keys          = new CompareServiceKeysType();
            request.model.instance      = new CompareServiceInstanceType();
            request.model.instance.Name = new StringType
            {
                Value = tableName
            };
            request.model.instance.QueryString = new StringType
            {
                Value = queryString
            };
            ObjectDiffDemo.CompareService.CompareService compareService = new ObjectDiffDemo.CompareService.CompareService();
            compareService.Url = webserviceUrl;
            CredentialCache   credentialCache = new CredentialCache();
            NetworkCredential credentials     = new NetworkCredential(webServiceUser, webServicePwd, "");

            credentialCache.Add(new Uri(compareService.Url), "Basic", credentials);
            compareService.Credentials = credentialCache;
            XmlSerializer ser       = new XmlSerializer(request.GetType());
            MemoryStream  memstream = new MemoryStream();

            ser.Serialize(memstream, request);
            memstream.Seek(0L, SeekOrigin.Begin);
            byte[] buffer = new byte[memstream.Length];
            memstream.Read(buffer, 0, (int)memstream.Length);
            string requestXML = Encoding.UTF8.GetString(buffer);

            memstream.Close();
            SaveCompareServiceResponse response = compareService.SaveCompareService(request);

            return(response.model.instance.Content.Value);
        }
        public async Task PreAuthenticate_FirstRequestNoHeaderAndAuthenticates_SecondRequestPreauthenticates(string credCacheScheme, string authResponse)
        {
            await LoopbackServer.CreateClientAndServerAsync(async uri =>
            {
                using (HttpClientHandler handler = CreateHttpClientHandler())
                    using (HttpClient client = CreateHttpClient(handler))
                    {
                        client.DefaultRequestHeaders.ConnectionClose = true; // for simplicity of not needing to know every handler's pooling policy
                        handler.PreAuthenticate = true;
                        switch (credCacheScheme)
                        {
                        case null:
                            handler.Credentials = s_credentials;
                            break;

                        default:
                            var cc = new CredentialCache();
                            cc.Add(uri, credCacheScheme, s_credentials);
                            handler.Credentials = cc;
                            break;
                        }

                        Assert.Equal("hello world", await client.GetStringAsync(uri));
                        Assert.Equal("hello world", await client.GetStringAsync(uri));
                    }
            },
                                                            async server =>
            {
                List <string> headers = await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.Unauthorized, authResponse);
                Assert.All(headers, header => Assert.DoesNotContain("Authorization", header));

                for (int i = 0; i < 2; i++)
                {
                    headers = await server.AcceptConnectionSendResponseAndCloseAsync(content: "hello world");
                    Assert.Contains(headers, header => header.Contains("Authorization"));
                }
            });
        }
Beispiel #34
0
        public JObject GetAccountDetailApi(string httpUrl, string mobileNumber)
        {
            JObject         accountObj            = null;
            JObject         reqObj                = new JObject();
            WebRequest      _Req                  = null;
            HttpWebResponse _Resp                 = null;
            StreamReader    SReader               = null;
            StreamWriter    SWriter               = null;
            string          HttpAPIResponseString = "";
            string          _ApiKey               = "fDZjHHybyM";
            string          _ApiSecret            = "zu5nKlRQFbPCQrihQn51";
            CredentialCache _credentialCache      = new CredentialCache();

            try
            {
                reqObj = new JObject(new JProperty("MobileNumber", mobileNumber));
                _Req   = HttpWebRequest.Create(httpUrl);
                _credentialCache.Add(new Uri(httpUrl), "Basic", new NetworkCredential(_ApiKey, _ApiSecret));
                _Req.Credentials = _credentialCache;
                _Req.Method      = "POST";
                _Req.ContentType = "application/json";
                SWriter          = new StreamWriter(_Req.GetRequestStream());
                SWriter.Write(reqObj.ToString());
                SWriter.Flush();
                SWriter.Close();
                SReader = new StreamReader(_Req.GetResponse().GetResponseStream());
                HttpAPIResponseString = SReader.ReadToEnd();
                SReader.Close();
                accountObj = JObject.Parse(HttpAPIResponseString);
            }
            catch (Exception ex)
            {
                //Logger.ExceptionLog(ex.StackTrace);
                accountObj = new JObject(new JProperty("Success", false),
                                         new JProperty("Message", "Something Went Wrong"));
            }
            return(accountObj);
        }
        public async Task PreAuthenticate_NoPreviousAuthenticatedRequests_NoCredentialsSent(string credCacheScheme)
        {
            const int NumRequests = 3;
            await LoopbackServer.CreateClientAndServerAsync(async uri =>
            {
                using (HttpClientHandler handler = CreateHttpClientHandler())
                    using (HttpClient client = CreateHttpClient(handler))
                    {
                        client.DefaultRequestHeaders.ConnectionClose = true; // for simplicity of not needing to know every handler's pooling policy
                        handler.PreAuthenticate = true;
                        switch (credCacheScheme)
                        {
                        case null:
                            handler.Credentials = s_credentials;
                            break;

                        default:
                            var cc = new CredentialCache();
                            cc.Add(uri, credCacheScheme, s_credentials);
                            handler.Credentials = cc;
                            break;
                        }

                        for (int i = 0; i < NumRequests; i++)
                        {
                            Assert.Equal("hello world", await client.GetStringAsync(uri));
                        }
                    }
            },
                                                            async server =>
            {
                for (int i = 0; i < NumRequests; i++)
                {
                    List <string> headers = await server.AcceptConnectionSendResponseAndCloseAsync(content: "hello world");
                    Assert.All(headers, header => Assert.DoesNotContain("Authorization", header));
                }
            });
        }
Beispiel #36
0
        public virtual HttpWebRequest CreateWebRequest(string uri, NameValueCollection collHeader, string RequestMethod,
                                                       bool NwCred)
        {
            var webrequest = (HttpWebRequest)WebRequest.Create(uri);

            webrequest.KeepAlive = false;
            webrequest.Method    = RequestMethod;

            int    iCount = collHeader.Count;
            string key;
            string keyvalue;

            for (int i = 0; i < iCount; i++)
            {
                key      = collHeader.Keys[i];
                keyvalue = collHeader[i];
                webrequest.Headers.Add(key, keyvalue);
            }

            webrequest.ContentType = "text/html";
            //"application/x-www-form-urlencoded";
            if (_proxyServer.Length > 0)
            {
                webrequest.Proxy = new WebProxy(_proxyServer, _proxyPort);
            }
            webrequest.AllowAutoRedirect = false;

            if (NwCred)
            {
                var wrCache = new CredentialCache();
                wrCache.Add(new Uri(uri), "Basic", new NetworkCredential(_userName, _userPwd));
                webrequest.Credentials = wrCache;
            }
            //Remove collection elements

            collHeader.Clear();
            return(webrequest);
        }
        private string DoFilePut(Zip zip, string target, string fileName)
        {
            var netCache = new CredentialCache();

            if (Uri.StartsWith(@"\\"))
            {
                // Todo - when dealing with UNC paths's that require auth, this doesn't work.
                // Todo - I found this solution online, but it doesn't work.  We probably don't
                // Todo - deal with this anyway since we are pushing everything to Artificatory and
                // Todo - not file shares.
                var credentials = ToNetworkCredentials();
                if (credentials != null)
                {
                    var uri = new Uri(Uri);
                    netCache.Add(new Uri("\\\\" + uri.Host), "Basic", credentials);
                }
            }

            var outputDirectory = new DirectoryInfo(Uri);

            if (!outputDirectory.Exists)
            {
                outputDirectory.Create();
            }

            var targetUri      = string.Format(Uri, target);
            var zipExeFileName = string.Format("{0}\\{1}", targetUri, fileName);

            Log.Info("Writing file to: " + zipExeFileName + ".");
            if (!zip.WriteExe(zipExeFileName))
            {
                var msg = string.Format("Unable to create self extracting zip file: {0}, cause: {1}", zipExeFileName,
                                        zip.LastErrorText);
                Log.Error(msg);
                throw new Exception(msg);
            }
            return(zipExeFileName);
        }
    private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype)
    {
        NetworkCredential cred;

        if (username.Contains(@"\"))
        {
            string domain = username.Substring(0, username.IndexOf(@"\"));
            username = username.Substring(username.IndexOf(@"\") + 1);
            cred     = new System.Net.NetworkCredential(username, password, domain);
        }
        else
        {
            cred = new System.Net.NetworkCredential(username, password);
        }
        CredentialCache cache = new CredentialCache();

        if (authtype.Contains(":"))
        {
            authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
        }
        cache.Add(new Uri(siteurl), authtype, cred);
        return(cache);
    }
        public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode)
        {
            Uri uri = Configuration.Http.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
            Uri redirectUri = Configuration.Http.RedirectUriForCreds(
                secure:false,
                statusCode:statusCode,
                userName:Username,
                password:Password);
            _output.WriteLine(uri.AbsoluteUri);
            _output.WriteLine(redirectUri.AbsoluteUri);
            var credentialCache = new CredentialCache();
            credentialCache.Add(uri, "Basic", _credential);

            var handler = new HttpClientHandler();
            handler.Credentials = credentialCache;
            using (var client = new HttpClient(handler))
            {
                using (HttpResponseMessage response = await client.GetAsync(redirectUri))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    Assert.Equal(uri, response.RequestMessage.RequestUri);
                }
            }
        }
        public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache)
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
                out port,
                requireAuth: creds != null && creds != CredentialCache.DefaultCredentials,
                expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            const string BasicAuth = "Basic";
            if (wrapCredsInCache)
            {
                Assert.IsAssignableFrom<NetworkCredential>(creds);
                var cache = new CredentialCache();
                cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds);
                creds = cache;
            }

            using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) })
            using (var client = new HttpClient(handler))
            {
                Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                Task.WaitAll(proxyTask, responseTask, responseStringTask);

                TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth);
                string expectedAuth =
                    nc == null || nc == CredentialCache.DefaultCredentials ? null :
                    string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" :
                    $"{nc.Domain}\\{nc.UserName}:{nc.Password}";
                Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
            }
        }
Beispiel #41
0
        public static void GetEnumerator_CurrentSynchronization_Invalid(CredentialCache cc, bool addUri)
        {
            //An InvalidOperationException is thrown when getting the current enumerated object
            //when a credential is added to the cache after getting the enumerator
            IEnumerator enumerator = cc.GetEnumerator();

            enumerator.MoveNext();

            if (addUri)
            {
                cc.Add(new Uri("http://whatever:80"), authenticationType1, credential1);
            }
            else
            {
                cc.Add("whatever", 80, authenticationType1, credential1);
            }

            Assert.Throws<InvalidOperationException>(() => enumerator.Current);
        }
        public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK()
        {
            Uri uri = HttpTestServers.BasicAuthUriForCreds(false, Username, Password);
            Uri redirectUri = HttpTestServers.RedirectUriForCreds(false, Username, Password);
            _output.WriteLine(uri.AbsoluteUri);
            _output.WriteLine(redirectUri.AbsoluteUri);
            var credentialCache = new CredentialCache();
            credentialCache.Add(uri, "Basic", _credential);

            var handler = new HttpClientHandler();
            handler.Credentials = credentialCache;
            using (var client = new HttpClient(handler))
            {
                using (HttpResponseMessage response = await client.GetAsync(redirectUri))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }
            }
        }
	public static void StartSession(string gameID)
	{
#if(FUSE_SESSION_IN_EDITOR && UNITY_EDITOR) || (FUSE_SESSION_IN_STANDALONE && UNITY_STANDALONE)
		gameConfig = new Dictionary<string, string>();
		string query = requestQuery + Convert.ToBase64String(
			Encoding.UTF8.GetBytes(
				//remove whitespace from json so the server doesn't blow up
				System.Text.RegularExpressions.Regex.Replace(startSessionJSON.Replace("{{game_id}}", gameID), "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1")
			));

		//SessionStart
		WebRequest request = WebRequest.Create(productionURL);
		// credentials
		var requestUri = new Uri(productionURL);
		var creds = new CredentialCache();
		var nc = new NetworkCredential("jimmyjimmyjango", "1Qdow7mFZMh7");
		creds.Add(requestUri, "Basic", nc);
		request.Credentials = creds;
		request.Method = "POST";
		request.ContentType = "application/x-www-form-urlencoded";
		request.ContentLength = query.Length;

		//request
		try
		{
			request.Timeout = 1000;
			Stream dataStream = request.GetRequestStream();
			byte[] data = Encoding.UTF8.GetBytes(query);
			dataStream.Write(data, 0, data.Length);
			dataStream.Close();
		}
		catch(WebException)
		{
			Debug.LogError("FuseSDK:.NET SDK: Session Login Error (Request Failed)");
			SessionLoginError(FuseError.REQUEST_FAILED);
			return;
		}

		//response
		WebResponse response;
		try
		{
			response = request.GetResponse();
		}
		catch(WebException e)
		{
			HttpWebResponse errorResponse = e.Response as HttpWebResponse;
			Debug.LogError("FuseSDK:.NET SDK: Session Login Error " + (errorResponse == null ? "(Response Error)" : ("(" + (int)errorResponse.StatusCode + ") " + errorResponse.StatusDescription)));
			SessionLoginError(FuseError.NOT_CONNECTED);
			return;
		}


		string xml;
		using(var reader = new StreamReader(response.GetResponseStream()))
		{
			string output = reader.ReadToEnd();
			try
			{
				byte[] responseData = Convert.FromBase64String(output);
				xml = Encoding.UTF8.GetString(responseData);
			}
			catch(FormatException)
			{
				Debug.LogError("FuseSDK:.NET SDK: Session Login Error (Response Parse Error)");
				SessionLoginError(FuseError.SERVER_ERROR);
				return;
			}
		}

		ParseXML(xml);
#endif
	}
	public HttpWebResponse Submit (Uri uri, FSpot.ProgressItem progress_item) 
	{
		this.Progress = progress_item;
		Request = (HttpWebRequest) WebRequest.Create (uri);
		CookieCollection cookie_collection = Cookies.GetCookies (uri);

		if (uri.UserInfo != null && uri.UserInfo != String.Empty) {
			NetworkCredential cred = new NetworkCredential ();
			cred.GetCredential (uri, "basic");
			CredentialCache credcache = new CredentialCache();
			credcache.Add(uri, "basic", cred);
			
			Request.PreAuthenticate = true;
			Request.Credentials = credcache;	
		}

		Request.ServicePoint.Expect100Continue = expect_continue;

		Request.CookieContainer = new CookieContainer ();
		foreach (Cookie c in cookie_collection) {
			if (SuppressCookiePath) 
				Request.CookieContainer.Add (new Cookie (c.Name, c.Value));
			else
				Request.CookieContainer.Add (c);
		}

		Request.Method = "POST";
		Request.Headers["Accept-Charset"] = "utf-8;";
		
		//Request.UserAgent = "F-Spot Gallery Remote Client";
		Request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7) Gecko/20040626 Firefox/0.9.1";

		Request.Proxy = WebProxy.GetDefaultProxy ();

		if (multipart) {
			GenerateBoundary ();
			Request.ContentType = "multipart/form-data; boundary=" + boundary;
			Request.Timeout = Request.Timeout * 3;

			long length = 0;
			for (int i = 0; i < Items.Count; i++) {
				FormItem item = (FormItem)Items[i];
				
				length += MultipartLength (item);
			}
			length += end_boundary.Length + 2;
			
			//Request.Headers["My-Content-Length"] = length.ToString ();
			if (Buffer == false) {
				Request.ContentLength = length;	
				Request.AllowWriteStreamBuffering = false;
			}
		} else {
			Request.ContentType = "application/x-www-form-urlencoded";
		}
		
		stream_writer = new StreamWriter (Request.GetRequestStream ());
		
		first_item = true;
		for (int i = 0; i < Items.Count; i++) {
			FormItem item = (FormItem)Items[i];
			
			Write (item);
		}
		
		if (multipart)
			stream_writer.Write (end_boundary + "\r\n");
		
		stream_writer.Flush ();
		stream_writer.Close ();

		HttpWebResponse response; 

		try {
			response = (HttpWebResponse) Request.GetResponse ();
			
			//Console.WriteLine ("found {0} cookies", response.Cookies.Count);
			
			foreach (Cookie c in response.Cookies) {
				Cookies.Add (c);
			}
		} catch (WebException e) {
			if (e.Status == WebExceptionStatus.ProtocolError 
			    && ((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.ExpectationFailed && expect_continue) {
				e.Response.Close ();
				expect_continue = false;
				return Submit (uri, progress_item);
			}
			
			throw new WebException (Mono.Unix.Catalog.GetString ("Unhandled exception"), e);
		}

		return response;
	}
Beispiel #45
0
        public static void GetCredential_SimilarUriAuthenticationType_GetLongestUriPrefix()
        {
            CredentialCache cc = new CredentialCache();
            cc.Add(new Uri("http://microsoft:80/greaterpath"), authenticationType1, credential2);
            cc.Add(new Uri("http://microsoft:80/"), authenticationType1, credential1);

            NetworkCredential nc = cc.GetCredential(new Uri("http://microsoft:80"), authenticationType1);
            Assert.Equal(nc, credential2);
        }
Beispiel #46
0
	public static string GetWebPage (string url) 
	{
		ServicePointManager.CertificatePolicy = new TestCertificatePolicy ();
		ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType) (int) protocol;

		Uri uri = new Uri (url);
		HttpWebRequest req = (HttpWebRequest) WebRequest.Create (uri);

		if ((digestCred != null) || (basicCred != null)) {
			CredentialCache cache = new CredentialCache ();
			if (digestCred != null)
				cache.Add (uri, "Digest", digestCred);
			if (basicCred != null)
				cache.Add (uri, "Basic", basicCred);
			req.Credentials = cache;
		}

		if (certificates.Count > 0)
			req.ClientCertificates.AddRange (certificates);
		
		WebResponse resp = req.GetResponse ();
		Stream stream = resp.GetResponseStream ();
		StreamReader sr = new StreamReader (stream, Encoding.UTF8);
		return sr.ReadToEnd ();
	}
Beispiel #47
0
        public static void Add_UriAuthenticationTypeCredential_DuplicateItem_Throws()
        {
            CredentialCache cc = new CredentialCache();
            cc.Add(uriPrefix1, authenticationType1, credential1);

            Assert.Throws<ArgumentException>(() => cc.Add(uriPrefix1, authenticationType1, credential1));
        }
Beispiel #48
0
        public static void Add_HostPortAuthenticationTypeCredential_DuplicateItem_Throws()
        {
            CredentialCache cc = new CredentialCache();
            cc.Add(host1, port1, authenticationType1, credential1);

            Assert.Throws<ArgumentException>(() => cc.Add(host1, port1, authenticationType1, credential1));
        }
            /// <summary>
            /// This method creates secure/non secure web
            /// request based on the parameters passed.
            /// </summary>
            /// <param name="uri"></param>
            /// <param name="collHeader">This parameter of type
            ///    NameValueCollection may contain any extra header
            ///    elements to be included in this request      </param>
            /// <param name="RequestMethod">Value can POST OR GET</param>
            /// <param name="NwCred">In case of secure request this would be true</param>
            /// <returns></returns>
            public virtual HttpWebRequest CreateWebRequest(string uri,
              NameValueCollection collHeader,
              string RequestMethod, bool NwCred)
            {
                HttpWebRequest webrequest =
                 (HttpWebRequest)WebRequest.Create(uri);
                webrequest.KeepAlive = false;
                webrequest.Method = RequestMethod;

                int iCount = collHeader.Count;
                string key;
                string keyvalue;

                for (int i = 0; i < iCount; i++)
                {
                    key = collHeader.Keys[i];
                    keyvalue = collHeader[i];
                    webrequest.Headers.Add(key, keyvalue);
                }

                webrequest.ContentType = "text/html";
                //"application/x-www-form-urlencoded";

                if (ProxyServer.Length > 0)
                {
                    webrequest.Proxy = new
                     WebProxy(ProxyServer, ProxyPort);
                }
                webrequest.AllowAutoRedirect = false;

                if (NwCred)
                {
                    CredentialCache wrCache =
                            new CredentialCache();
                    wrCache.Add(new Uri(uri), "Basic",
                      new NetworkCredential(UserName, UserPwd));
                    webrequest.Credentials = wrCache;
                }
                //Remove collection elements
                collHeader.Clear();
                return webrequest;
            }//End of secure CreateWebRequest
Beispiel #50
0
        public async void TestCredentialsCopyInAsyncContext()
        {
            SmtpServer server = new SmtpServer();
            SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
            MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**", "hello", "howdydoo");

            CredentialCache cache = new CredentialCache();
            cache.Add("localhost", server.EndPoint.Port, "NTLM", CredentialCache.DefaultNetworkCredentials);

            client.Credentials = cache;

            try
            {
                Thread t = new Thread(server.Run);
                t.Start();
                await client.SendMailAsync(msg);
                t.Join();

                Assert.Equal("<*****@*****.**>", server.MailFrom);
                Assert.Equal("<*****@*****.**>", server.MailTo);
                Assert.Equal("hello", server.Subject);
                Assert.Equal("howdydoo", server.Body);
            }
            finally
            {
                server.Stop();
            }
        }
Beispiel #51
0
    public static string GetWebPage(string url)
    {
        ServicePointManager.CertificatePolicy = new TestCertificatePolicy ();
        ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType) (int) protocol;

        ServicePointManager.ClientCipherSuitesCallback += (System.Net.SecurityProtocolType p, IEnumerable<string> allCiphers) => {
            Console.WriteLine ("Protocol: {0}", p);
        //			var ciphers = allCiphers;
            var ciphers = from cipher in allCiphers where !cipher.Contains ("EXPORT") select cipher;
            // string prefix = p == System.Net.SecurityProtocolType.Tls ? "TLS_" : "SSL_";
            //			var ciphers = new List<string> { prefix + "RSA_WITH_AES_128_CBC_SHA", prefix + "RSA_WITH_AES_256_CBC_SHA" };
            foreach (var cipher in ciphers)
                Console.WriteLine ("\t{0}", cipher);
            return ciphers;
        };

        Uri uri = new Uri (url);
        HttpWebRequest req = (HttpWebRequest) WebRequest.Create (uri);

        if ((digestCred != null) || (basicCred != null)) {
            CredentialCache cache = new CredentialCache ();
            if (digestCred != null)
                cache.Add (uri, "Digest", digestCred);
            if (basicCred != null)
                cache.Add (uri, "Basic", basicCred);
            req.Credentials = cache;
        }

        if (certificates.Count > 0)
            req.ClientCertificates.AddRange (certificates);

        WebResponse resp = req.GetResponse ();
        Stream stream = resp.GetResponseStream ();
        StreamReader sr = new StreamReader (stream, Encoding.UTF8);
        return sr.ReadToEnd ();
    }
Beispiel #52
0
        public static void AddRemove_HostPortAuthenticationTypeDefaultCredentials_Success()
        {
            NetworkCredential nc = CredentialCache.DefaultNetworkCredentials as NetworkCredential;

            CredentialCache cc = new CredentialCache();
            cc.Add(host1, port1, authenticationType1, nc);

            Assert.Equal(nc, cc.GetCredential(host1, port1, authenticationType1));

            cc.Remove(host1, port1, authenticationType1);
            Assert.Null(cc.GetCredential(host1, port1, authenticationType1));
        }