1

How can I request a token by exchanging basic credentials (client id and secret) (OAuth authentication) in VB.NET?

I tried the code below without any success. I get the error saying:

The underlying connection was closed: An unexpected error occurred on a send.

Code

Function test()
    Try
        Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create("https://www.ia.provider.com/access_token"), HttpWebRequest)
        myHttpWebRequest.Method = "POST"
        myHttpWebRequest.ContentType = "application/json"
        myHttpWebRequest.Headers.Add("Authorization", "Basic " & System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("545874a9f5134ed0b54545:333650277fa4d50934c65AAb46Ad123")))

        Dim myHttpWebResponse As HttpWebResponse CType(myHttpWebRequest.GetResponse(), HttpWebResponse)

        Dim myreader As New System.IO.StreamReader(myHttpWebResponse.GetResponseStream)
        Dim myText As String
        myText = myreader.ReadToEnd
        Console.WriteLine(myText)

    Catch e As ArgumentException

        Console.WriteLine(e.Message)
        MsgBox((vbLf & "WebException is thrown. " & vbLf & "Message is:" & e.Message))

    Catch e As WebException
        Console.WriteLine(vbLf & "WebException is thrown. " & vbLf & "Message is :" & e.Message)
        If e.Status = WebExceptionStatus.ProtocolError Then
            Console.WriteLine("Status Code: {0}", CType(e.Response, HttpWebResponse).StatusCode)
            Console.WriteLine("Status Description: {0}", CType(e.Response, HttpWebResponse).StatusDescription)
            Console.WriteLine("Server : {0}", CType(e.Response, HttpWebResponse).Server)
        End If

    Catch e As Exception
        Console.WriteLine("Exception is thrown. Message is:" & e.Message)

    End Try
End Function
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Ismail
  • 700
  • 4
  • 9
  • 22
  • It would help a lot if you could be significantly more specific and precise about what goes wrong when you run the code – ADyson Apr 20 '19 at 22:47
  • I get the error saying: The underlying connection was closed: An unexpected error occurred on a send. – Mark Ismail Apr 20 '19 at 22:50
  • Using WebRequest, an Https connection you need to set the TLS1.2 protocol explicitly. Add `ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12`. The handshake might also require a `ServicePointManager.ServerCertificateValidationCallback`. Add one that just returns `True` (unless you actually want/need to validate the Server certificate). – Jimi Apr 20 '19 at 22:55
  • Please add the full error message and stack trace to your question, thanks – ADyson Apr 20 '19 at 22:57
  • Now it saying : The remote server returned an error: (500) – Mark Ismail Apr 20 '19 at 23:09
  • Btw, you're configuring an "application/json" post, but you're not sending a JSON. You'll probably receive a JSON as the server response. You ContentType should be `myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"`. There are different ways to send UrlEncoded POST data. See here: [How do I get an OAuth 2.0 authentication token](https://stackoverflow.com/q/38494279/7444103) if you find something that matches what the server is expecting (there's usually a *manual* that explains what's required). Error `500` means your request doesn't comply and generates an internal error. – Jimi Apr 21 '19 at 00:44
  • Thanks @Jimi, I appreciate your help. – Mark Ismail Apr 21 '19 at 02:40

1 Answers1

1

The best way is to use RestClient. You can add it to your project from the NuGet package manager.

Here is how to request a token:

 Function request_token()

    ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    Dim client = New RestClient("https://www.ia.provider.com/access_token")


    Dim request = New RestRequest(Method.POST)
    request.Parameters.Clear()
    request.AddParameter("Authorization", "Basic " & System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("545874a9f5134ed0b54545:333650277fa4d50934c65AAb46Ad123")))
    request.AddParameter("Accept", "application/json")
    request.AddParameter("Content-Type", "application/x-www-form-urlencoded")
    request.AddParameter("Content-Length", "29")
    request.AddParameter("grant_type", "client_credentials")

    Return response.Content.ToString
End Function
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Ismail
  • 700
  • 4
  • 9
  • 22
  • `ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications`... you are aware that you are effectively disabling SSL protection from man-in-the-middle attacks by doing that? – Heinzi Oct 16 '21 at 14:14