Google API Token Endpoint Returns Bad Request 400

I am trying to exchange a Google Plus one-time authorization code for an access token. But I keep getting 400 Bad Request. I am using VB.NET. Here is the code:

'We should now have a "good" one-time authorization code stored in "code" Using Client As New WebClient() 'Dim Client As New WebClient() Dim values As New NameValueCollection() Dim Resp Dim responseString As String values("code") = Request.QueryString("code") values("client_id") = ConfigurationManager.AppSettings("google.clientid") values("client_secret") = ConfigurationManager.AppSettings("google.clientsecret") values("grant_type") = "authorization_code" values("redirect_uri") = "http://localhost:3333/MyVacations/default.aspx" Resp = Client.UploadValues("https://www.googleapis.com/oauth2/v3/token", values) responseString = Encoding.Default.GetString(Resp) End Using 

I'm sure this is the endpoint that I should use https://www.googleapis.com/oauth2/v3/token , but who knows? The Google Discovery document just bothers me with this.

Also, please forgive my naivety, but will someone explain how the POST code used by Google as an example relates to the web request in my code above? I think I understand how values ​​are converted, but 3 header lines in POST (below) ... how is this defined in VB code? I am missing something that should be really obvious to others, so if you know, please tell me.

 POST /oauth2/v3/token HTTP/1.1 Host: www.googleapis.com Content-Type: application/x-www-form-urlencoded code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7& client_id=8819981768.apps.googleusercontent.com& client_secret={client_secret}& redirect_uri=https://oauth2-login-demo.appspot.com/code& grant_type=authorization_code 

Another Post overflow Post says something about sending data as request parameters (using "&", I think) instead of sending data as request headers, so is there something wrong with sending by NameValueCollection?

+6
source share
1 answer

So here is the answer: API requires 2 calls. The first call returns a one-time authorization code. The first call must indicate a redirect URI.

The second call sends one time code to the API for the authorization token. This POST also requires URI redirection.

The redirect URI on the first call must be the same as the redirect URI on the second call !!!

I could not find this in the documentation. Remember that this URI must also match one of the URIs in the list in the developer console, as described in the documentation.

+4
source

Source: https://habr.com/ru/post/983192/


All Articles