Google API token endpoint POST returns Bad Request 400

非 Y 不嫁゛ 提交于 2019-12-08 19:39:32

问题


I am trying to exchange a one-time Google Plus Authorization code for an access token. But I keep on getting a 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 pretty sure this is the endpoint I'm supposed to be using https://www.googleapis.com/oauth2/v3/token but who knows? The Google Discovery Document just muddles this for me.

Also pardon my naivete but would someone explain how the POST code Google uses as an example relates to the Web Request in my code above? I think I understand how the values translate, but the 3 header lines in the POST (below) ... how does this get specified in the VB code? I'm missing something that must 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 Stack Overflow Post says something about sending the data as query parameters (using '&' I guess) instead of sending the data as request headers, so is there something wrong with sending along a NameValueCollection?


回答1:


So here's the answer: The API requires 2 calls. The first call returns a one time authorization code. The first call must specify a redirect URI.

The 2nd call sends the one time code to the API for an authorization token. This POST also requires a redirect URI.

The redirect URI in the first call must be the same as the redirect URI in the 2nd call!!!

I was unable to find this anywhere in the documentation. Remember that this URI must also match one of the URIs in the list in your developers console, which is what all the documentation says.



来源:https://stackoverflow.com/questions/28797800/google-api-token-endpoint-post-returns-bad-request-400

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!