Twitter API返回401

时间:2013-08-14 20:35:48

标签: .net vb.net twitter twitter-oauth

这是对将使用twitter API阻止某些用户的应用程序的测试。在提交以下HTTP POST时,它始终返回401 Unauthorized。请注意,键(“###”)已被删除,但可以在应用程序的Twitter开发人员工具中找到它们。

似乎应该很容易获得,所以我希望我们可以为社区提供简单的解决方案。如果你帮我解决这个问题,我会重构一个更好的代码库并让它适用于所有人。

仅供参考 - 我在https://dev.twitter.com/docs/auth/creating-signature#note-lexigraphically

按照Twitter上的说明进行操作
Protected Sub btnBlock_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBlock.Click
    Try
        Dim oauth_signature_method = "HMAC-SHA1" 'goes in header
        Dim oauth_consumer_key As String = "###" 'goes in header
        Dim oauth_token As String = "###" 'goes in header
        Dim oauth_version As String = "1.0" 'goes in header
        Dim oauth_timestamp As String = GenerateTimeStamp() 'goes in header 
        Dim oRandom As New Random()
        Dim oauth_nonce As String = GenerateNonce(oRandom) 'goes in header
        Dim screen_name As String = txtUserName.Text.Trim
        Dim sURL As String = "https://api.twitter.com/1.1/blocks/create.json"
        Dim sHTTPMethod As String = "POST"

        Dim dSignatureParameters As New SortedDictionary(Of String, String)
        dSignatureParameters.Add("oauth_signature_method", oauth_signature_method)
        dSignatureParameters.Add("oauth_consumer_key", oauth_consumer_key)
        dSignatureParameters.Add("oauth_token", oauth_token)
        dSignatureParameters.Add("oauth_version", oauth_version)
        dSignatureParameters.Add("oauth_timestamp", oauth_timestamp)
        dSignatureParameters.Add("oauth_nonce", oauth_nonce)
        dSignatureParameters.Add("screen_name", screen_name)

        'https://dev.twitter.com/docs/auth/creating-signature#note-lexigraphically
        Dim sParameterString As String = GenerateSignature(dSignatureParameters)

        Dim sSignatureBaseString = sHTTPMethod.ToUpper & "&" & HttpUtility.UrlEncode(sURL) & "&" & HttpUtility.UrlEncode(sParameterString)
        Dim oauth_consumer_secret As String = "###"
        Dim oauth_token_secret As String = "###"
        Dim sSigningKey As String = HttpUtility.UrlEncode(oauth_consumer_secret) & "&" & HttpUtility.UrlEncode(oauth_token_secret)
        Dim oauth_signature As String = ""
        Using oHasher As HMACSHA1 = New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(sSigningKey)) 
            'goes in header
            oauth_signature = Convert.ToBase64String(oHasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(sSignatureBaseString)))
        End Using
        Dim dHeaderParameters As New SortedDictionary(Of String, String)
        dHeaderParameters.Add("oauth_signature_method", oauth_signature_method)
        dHeaderParameters.Add("oauth_consumer_key", oauth_consumer_key)
        dHeaderParameters.Add("oauth_token", oauth_token)
        dHeaderParameters.Add("oauth_version", oauth_version)
        dHeaderParameters.Add("oauth_timestamp", oauth_timestamp)
        dHeaderParameters.Add("oauth_nonce", oauth_nonce)
        dHeaderParameters.Add("oauth_signature", oauth_signature)
        Dim sAuthHeader As String = GenerateHeader(dHeaderParameters)

        Dim oRequest As HttpWebRequest = (HttpWebRequest).Create(sURL)
        oRequest.Method = sHTTPMethod
        oRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8" 'or 16?
        Dim oProxy As New WebProxy("proxy.wellsfargo.com", 8080)
        oProxy.Credentials = CredentialCache.DefaultCredentials
        oRequest.Proxy = oProxy

        oRequest.Headers.Add("Authorization", sAuthHeader)

        Dim sRequestBody As String = "screen_name=" & screen_name
        Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(sRequestBody)
        oRequest.ContentLength = bytes.Length
        Dim oRS As System.IO.Stream = oRequest.GetRequestStream()
        oRS.Write(bytes, 0, bytes.Length)
        oRS.Close()

        Dim oResponse As WebResponse = oRequest.GetResponse()
        Dim oStream As Stream = oResponse.GetResponseStream()
        Dim oReadStream As New StreamReader(oStream, True)
        litResponse.Text = oReadStream.ReadToEnd()
        oResponse.Close()
        oReadStream.Close()
    Catch ex As Exception
        litError.Text = ex.Message
    End Try

End Sub

Private Function GenerateHeader(ByVal dParameters As SortedDictionary(Of String, String)) As String
    Dim sHeader As String = "OAuth "
    For Each sKey As String In dParameters.Keys
        sHeader &= HttpUtility.UrlEncode(sKey) & "=""" & HttpUtility.UrlEncode(dParameters(sKey)) & """"
        If sKey <> dParameters.Keys.Last Then
            sHeader &= ", "
        End If
    Next
    Return sHeader
End Function

Private Function GenerateSignature(ByVal dParameters As SortedDictionary(Of String, String)) As String
    Dim sSignature As String = ""
    For Each sKey As String In dParameters.Keys
        sSignature &= HttpUtility.UrlEncode(sKey) & "=" & HttpUtility.UrlEncode(dParameters(sKey))
        If sKey <> dParameters.Keys.Last Then
            sSignature &= "&"
        End If
    Next
    Return sSignature
End Function

Private Function GenerateTimeStamp() As String
    Dim ts As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0)
    Return Convert.ToInt64(ts.TotalSeconds).ToString()
End Function

Private Function GenerateNonce(ByVal oRandom As Random) As String
    Dim sb As New StringBuilder
    For i As Integer = 0 To 31
        Dim g As Integer = oRandom.[Next](3)
        Select Case g
            Case 0
                ' lowercase alpha
                sb.Append(ChrW(oRandom.[Next](26) + 97), 1)
                Exit Select
            Case Else
                ' numeric digits
                sb.Append(ChrW(oRandom.[Next](10) + 48), 1)
                Exit Select
        End Select
    Next
    Dim sRandom As String = sb.ToString()
    Dim bytes() As Byte = Text.Encoding.ASCII.GetBytes(sRandom)
    Dim sResult As String = Convert.ToBase64String(bytes)
    Dim sPattern As String = "[^A-Za-z0-9]"
    sResult = Regex.Replace(sResult, sPattern, "")
    Return sResult
End Function

0 个答案:

没有答案