错误请求获取Google访问令牌

时间:2014-07-11 19:01:56

标签: .net access-token bad-request

当我使用WebClient对象(或使用.NET框架的任何标准HTTP请求方法)对此URL执行简单的Web请求时,我收到400错误请求错误。当我尝试使用CURL时,我从Web服务器获得了有效的响应。似乎Google并不喜欢Windows请求 - 有些东西会抛弃它。

它适用于https://developers.google.com/oauthplayground/,如果我只是创建一个Web表单并发帖子,它也可以工作 - 我得到一个访问令牌没问题。

但我确实需要能够以编程方式完成它。 我也尝试过WebRequest和HTTP对象,但是还没有真正的运气。

我在这里发现了大约4-5个类似的问题,其中一些有代码示例 - 我尝试了他们的代码,但没有运气。 (Code that I have tried)

函数GetAccessToken(ByVal Code As String,ByVal sScopes As String)As ActionResult     Dim sAccessURLTokenURL As String =" https://accounts.google.com/o/oauth2/token"

Dim oWebCLient As New WebClient

Dim oNameValueCollection As New NameValueCollection

Dim oResponse() As Byte

oWebCLient.Headers.Add("Content-type", "application/x-www-form-urlencoded; charset=utf-8")

oNameValueCollection.Add("client_id", "562344623411-b2mt2215qdfs34asdqwe345jmq2ec7su.apps.googleusercontent.com")
oNameValueCollection.Add("client_secret", "KjsPkBUTosdeROuVfkKBaAwm")
oNameValueCollection.Add("code", Code)
oNameValueCollection.Add("scopes", sScopes)
oNameValueCollection.Add("grant_type", "authorization_code")

oResponse = oWebCLient.UploadValues(sAccessURLTokenURL, oNameValueCollection)

End Function

我在这里做错了什么?

更新

搞定了!

将清理代码并发布一些解释

2 个答案:

答案 0 :(得分:0)

我想你应该设置方法和内容类型,因为服务器响应表明:错误的请求。所以,我想将内容类型设置为application/x-www-form-urlencoded; charset=utf-8,将方法设置为POST。要做到这一点:

oWebCLient.Headers.Add("Content-type", "application/x-www-form-urlencoded; charset=utf-8")
oWebClient.UploadValues(sAccessURLTokenURL, "POST", oNameValueCollection)

据我所知,Webclient使用GET作为默认方法,所以我认为你面临的问题是......你能试试吗?

<强>更新

还可以尝试:

oWebClient.Encoding = System.Text.Encoding.UTF8
oWebClient.Proxy = Nothign

如果您使用UploadValues,则无需设置内容类型,因为它会自动设置为application/x-www-form-urlencoded。在文档中不清楚charset是否可以通过标头设置。此外,如果Google服务器自动检测到无效参数将返回错误请求,因此您可能在参数或调用uri时出错,请问您是否可以粘贴不起作用的完整代码?也许我能够更好地帮助你。

希望它有所帮助!

答案 1 :(得分:0)

Imports System.Web
Imports System.IO
Imports System.Net

Imports System.Text

Public Class OAuth2Utilities

Protected msTokenAuthorizationURL As String = "https://accounts.google.com/o/oauth2/token"

Public Function ExchangeAuthorizationCodeForTokens(ByVal oAuth2Model As oAuth2Model) As String
    Dim oWebResponse As WebResponse
    Dim sWebResponse As String

    If Not oAuth2Model Is Nothing Then

        oWebResponse = GetWebResponse(oAuth2Model)

        If Not oWebResponse Is Nothing Then

            sWebResponse = ReadWebResponse(oWebResponse)

        End If

    End If

    Return sWebResponse
End Function

Protected Function GetWebResponse(ByVal oAuth2Model As oAuth2Model) As WebResponse
    Dim oWebResponse As WebResponse = Nothing

    Dim oWebRequest As WebRequest

    Dim sRequestParameters As String
    Dim oRequestParametersByteArray() As Byte

    Dim oUTF8Encoding As New UTF8Encoding()

    Dim oStream As Stream

    If Not oAuth2Model Is Nothing Then

        oWebRequest = WebRequest.Create(msTokenAuthorizationURL)

        oWebRequest.Method = "POST"
        oWebRequest.ContentType = "application/x-www-form-urlencoded"

        sRequestParameters = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", oAuth2Model.AuthorizationCode, oAuth2Model.ClientID, oAuth2Model.ClientSecret, oAuth2Model.RedirectURI)

        oRequestParametersByteArray = oUTF8Encoding.GetBytes(sRequestParameters)

        If oRequestParametersByteArray.Length > 0 Then

            oWebRequest.ContentLength = oRequestParametersByteArray.Length

            oStream = oWebRequest.GetRequestStream()
            oStream.Write(oRequestParametersByteArray, 0, oRequestParametersByteArray.Length)

            If Not oStream Is Nothing Then

                oWebResponse = oWebRequest.GetResponse()

            End If
        End If
    End If

    Return oWebResponse
End Function

Protected Function ReadWebResponse(ByVal oWebResponse As WebResponse) As String
    Dim sWebResponse As String = String.Empty

    Dim oStream As Stream
    Dim oStreamReader As StreamReader

    Try

        If IsNothing(oWebResponse) = False Then

            oStream = oWebResponse.GetResponseStream()

            If IsNothing(oStream) = False Then

                oStreamReader = New StreamReader(oStream)

                If Not oStreamReader Is Nothing Then

                    oStreamReader = New StreamReader(oStream)

                    If IsNothing(oStreamReader) = False Then

                        sWebResponse = oStreamReader.ReadToEnd()

                    End If

                End If

            End If

        End If

    Catch oException As Exception

    End Try

    Return sWebResponse
End Function

End Class

让它发挥作用。伙计们,他就是问题所在。我会生成授权码,并且会花几个小时试图查看我一直收到的错误请求。

事情是(特别感谢Rich Sutton's Answer here),一旦您似乎无法使用相同的访问令牌 / 刷新令牌在执行该操作的初始时间之后的授权代码。

顺便说一下,这是你的朋友 - Google OAuth 2.0 Playground

Otherwords:

  1. 您可以通过将传递ClientID,ClientSecret和Redirect URI(以及您想要传递的任何参数)的URL放在一起来生成授权码。
  2. 如果您的数据是“您将获取授权码”