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

  • Question

  • User2054207217 posted

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

    Tuesday, May 15, 2018 1:18 AM

All replies

  • User475983607 posted

    You need to contact the REST service owner as ask for help using their service.  Basic authentication is an HTTP spec and generally configured for the entire site.  Every request requires the basic auth header not just one URL.

    Anyway, there's not much we can do here on the forum without the operation docs from the service.  

    Tuesday, May 15, 2018 10:39 AM
  • User1168443798 posted

    Hi progdever,

    I found you posted a same thread below:

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

    Did the suggestion from progdever resolve the “Forbidden error”?

    If not, could you share us how you implement Rest API with basic authentication?

    Will the Rest api validate the token from “Authorization” with “Basic”?

    For appending the token, it depends on how the server side validates the token.

    Best Regards,

    Edward

    Wednesday, May 16, 2018 2:22 AM