Example #1
0
        static void Main(string[] args)
        {
            var tokenClient = new TokenClient("tokenService");
            XmlElement tokenXml = tokenClient.GetToken("urn:claimsdemo:http45mvc");
            string encodedToken = HeaderEncoding.EncodeBase64(tokenXml.OuterXml);

            string serviceEndpoint = ConfigurationManager.AppSettings["ServiceEndpoint"];

            var client = new System.Net.Http.HttpClient { BaseAddress = new Uri(serviceEndpoint) };
            //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SAML", tokenXml.OuterXml);
            client.SetToken("SAML", encodedToken);

            HttpResponseMessage response = client.GetAsync("api/DemoService/WhoAmI").Result;
            response.EnsureSuccessStatusCode();

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

            Console.WriteLine(content);

            //string whoAmIresult = channel.WhoAmI();
            //Console.WriteLine(whoAmIresult);

            //string restrictedMethodResult = channel.RestrictedMethod();
            //Console.WriteLine(restrictedMethodResult);

            Console.ReadLine();
        }
        private static void CallService(string token)
        {
            var client = new HttpClient
            {
                BaseAddress = _baseAddress
            };

            client.SetToken(Constants.IdSrv.SamlScheme, token);

            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();
            }            
        }
        private static void CallService(string token)
        {
            var client = new HttpClient { BaseAddress = _baseAddress };

            client.SetToken("Session", token);

            // some alternative header for session token 
            //client.DefaultRequestHeaders.Add("X-Session", "Session " + token);

            while (true)
            {
                "Calling service.".ConsoleYellow();

                Helper.Timer(() =>
                {
                    var response = client.GetAsync("identity").Result;
                    response.EnsureSuccessStatusCode();

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

                Console.ReadLine();
            }
        }
Example #4
0
        public static Task <HttpResponseMessage> PatchJsonAsync(this HttpClient client, string requestUri, string token, object data)
        {
            client.SetToken(token);
            var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri);

            request.Content = new StringContent(JsonConvert.SerializeObject(data, serializerSettings), Encoding.UTF8, MediaTypeNames.Application.Json);
            return(client.SendAsync(request));
        }
Example #5
0
        private void buttonCallService_Click(object sender, EventArgs e)
        {
            textBoxServiceResponse.Text = string.Empty;
            try
            {
                string output = string.Empty;
                bool includeToken = checkBoxIncludeBearerToken.Checked;
                string acceptHeader = textBoxAcceptHeader.Text;
                string accessToken = textBoxToken.Text;
                string verb = textBoxHttpVerb.Text;
                string url = string.Format("{0}?api_key={1}", textBoxServiceUrl.Text, textBoxMasheryApiKey.Text);

                using (var client = new HttpClient())
                {
                    //Add default headers for every request from this http client
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));
                    if (includeToken)
                        client.SetToken("Bearer", accessToken);

                    //Create specific request to send
                    HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(verb), url);

                    //Add specific header to this request
                    request.Headers.Add("x-cim-RequestId", Guid.NewGuid().ToString());

                    //Send request
                    HttpResponseMessage response = client.SendAsync(request).Result;
                    if(response.IsSuccessStatusCode)
                    {
                        string test = response.Content.ReadAsStringAsync().Result;
                        output = test;
                    }
                    else{
                        output = string.Format("StatusCode: {0}", response.StatusCode.ToString());
                    }
                }

                textBoxServiceResponse.Text = output;

            }
            catch(System.Exception exp)
            {
                MessageBox.Show(string.Format("{0}", exp.ToString()));
            }
        }
        private void CallServiceButton_Click(object sender, RoutedEventArgs e)
        {
            var client = new HttpClient
            {
                BaseAddress = _baseAddress
            };

            client.SetToken(Constants.ACS.Scheme, _token);

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

            var claims = response.Content.ReadAsAsync<ViewClaims>().Result;
            var sb = new StringBuilder(128);

            foreach (var claim in claims)
            {
                sb.AppendFormat(" {0}\n  {1}\n\n", claim.Type, claim.Value);
            }

            OutputTextBox.Text = sb.ToString();
        }
 /// <summary>
 /// Sets BearerToken value
 /// </summary>
 /// <param name="client">client</param>
 /// <param name="token">token</param>
 public static void SetBearerToken(this HttpClient client, string token)
 {
     client.SetToken("Bearer", token);
 }
