示例#1
0
        static void Main(string[] args)
        {
            var localClient = new HttpClient();
            localClient.BaseAddress = new Uri("https://windows8vm/ngmd/api/");
            localClient.SetBasicAuthentication("cw", "cw");

            var cloudClient = new HttpClient();
            cloudClient.BaseAddress = new Uri("https://demo.christianweyer.net/api/");
            cloudClient.SetBasicAuthentication("cw", "cw");

            while (true)
            {
                Console.WriteLine("Calling 'personalization'");
                localClient.GetAsync("personalization");
                cloudClient.GetAsync("personalization");
                Console.WriteLine("Calling 'articles'");
                localClient.GetAsync("articles");
                cloudClient.GetAsync("articles");
                Console.WriteLine("Calling 'images'");
                localClient.GetAsync("images");
                cloudClient.GetAsync("images");
                Console.WriteLine("Calling 'statistics'");
                localClient.GetAsync("statistics");
                cloudClient.GetAsync("statistics");

                Thread.Sleep(10000);
            }
        }
示例#2
0
        public void Http_Post_Order()
        {
            var uri = "http://localhost/NortwindApi/";
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.SetBasicAuthentication("*****@*****.**", "Wayne!");

                var model = new OrderModel()
                {
                    CustomerID = "VINET",
                    ShipCity = "Boston",
                    IsShipped = true
                };

                HttpResponseMessage response = client.PostAsJsonAsync("api/orders", model).Result;

                Assert.IsTrue(response.IsSuccessStatusCode);

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

                Assert.IsTrue(!String.IsNullOrEmpty(content));

                var order = JsonConvert.DeserializeObject<Order>(content);

                Assert.IsNotNull(order);
            }
        }
        private static string RequestSessionToken()
        {
            "Requesting session token\n".ConsoleYellow();

            var client = new HttpClient { BaseAddress = _baseAddress };
            client.SetBasicAuthentication("bob", "bob");

            var response = client.GetAsync("token").Result;
            response.EnsureSuccessStatusCode();

            var tokenResponse = response.Content.ReadAsStringAsync().Result;
            var json = JObject.Parse(tokenResponse);
            var token = json["access_token"].ToString();
            var expiresIn = int.Parse(json["expires_in"].ToString());
            var expiration = DateTime.UtcNow.AddSeconds(expiresIn);

            "\nSession Token:".ConsoleRed();
            Console.WriteLine(json.ToString());

            "\nExpiration:".ConsoleRed();
            Console.WriteLine(expiration.ToLongDateString() + " " + expiration.ToLongTimeString());

            //DecodeSessionToken(token);
            return token;
        }
        //static Uri _baseAddress = new Uri(Constants.SelfHostBaseAddress);

        static void Main(string[] args)
        {
            var handler = new WebRequestHandler();
            handler.ClientCertificates.Add(
                X509.CurrentUser.My.SubjectDistinguishedName.Find("CN=Client").First());

            var client = new HttpClient(handler) {
                BaseAddress = _baseAddress
            };

            client.SetBasicAuthentication("bob", "bob");

            while (true)
            {
                Helper.Timer(() =>
                {
                    "Calling service.".ConsoleYellow();

                    var response = client.GetAsync("identity").Result;
                    response.EnsureSuccessStatusCode();

                    var claims = response.Content.ReadAsAsync<ViewClaims>().Result;
                    Helper.ShowConsole(claims);
                });

                Console.ReadLine();
            }
        }
示例#5
0
        public async Task<ActionResult> LogIn(UsersLogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(Constants.ApiBaseUri);
                httpClient.SetBasicAuthentication(model.Username, model.Password);

                var response = await httpClient.GetAsync("token");

                if (response.IsSuccessStatusCode)
                {
                    var tokenResponse = await response.Content.ReadAsStringAsync();
                    var json = JObject.Parse(tokenResponse);
                    var token = json["access_token"].ToString();

                    Session[Constants.SessionTokenKey] = token;
                    
                    FormsAuthentication.SetAuthCookie(model.Username, createPersistentCookie: true);
                    return Redirect("~/");
                }
                else // could check specific error code here
                {
                    ModelState.AddModelError("", "The username and password provided do not match any accounts on record.");
                    return View();
                }
            }
        }
        public async Task<ActionResult> RevokeRefreshToken()
        {
            var refreshToken = (User as ClaimsPrincipal).FindFirst("refresh_token").Value;
            var client = new HttpClient();
            client.SetBasicAuthentication("codeclient", "secret");

            var postBody = new Dictionary<string, string>
            {
                { "token", refreshToken },
                { "token_type_hint", "refresh_token" }
            };

            var result = await client.PostAsync(Constants.TokenRevocationEndpoint, new FormUrlEncodedContent(postBody));

            return RedirectToAction("Index");
        }
        private static string RequestSessionToken()
        {
            "Requesting session token\n".ConsoleYellow();

            var client = new HttpClient { BaseAddress = _baseAddress };
            client.SetBasicAuthentication("bob", "bob");

            var response = client.GetAsync("token").Result;
            response.EnsureSuccessStatusCode();

            var tokenResponse = response.Content.ReadAsStringAsync().Result;
            var json = JObject.Parse(tokenResponse);
            var token = json["access_token"].ToString();
            
            "\nSession Token:".ConsoleRed();
            Console.WriteLine(json.ToString());

            return token;
        }
        public IntrospectionClient(string endpoint, string clientId = "", string clientSecret = "", HttpMessageHandler innerHttpMessageHandler = null)
        {
            if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentNullException("endpoint");
            if (innerHttpMessageHandler == null) innerHttpMessageHandler = new HttpClientHandler();

            _client = new HttpClient(innerHttpMessageHandler)
            {
                BaseAddress = new Uri(endpoint)
            };

            _client.DefaultRequestHeaders.Accept.Clear();
            _client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            if (!string.IsNullOrWhiteSpace(clientId))
            {
                _client.SetBasicAuthentication(clientId, clientSecret);
            }
        }
