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

  • Question

  • 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();


    Monday, May 14, 2018 7:51 PM

All replies

  • your issues can be better discussed at the below forum.

    https://forums.asp.net/28.aspx/1?WCF+ASMX+and+other+Web+Services

    Monday, May 14, 2018 9:38 PM
  • Hi Pauldever,

    Thank you for posting here.

    According to your question, what is your project?

    If your question is more related to ASP.NET, you could post a new thread in ASP.NET forum for suitable support.

    https://forums.asp.net/

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, May 15, 2018 7:40 AM
  • Ok I will try in that forum. Thanks Wendy.
    Tuesday, May 15, 2018 8:43 PM