Example #8
0
        private void buttonGetOAuthToken_Click(object sender, EventArgs e)
        {
            textBoxToken.Text = string.Empty;
            try
            {
                // Getting a Token
                string uri = textBoxTokenEndpoint.Text;
                string clientid = textBoxClientId.Text;
                string secret = textBoxSecret.Text;
                string theToken = string.Empty;
                long HowLongTillExpires = long.MinValue;

                if(radioButtonThinkTecture.Checked)
                {
                    // Using the Thinktecture.IdentityModel.Client
                    var client = new OAuth2Client(
                        new Uri(uri),
                        clientid,
                        secret);

                    // For Thinktecture the "scope" request is passed in.
                    var response = client.RequestClientCredentialsAsync("read write").Result;

                    // At this point we now have the AccessToken in the response
                    theToken = response.AccessToken;
                    HowLongTillExpires = response.ExpiresIn;
                }
                else if(radioButtonStandardHttpClient.Checked)
                {
                    // Using standard http, we can make the call with Basic Authorization header
                    // We need to encode the "scope" as formUrlEncoded body
                    // First prepare the Base64Encode string for Basic Auth
                    string data = string.Format("{0}:{1}", clientid, secret);
                    byte[] binaryData = System.Text.Encoding.UTF8.GetBytes(data);
                    string authorizationString = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);

                    using (var client = new HttpClient())
                    {
                        //Add Basic Authorization header for call to get OAuth token.
                        client.SetToken("Basic", authorizationString);

                        //Create specific request to send
                        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);

                        //Pass in oAuth "grant_type" as "client credentials" and "scope" as "read write"
                        //These must be application-form-url-encoded
                        List<KeyValuePair<string, string>> bodyContentList = new List<KeyValuePair<string, string>>();
                        bodyContentList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                        bodyContentList.Add(new KeyValuePair<string, string>("scope", "read write"));
                        request.Content = new FormUrlEncodedContent(bodyContentList);

                        //Send request
                        HttpResponseMessage response = client.SendAsync(request).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            string oAuthResponseString = response.Content.ReadAsStringAsync().Result;

                            //An example of using dynamic keyword and accessing properties ("access_token" and "expires_in") at runtime.
                            dynamic oAuthToken = JsonConvert.DeserializeObject(oAuthResponseString);
                            theToken = oAuthToken.access_token;
                            HowLongTillExpires = oAuthToken.expires_in;
                        }
                        else
                        {
                            throw new System.Exception("Unable to acquire token.");
                        }
                    }

                }
                else
                {
                    throw new Exception("Invalid Client selected");
                }

                textBoxToken.Text = theToken;
                textBoxExpiresInSeconds.Text = HowLongTillExpires.ToString();

            }
            catch(System.Exception exp)
            {
                textBoxToken.Text = string.Format("Unable to get token.{0}{1}", System.Environment.NewLine, exp.ToString());
            }
        }
 /// <summary>
 /// Sets BearerToken value
 /// </summary>
 /// <param name="client">client</param>
 /// <param name="token">token</param>
 public static void SetBearerToken(this HttpClient client, string token)
 {
     client.SetToken("Bearer", token);
     // OAuth2Client.AdvancedLogger.Log("Logging Bearer Token value:" + token);
 }
        private async void api_Click(object sender, RoutedEventArgs e)
        {
            var baseAddress = Sample.Constants.AspNetWebApiSampleApiUsingPoP;

            var signature = new RS256Signature(_provider);
            var signingHandler = new HttpSigningMessageHandler(signature);

            var client = new HttpClient(signingHandler)
            {
                BaseAddress = new Uri(baseAddress)
            };
            
            client.SetToken("PoP", _result?.AccessToken);

            var response = await client.GetAsync("identity");

            var sb = new StringBuilder(128);
            sb.AppendLine($"{(int)response.StatusCode}, {response.StatusCode}");
            var json = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
            {
                var values = JArray.Parse(json);
                foreach (JObject item in values)
                {
                    sb.AppendLine($"{item["type"].ToString()}, {item["value"].ToString()}");
                }
            }
            else
            {
                sb.AppendLine(json);
            }

            IdentityTextBox.Text = sb.ToString();
        }
Example #11
0
 public static Task <HttpResponseMessage> DeleteAsync(this HttpClient client, string requestUri, string token, string id)
 {
     client.SetToken(token);
     return(client.DeleteAsync($"{requestUri}{(requestUri.EndsWith("/", StringComparison.InvariantCultureIgnoreCase) ? "" : "/")}{id}"));
 }
Example #12
0
 public static Task <HttpResponseMessage> GetAsync(this HttpClient client, string requestUri, string token)
 {
     client.SetToken(token);
     return(client.GetAsync(requestUri));
 }
Example #13
0
 public static void SetBearerToken(this HttpClient client, string token)
 {
     client.SetToken(JwtConstants.Bearer, token);
 }