Quantcast
Channel: WCF, ASMX and other Web Services
Viewing all articles
Browse latest Browse all 555

Error making a POST request with Bearer Token to REST API using C#

$
0
0

I am able to POST to an REST API with Basic authentication and getting  successful response back, along with the Token. Now I need to pass the token to the site. I am having some difficulties as to passing the Bearer Token. I get a Forbidden error. Can some please give some thoughts where am I missing something?

Thanks.

 String username = "username";
        String password = "pwd";
        string URL = "url/login";
        string URL2 = "url/sessions"
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = 0;

        request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password)));
        using (var response = request.GetResponse())

        using (var reader = new StreamReader(response.GetResponseStream()))
        {

            string result = reader.ReadToEnd();
            txtResponse.Text = Convert.ToString(result);
        }

      using (var reader = new StreamReader(response.GetResponseStream()))
        {

            string result = reader.ReadToEnd();
            txtResponse.Text = Convert.ToString(result);
            JObject joResponse = JObject.Parse(result);
           apitoken = (string)joResponse["token"];

         }
//I get the correct token from above, but I get Forbidden error
        WebRequest request1 = HttpWebRequest.Create(URL2);
        request1.Headers.Add("Authorization", "Bearer " + apitoken);
        request1.Method = "POST";
        request1.ContentType = "application/json";
        var resp = request1.GetResponse();


Viewing all articles
Browse latest Browse all 555

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>