示例#9
0
        static void Main()
        {
            var address = "http://localhost:925/";

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();
                var response = client.GetAsync(address + "test").Result;
                Console.WriteLine(response.StatusCode);

                Console.WriteLine();
                Console.WriteLine("Next request sets basic authentication password");

                client.SetBasicAuthentication("filip", "abc");
                var response2 = client.GetAsync(address + "test").Result;
                Console.WriteLine(response2.StatusCode);

                Console.ReadLine();
            }
        }
        public async static Task<OidcTokenResponse> CallTokenEndpointAsync(Uri tokenEndpoint, Uri redirectUri, string code, string clientId, string clientSecret)
        {
            var client = new HttpClient
            {
                BaseAddress = tokenEndpoint
            };

            client.SetBasicAuthentication(clientId, clientSecret);

            var parameter = new Dictionary<string, string>
                {
                    { OAuth2Constants.GrantType, OAuth2Constants.GrantTypes.AuthorizationCode },
                    { OAuth2Constants.Code, code },
                    { OAuth2Constants.RedirectUri, redirectUri.AbsoluteUri }
                };

            var response = await client.PostAsync("", new FormUrlEncodedContent(parameter));
            response.EnsureSuccessStatusCode();

            var json = JObject.Parse(await response.Content.ReadAsStringAsync());
            return json.ToObject<OidcTokenResponse>();
        }
        public static OidcTokenResponse CallTokenEndpoint(Uri tokenEndpoint, Uri redirectUri, string code, string clientId, string clientSecret)
        {
            var client = new HttpClient
            {
                BaseAddress = tokenEndpoint
            };

            client.SetBasicAuthentication(clientId, clientSecret);

            var parameter = new Dictionary<string, string>
                {
                    { "grant_type", "authorization_code" },
                    { "code", code },
                    { "redirect_uri", redirectUri.AbsoluteUri }
                };

            var response = client.PostAsync("", new FormUrlEncodedContent(parameter)).Result;
            response.EnsureSuccessStatusCode();

            var json = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            return json.ToObject<OidcTokenResponse>();
        }
示例#12
0
        public void Http_Get_Orders()
        {
            var uri = "http://localhost/NortwindApi/";
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.SetBasicAuthentication("*****@*****.**", "Wayne!");

                HttpResponseMessage response = client.GetAsync("api/orders").Result;

                Assert.IsTrue(response.IsSuccessStatusCode);

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

                Assert.IsTrue(!String.IsNullOrEmpty(content));

                var orders = JsonConvert.DeserializeObject<IEnumerable<Order>>(content);

                Assert.IsTrue(orders.Any());
            }
        }
        //static Uri _baseAddress = new Uri(Constants.SelfHostBaseAddress);

        static void Main(string[] args)
        {
            var client = new HttpClient {
                BaseAddress = _baseAddress
            };

            client.SetBasicAuthentication("bob", "bob");

            while (true)
            {
                Helper.Timer(() =>
                {
                    "Calling service.".ConsoleYellow();

                    var response = client.GetAsync("identity").Result;
                    response.EnsureSuccessStatusCode();

                    var claims = response.Content.ReadAsAsync<ViewClaims>().Result;
                    Helper.ShowConsole(claims);
                });

                Console.ReadLine();
            }            
        }
        public HttpResponseMessage Logout([FromBody] LogoutViewModel input)
        {
            ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

            var Name = ClaimsPrincipal.Current.Identity.Name;
            var Name1 = User.Identity.Name;

            var userName = principal.Claims.Where(c => c.Type == "sub").Single().Value;
            var a = HttpContext.Current.GetOwinContext();
            var b = a.Authentication;

            var client = new HttpClient();
            client.SetBasicAuthentication("carbon", "21B5F798-BE55-42BC-8AA8-0025B903DC3B");
            var postBody = new System.Collections.Generic.Dictionary<string, string>
            {
            { "token", input.Access_Token },
            //{ "token_type_hint", "refresh_token" }
            { "token_type_hint", "access_token" }
            };

            if (!string.IsNullOrEmpty(input.Access_Token))
            {
                var result = client.PostAsync("https://HFL0100:44333/connect/revocation", new FormUrlEncodedContent(postBody)).Result;
            }

            postBody = new System.Collections.Generic.Dictionary<string, string>
            {
            { "token", input.Refresh_Token },
            { "token_type_hint", "refresh_token" }
            //{ "token_type_hint", "access_token" }
            };

            if (!string.IsNullOrEmpty(input.Refresh_Token))
            {
                var result2 = client.PostAsync("https://HFL0100:44333/connect/revocation", new FormUrlEncodedContent(postBody)).Result;
            }
            var response2 = new HttpResponseMessage(HttpStatusCode.OK);
            var test = Request.Headers.GetCookies("Halo-Secure").SingleOrDefault();
            if (test != null)
            {
                test.Expires = DateTimeOffset.Now.AddDays(-1);
                response2.Headers.AddCookies(new CookieHeaderValue[] { test });
            }
            return response2;
        }