#vb.net #twitter #authorize
#vb.net #Twitter #авторизовать
Вопрос:
Я перепробовал много способов авторизации моего vb.net проект в моем аккаунте в твиттере, но я не смог этого сделать. Моя последняя попытка;
Imports System.Net
Imports System.Text
Imports System.Security.Cryptography
Imports System.IO
Public Class authRequest
Private oauth_consumer_key As String
Private consumer_secret As String
Private oauth_token As String
Private oauth_token_secret As String
Private oauth_timestamp As String 'The number of seconds since the Unix epoch at the point the request is generated
Private oauth_nonce As String 'An hash identifing the request
'We are going to invoke the search API
Private requestUrl As String = "https://api.twitter.com/oauth/authorize"
Private requestMethod As String = "GET"
Private oauth_version As String = "1.0"
Private oauth_signature_method As String = "HMAC-SHA1"
Public Sub New(ByVal oauth_consumer_key_in As String, ByVal consumer_secret_in As String, ByVal oauth_token_in As String, ByVal oauth_token_secret_in As String)
oauth_consumer_key = oauth_consumer_key_in
consumer_secret = consumer_secret_in
oauth_token = oauth_token_in
oauth_token_secret = oauth_token_secret_in
End Sub
Private Function setNounce() As String
Return Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
End Function
Private Function setTimeStamp() As String
Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Return Convert.ToInt64(timeSpan.TotalSeconds).ToString()
End Function
Private Function percEncode(ByVal StringToEncode As String) As String
Dim utf8Encoding As New System.Text.UTF8Encoding(True)
Dim encodedString() As Byte
encodedString = utf8Encoding.GetBytes(StringToEncode)
StringToEncode = utf8Encoding.GetString(encodedString)
Return System.Uri.EscapeDataString(StringToEncode)
End Function
Public Function getSignature(ByVal consumer_key_in As String, ByVal oauth_nonce_in As String, ByVal oauth_timestamp_in As String, ByVal oauth_token_in As String, ByVal consumer_secret_in As String, ByVal oauth_token_Secret_in As String, ByVal query As String) As String
Dim myKey As String = percEncode(consumer_secret_in) "amp;" percEncode(oauth_token_Secret_in)
Dim percURL = percEncode(requestUrl)
Dim ris As String = ""
Dim signature_base As String = ""
Dim mypar As String = createAuthParam(consumer_key_in, oauth_nonce_in, oauth_timestamp_in, oauth_token_in, query)
signature_base = requestMethod amp; "amp;" amp; percURL amp; "amp;" amp; percEncode(mypar)
ris = HashString(signature_base, myKey)
Return ris
End Function
Public Function HashString(ByVal StringToHash As String, ByVal Key As String) As String
Dim oauth_signature As String
Dim hasher As HMACSHA1 = New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(Key))
Using hasher
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(StringToHash)))
End Using
Return oauth_signature
End Function
Public Function createAuthParam(ByVal consumer_key_in As String, ByVal nonce_in As String, ByVal oauth_timestamp_in As String, ByVal oauth_token_in As String, ByVal query As String) As String
Dim paramString As String = "oauth_consumer_key={0}amp;oauth_nonce={1}amp;oauth_signature_method={2}amp;oauth_timestamp={3}amp;oauth_token={4}amp;oauth_version={5}amp;{6}"
Dim authString As String = String.Format(paramString, percEncode(consumer_key_in), percEncode(nonce_in), oauth_signature_method, oauth_timestamp_in, oauth_token_in, oauth_version, reqParam(query))
Return authString
End Function
Public Function reqParam(ByVal statusInput As String) As String
Return "oauth_token=" amp; statusInput
End Function
Public Function makeRequest(ByVal query As String)
Dim requestResult As String = ""
oauth_nonce = setNounce()
oauth_timestamp = setTimeStamp()
Dim oauth_signature As String = getSignature(oauth_consumer_key, oauth_nonce, oauth_timestamp, oauth_token, consumer_secret, oauth_token_secret, query)
'Set the authorization header
Dim headerFormat As String = "OAuth oauth_nonce=""{0}"", oauth_signature_method=""{1}"", oauth_timestamp=""{2}"", oauth_consumer_key=""{3}"", oauth_token=""{4}"", oauth_signature=""{5}"", oauth_version=""{6}"""
Dim authHeader As String = String.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version))
'set the request
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Dim streamReader As System.IO.StreamReader
Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")
request = HttpWebRequest.Create(requestUrl amp; "?" amp; "oauth_token=" amp; oauth_token)
request.Timeout = -1
request.Headers.Add("Authorization", authHeader)
Try
response = DirectCast(request.GetResponse(), HttpWebResponse)
streamReader = New System.IO.StreamReader(response.GetResponseStream(), encode)
requestResult = streamReader.ReadLine()
request.Abort()
streamReader.Close()
streamReader = Nothing
response.Close()
response = Nothing
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
Return requestResult
End Function
End Class
Но эти коды возвращают «403 Forbidden». Может ли кто-нибудь привести мне пример авторизации в Twitter vb.net ? Я действительно устал.
Комментарии:
1. Ответ может быть с библиотекой LinqToTwitter, я тоже не могу использовать эту библиотеку.
2. Я не уверен, что вы все делаете правильно. Если вы хотите, чтобы ваше приложение получило доступ к вашей учетной записи, вам необходимо использовать метод «3-legged OAuth» , который они документируют, который включает в себя сначала получение PIN-кода, а затем его использование для получения токена авторизации, который затем можно использовать для доступа к вашей учетной записи на некоторое время.