Home > Net >  Getting an OAuth2 authentication token in VB.net
Getting an OAuth2 authentication token in VB.net

Time:09-23

I'm trying to get an OAuth token using a ClientID and SecretID.

My code so far:

    Dim clientId As String = "8cd6b80dd822961f362"
    Dim clientSecret As String = "5afbd4bb280f29cba5ec1f362"
    Dim credentials = String.Format("{0}:{1}", clientId, clientSecret)
    Dim headerValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials))

    Dim content = New FormUrlEncodedContent(New Dictionary(Of String, String) From {
                                            {"client_id", clientId},
                                            {"client_secret", clientSecret},
                                            {"response_type", "code"},
                                            {"redirect_uri", "https://somesite.com/"},
                                            {"grant_type", "authorization_code"}})
    Dim requestMessage = New HttpRequestMessage(HttpMethod.Post, "https://api.site.com/oauth2/authorize")
    requestMessage.Headers.Authorization = New AuthenticationHeaderValue("Basic", headerValue)
    requestMessage.Content = content

    Dim client As HttpClient = New HttpClient()
    Dim task = client.SendAsync(requestMessage)
    Dim response = task.Result
    response.EnsureSuccessStatusCode()
    Dim responseBody As String = response.Content.ReadAsStringAsync().Result
    MsgBox(responseBody)

The above code returns the HTML for the redirect_uri site and not a token.

What am I missing or doing wrong?

Using Postman and the credentials provided I managed to get the token.

CodePudding user response:

By default HttpClient is using AllowAutoRedirect = true. The documentation says:

The Authorization header is cleared on auto-redirects and the handler automatically tries to re-authenticate to the redirected location. No other headers are cleared. In practice, this means that an application can't put custom authentication information into the Authorization header if it is possible to encounter redirection.

So depending on the setup of the server you might have to create a CookieContainer and do the redirecting on your own.

CodePudding user response:

The second step of a code flow uses the token endpoint, not the authorize endpoint. Your payload looks correct though. Try posting it to this endpoint:

https://api.site.com/oauth2/token
  • Related