Trying to request access token from Google oauth2 - vb.net

i'am trying to get started with dealing googles oauth2
My application vill be so called server application. it should be workin wihtout user input. My code so far(only trying to get access token):
Dim strToken = Request.QueryString("code")
Dim strExchange = "response_type=code"
strExchange += "&redirect_uri=http://xxxx.zzzzz.com/test/google.aspx"
strExchange += "&client_id=xxxx7hju.apps.googleusercontent.com"
strExchange += "&scope=&"
strExchange += "client_secret=yJpGI1yQBCvvxxxxx&grant_type=authorization_code"
Dim url = "https://accounts.google.com/o/oauth2/auth?"
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString(url & strExchange)
Response.Write(result)
This gives me bad reguest (400)

You can try this Article which handles the google calender entries. their you are able to get proper documentation for oauth2.0 authentication technique. Hope that all the values ware taken from App.Config
clientId = ConfigurationManager.AppSettings("client_id").ToString
clientSecret = ConfigurationManager.AppSettings("client_secret").ToString
redirecturi = ConfigurationManager.AppSettings("redirect").ToString
mainUser = ConfigurationManager.AppSettings("mainuser").ToString
Public Sub authorize()
Dim Uri As String = "https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=" & clientId & "&redirect_uri=" & redirecturi & "&scope=https://www.googleapis.com/auth/calendar&login_hint=" & mainUser & "&include_granted_scopes=true"
Response.Redirect(Uri)
End Sub

Related

How to obtain Access Token using production environment in DocuSign?

In Docusing I am obtained access token with demo account successfully and create envelope also, when I move to production account, I can't get access token and got error as "The remote server returned an error: (400) Bad Request." I did 20 API calls successfully and reviewed and make Go to live from developer account, API key details reflects on production login also.
Old Code
This is the code I used to obtain access token.
Dim PrivateKey As String = odjDTRep.Rows(0)("PrivateKey").ToString().Trim.Replace(vbLf, "").Replace(vbCr, "")
'This section to generate jwt Header
Dim ar1 As JObject = New JObject()
ar1.Add("typ", "JWT")
ar1.Add("alg", "RS256")
Dim header As String = Base64UrlEncoder.Encode(ar1.ToString)
'This section to generate jwt Body
Dim ar2 As JObject = New JObject()
ar2.Add("iss", odjDTRep.Rows(0)("iss_Int_Key").ToString())
ar2.Add("sub", odjDTRep.Rows(0)("sub1_Api_UserName").ToString())
ar2.Add("iat", DateDiff(DateInterval.Second, New Date(1970, 1, 1), Now().ToUniversalTime))
ar2.Add("exp", DateDiff(DateInterval.Second, New Date(1970, 1, 1), DateAdd(DateInterval.Hour, 1, Now().ToUniversalTime)))
ar2.Add("aud", odjDTRep.Rows(0)("aud").ToString())' aud i pass account.docusign.com
ar2.Add("scope", odjDTRep.Rows(0)("scope").ToString())
Dim body As String = Base64UrlEncoder.Encode(ar2.ToString)
Dim stringToSign As String = header & "." & body
Dim bytesToSign() As Byte = Encoding.UTF8.GetBytes(stringToSign)
Dim keyBytes() As Byte = Convert.FromBase64String(PrivateKey)
Dim privKeyObj = Asn1Object.FromByteArray(keyBytes)
Dim privStruct = RsaPrivateKeyStructure.GetInstance(privKeyObj)
'This section to generate jwt Signature
Dim sig As ISigner = SignerUtilities.GetSigner("SHA256withRSA")
sig.Init(True, New RsaKeyParameters(True, privStruct.Modulus, privStruct.PrivateExponent))
sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length)
Dim signature() As Byte = sig.GenerateSignature()
Dim sign As String = Base64UrlEncoder.Encode(signature)
Dim a As String = header & "." & body & "." & sign
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
ServicePointManager.SecurityProtocol = DirectCast(3072, SecurityProtocolType)
ServicePointManager.Expect100Continue = True
Dim request As WebRequest = WebRequest.Create("https://account.docusign.com/oauth/token?grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=" & a & "")
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = 0
request.Headers.Add("X-DocuSign-Authentication", "{ ""Username"":""" & odjDTRep.Rows(0)("UserName").ToString() & """, ""Password"":""" & odjDTRep.Rows(0)("Password").ToString() & """, ""IntegratorKey"":""" & odjDTRep.Rows(0)("iss_Int_Key").ToString() & """ }")
Dim response As WebResponse = request.GetResponse()
Console.WriteLine((CType(response, HttpWebResponse)).StatusCode)
If (CType(response, HttpWebResponse)).StatusCode <> HttpStatusCode.OK Then
Return "002:Fail"
End If
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
All details I read from SQL table and store in DataTable, from DataTable I pass all details in that code. Any other URL I need change above I mention for production environment?
New code to obtain Access token
var apiCent = new ApiClient("https://demo.docusign.net/restapi");
string ik = "xxxx-6a8b-4a7d-ba0f-xxxx";
string userId = "xxxxx-db97-xxx-a398-0e5986fadf49";
string accountId = "xxxxx-3e10-42af-xxxxx-xxxx";
string envId = "";
string authserver = "account.docusign.com";
string rsaKey = "xxxxxxxxxi7+b8i7SmfRdx8sExxxxxxxKmwIbLFOv1LtmUk/KRP8wPmMeNpq10kAzizzAeqnuBgW9ECHjV/gUA984dzk128UPmIRqTW+69e1dSknGA+nJWshyZEqJXmvFB8Ueie5EiCW6FIlXpdLVWwmJwUGiQQsV+r8hpmbhSImr5A40HQPPpasYAnKPNDgRbKwxrOONrCdUUre34Up2sk8gcAcMQRwKosPBn6/dAXadYP0sKEGSVKogguNSCyoHOLh74MPepDLnEVs9VAiyk+zQEmZxYaXhrV4pvO2C5WNXdnqHUdcC/McZOBVGwRdG0xOaC8t4lplJHjiis+8YQEWQIDAQABAoIBACTzxYJBBWGtVXRyqo+jzqmSOKJrBumvtHlC6k7IvYYInJI3IVPV44pC+eROAdDiYgQE9LZvag2MW7A8IAeYwWJZhBKCq8odz4plgJaZwX2YdItDP4kSjIOco5W4lMjMQd66KNMTKFkS2fgbtBF0crogO8cuAwn+kZtsdFH8IKA+LPQjvp09yXZvDN6Q8XTKfcIkW2TqthdUOcJP65h72KwQnQGGvTDAd8p3OsHqAt7LEwW6xg0ci2HT1fGZbdwrXVHFHX9mFPndLmQ1CZlwX8XiVIHYPdbEEjO+3U29jGsi/k8+h54ngcf5H1An8t+fdDVzknprbCGOIdynnLFq0CgYEA1os/qHEXObHe+Yn2EQWM924hPtOjY5Z6p60EEALaaKVLYiCyhI7fXkhfB0475gC0+HhGgyu0zts04iOE2Agr8Yc8jAkZ3/UGOrbBFoSSyHvKYQaYqdWJ4HjbV3L5jkWSzplmn5/KFM9COMecEpx0cXkhxt1MMC5gu3WKU5QWhMcCgYEAvdLlwOf33KUsG/dojZAtzK6Lz6UoBi+nHHg9jZ2V561xSzhrGGBTRkpUL5kf66AOrHRNYZvNX051WCzsQ94NBOzgwykhqcC+gYBx6ravoBgyyrw/YICQB69xkxJlq/uGZQf3cvcPfcxFbjySzjCqgmgXewmqJE2U0drnhDVzd8CgYBOGViuB6UNwptJuZgSsDOVqsh9Z2t2CERUH553+aHqMCnV6dMygBP97Vhyf188pgs63AXHIDTsjE2e+JEWVzsv7Cv1SibaKQcAfqChgtcwFigg09blFC/hv/0Qw3DnApqjjKIX/4H/u0b/BmLhP4T//bl2+/4NGATsmKgnLqRX5wKBgBFP36ZVQZS896XhTYbDpHmrXZLldB4EUJBXIv38ZkSH2/JJRfMmLdIWS1E//NpHca8muDvzsqpDhJn7qMe4KnVNaqzEBWlGaA4XaCgmm+aN3MYKt4nXRo9EfnhMUtXMW8G3caSPyBlapv5dLLPRjGdnk1mdhPUQsUytEdKLpIQvAoGAbcb1rHbHv9AlmBBq5JODGgfN9GbLpPR6KyCtUGPhIrcSyZF00PcIEckwwt1XvqFJXFzFWCs9SEq7YbmGKuxSVZ7NLOOLaX6lZ3HdBiHvqcsCdMiqw9egTqqkn2po7pGCQzwxYmGLBfF+MXDo3KTynvNMz31efrZlmQsVq3VBt9U=";
var scopes = new List<string>
{
"signature"
};
OAuth.OAuthToken authToken = apiCent.RequestJWTUserToken(ik, userId, authserver,Encoding.UTF8.GetBytes(rsaKey), 1, scopes);
string accessToken = authToken.access_token;
Now i am getting error as "Unexpected PEM type" , in production account i take IK,UserID and generated new RSA key.
First off, using legacy auth is not allowed for new applications. You are using the X-DocuSign-Authentication header with clear text password which is a legacy mechanism to authenticate. It is insecure and cannot be used.
When using JWT authentication and changing from the developer environment to the production environment you have to do the following:
Pass go-live and get approval to have your IK (app) in production.
Promote your IK to your production account.
Create a new RSA key for the new IK in the production account. You cannot use the RSA key from your developer account.
The URL for authentication is changed from https://account-s.docusign.com to https://account.docusign.com
userId for the user will be different GUID - need to update
accountId for the account will be different GUID - need to update

RestSharp response forbidden

I trying get a simple request to https://c-cex.com/t/prices.json
If i use this url in browser the correct response is showed , but if i make the same request using RestRequest i receive the 403 error Forbidden in all times. i trying HttpClient,WebRequest i get the same error
I put the header with user-agent, no cache and a lot of another values but did not work
Any ideas about this problem?
Dim url As String = "https://c-cex.com/t/prices.json"
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
Dim response = client.Execute(request)
Updated code with apisign request
Dim nonce As String = CInt((DateTime.UtcNow - New DateTime(1970, 1, 1)).TotalSeconds).ToString
Dim url As String = "https://c-cex.com/t/api.html?a=getbalance&currency=BTC&apikey=" & API_KEY & "&nonce=" & nonce
Dim keybytes() = UnicodeEncoding.ASCII.GetBytes(API_SECRET)
Dim hs As System.Security.Cryptography.HMACSHA512 = New System.Security.Cryptography.HMACSHA512(keybytes)
Dim urlbytes() = UnicodeEncoding.ASCII.GetBytes(url)
Dim sh() = hs.ComputeHash(urlbytes)
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
request.AddHeader("Cache-Control", "no-cache")
request.AddHeader("apisign", HttpUtility.UrlEncode(ToHexString(sh)))
Dim response = client.Execute(request)
I am getting the response without providing the header information and It looks given piece of code is working correctly for me in VB and C#.As a best practice, base URL needs to be specified in RestClient and relative URL in RestRequest.
Please recheck without adding the request header information
VB:
Imports RestSharp
Module Module1
Sub Main()
Dim host As String = "https://c-cex.com"
Dim endpoit As String = "t/prices.json"
Dim client As New RestSharp.RestClient(host)
Dim request = New RestRequest(endpoit, Method.GET)
Dim response = client.Execute(request)
Console.WriteLine("Response Body " + response.Content)
Console.WriteLine("Response Code " + response.StatusDescription)
End Sub
End Module
C#:
String host = "https://c-cex.com";
String endpoint = "t/prices.json";
RestClient _restClient = new RestClient(host);
var request = new RestRequest(endpoint, Method.GET);
var response = _restClient.Execute(request);
Console.WriteLine("Response Body :"+response.Content);
Console.WriteLine("Response Status Code :" + response.StatusDescription);

Acessing Google Calendar API from Windows Service

I am writing a windows service application in Visual Studio (VB) that polls a users google calendar for any events that are happening within the next 5 minutes.
Ideally, I'd like my service to generate the credentials, but I don't think a windows service can pop up a browser page to authenticate someone. Currently I am generating the credentials in a specific location from a console app that can pop up a browser, and having the service look for credentials in that location. I'd like to get rid of the console app altogether, but if it's necessary I'll just run it in the batch file that installs the service.
The big issue I'm having is generating the credentials file (secondary concern), and more importantly refreshing it so it doesn't expire after an hour (primary concern).
Here is my windows service code (this works perfectly fine for the hour after I run my console app and allow access to my calendar):
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Private Sub writeUpdateTimerEvent(source As Object, e As ElapsedEventArgs)
Dim credential As UserCredential
Try
Using stream = New FileStream("FILE PATH TO client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "FILE PATH TO WHERE MY CONSOLE APP IS STORING THE CREDENTIALS FILE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
If credential Is Nothing Then
credential.RefreshTokenAsync(CancellationToken.None)
End If
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.TimeMax = DateTime.Now.AddMinutes(5)
request.ShowDeleted = False
request.SingleEvents = True
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim eventsString As String = ""
Dim events As Events = request.Execute()
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
'This is where I do my operations on events occuring in the next 5 minutes
EventLog1.WriteEntry("Event occuring within 5 minutes")
Else
EventLog1.WriteEntry("No event occuring within 5 minutes")
End If
Catch ex As Exception
EventLog1.WriteEntry("error grabbing events." & Environment.NewLine & ex.message)
End Try
End Sub
Here is my console app code (pretty much the same as above):
Module Module1
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Sub Main()
Dim credential As UserCredential
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "SAME FILE PATH AS IN MY SERVICE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.ShowDeleted = False
request.SingleEvents = True
request.MaxResults = 10
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim events As Events = request.Execute()
Console.WriteLine("Upcoming events:")
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
For Each eventItem As Object In events.Items
Dim [when] As String = eventItem.Start.DateTime.ToString()
If [String].IsNullOrEmpty([when]) Then
[when] = eventItem.Start.[Date]
End If
Console.WriteLine("{0} ({1})", eventItem.Summary, [when])
Next
Console.WriteLine("You may now close this window.")
System.Environment.Exit(0)
Else
Console.WriteLine("No upcoming events found.")
End If
Console.Read()
End Sub
End Module
Got it working now, using a service account instead of a user account. No need for dealing with generating credentials or refreshing the token.
Dim serviceAccountEmail As [String] = ConfigurationManager.AppSettings("ServiceAcct")
Dim certificate = New X509Certificate2("key.p12", "notasecret", X509KeyStorageFlags.Exportable)
Dim credential1 As New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = Scopes
}.FromCertificate(certificate))
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential1,
.ApplicationName = ApplicationName
})

WP7, getting weird response from twitter

i am using hammock twitter library to post and get the friends list from Twitter. Previously it was working fine. But now only the request_token part is working. While trying to get the access tokens and userid, screen name getting an "OK" server response. But the result looks likes this:
� �Dͻ�0#�as�"Ё��&b�����֔ԧ��8ߑ��h9�v�r<{g�/�XR>�eݻ.>~�rH�5�Z��_�~�+Kn9��)��£�sU��)��������|�TV6!�B��2(���֚V`�!��#4�� �� ��?d�
I dont know why i am getting this.. :(
below is my code
Public Sub GetRequestToken(Consumer_KEY As String, Consumer_Secret_Key As String)
Dim credentials = New OAuthCredentials
credentials.Type = OAuthType.RequestToken
credentials.SignatureMethod = OAuthSignatureMethod.HmacSha1
credentials.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader
credentials.ConsumerKey = TwitterSettings.ConsumerKey
credentials.ConsumerSecret = TwitterSettings.ConsumerKeySecret
credentials.Version = TwitterSettings.OAuthVersion
credentials.CallbackUrl = "oob"
Dim client = New RestClient
client.Authority = "https://api.twitter.com/oauth"
client.Credentials = credentials
client.HasElevatedPermissions = True
Dim request = New RestRequest
request.Path = "/request_token"
client.BeginRequest(request, New RestCallback(AddressOf TwitterRequestTokenCompleted))
End Sub
Public Sub TwitterRequestTokenCompleted(request As RestRequest, response As RestResponse, userstate As Object)
result = Regex.Split(response.Content, "&")
oauth_token = Regex.Split(result(0), "=")(1)
oauth_secret_token = Regex.Split(result(1), "=")(1)
request_url = TwitterSettings.AuthorizeUri + "?oauth_token=" + oauth_token
case_url = "request"
Deployment.Current.Dispatcher.BeginInvoke(getresult)
End Sub
After parsing the oob pin, i am requesting for access tokens:
Public Sub GetAccessToken(Verifier As String)
Dim credentials = New OAuthCredentials
credentials.Type = OAuthType.AccessToken
credentials.SignatureMethod = OAuthSignatureMethod.HmacSha1
credentials.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader
credentials.ConsumerKey = TwitterSettings.ConsumerKey
credentials.ConsumerSecret = TwitterSettings.ConsumerKeySecret
credentials.Token = oauth_token
credentials.TokenSecret = oauth_secret_token
credentials.Verifier = Verifier
Dim client = New RestClient
client.Authority = "https://api.twitter.com/oauth"
client.Credentials = credentials
client.HasElevatedPermissions = True
Dim request = New RestRequest
request.Path = "/access_token"
client.BeginRequest(request, New RestCallback(AddressOf RequestAccessTokenCompleted))
did anyone face this before? i need this asap.. just confused how this happened all of a sudden. Thanks in advance geeks ;)

Creating webrequest POST for Twitter API using VB.NET

There are quite a few Twitter API related posts, but none seem to answer my questions directly.
I know how to send an HttpWebRequest as POST.
I am fairly sure I need to send the webrequest to: "https://api.twitter.com/1/statuses/update.json" (not totally clear)
I know there are many libraries out there that all you have to do is pass your consumer keys and token keys. However, I need to create some very short code, in a function, that simple posts a hard coded string to Twitter. When I get this working that hard coded string will be replaced by variable.
I've no need to status updates or any kind of information from Twitter. Just POST "Hello World!" to start with, and I can go from there.
I am forced to use VB.NET. I am using Visual Studio Web Developer 2010.
Now, that all said, I have looked at Nikolas Tarzia's VB.NET port of C-Sharp code here:
http://oauth.googlecode.com/svn/code/vbnet/oAuth.vb
I can see roughly what the functions do by looking at them, but have no idea which ones I need to call to create a webresponse and send to Twitter! Also I believe this code contains more than I need. If I just want to create a POST, then likely I only need to hash function and the nonce function and my tokens and keys. Is that right? If so, could someone please help me narrow this down? In the process helping me understand a bit better what properly formed webrequest needs to be sent to Twitter to make a quick Tweet?
Thanks,
Will
PS - I finally put together some code, based on looking at OAuth documentation, a neat little code example on using POST request in VB, and the Twitter Developer area OAuth tool to generate some Base String for the request. Unfortunately while it compiles and runs okay, I am not getting a tweet. Could someone have a look at the code and see if they can spot any glaring issues? Obviously I replaced my tokens and consumer keys with "xxxxx". All I want for Christmas is to run this code and make a quick Tweet on my Twitter account! ;)
Public Shared Function Tweet(strText As String) As Boolean
Dim boolResult As Boolean = False
Dim urlAddress As Uri = New Uri("https://api.twitter.com/1/statuses/update.json")
Dim strData As StringBuilder
Dim byteData() As Byte
Dim postStream As Stream = Nothing
Dim strConsumerKey As String = "xxxxxx"
Dim strConsumerSecret As String = "xxxxxx"
Dim strAccessToken As String = "xxxxxx"
Dim strAccessTokenSecret As String = "xxxxxx"
Dim objRequest As HttpWebRequest
Dim objResponse As HttpWebResponse = Nothing
Dim objReader As StreamReader
Dim objHeader As HttpRequestHeader = HttpRequestHeader.Authorization
Try
objRequest = DirectCast(WebRequest.Create(urlAddress), HttpWebRequest)
objRequest.Method = "POST"
objRequest.ContentType = "application/x-www-form-urlencoded"
strData = New StringBuilder()
strData.Append("&Hello_World%2521%3D%26oauth_consumer_key%3D" + strConsumerKey + "%26oauth_nonce%3Dda6bb8ce7e48547692f4854833afa680%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1329746260%26oauth_token%3D" + strAccessToken + "%26oauth_version%3D1.0")
objRequest.Headers.Add(objHeader, "Authorization: OAuth oauth_consumer_key=""xxxx"", oauth_nonce=""da6bb8ce7e48547692f4854833afa680"", oauth_signature=""xxxx"", oauth_signature_method=""HMAC-SHA1"", oauth_timestamp=""1329750426"", oauth_token=""xxxx"", oauth_version=""1.0""")
' Create a byte array of the data we want to send
byteData = UTF8Encoding.UTF8.GetBytes(strData.ToString())
' Set the content length in the request headers
objRequest.ContentLength = byteData.Length
Try
postStream = objRequest.GetRequestStream()
postStream.Write(byteData, 0, byteData.Length)
Finally
If Not postStream Is Nothing Then postStream.Close()
End Try
boolResult = True
Catch ex As Exception
boolResult = False
HttpContext.Current.Session.Add("Error", ex.ToString())
End Try
Try
' Get response
objResponse = DirectCast(objRequest.GetResponse(), HttpWebResponse)
' Get the response stream into a reader
objReader = New StreamReader(objResponse.GetResponseStream())
' Console application output
Console.WriteLine(objReader.ReadToEnd())
Finally
If Not objResponse Is Nothing Then objResponse.Close()
End Try
Return boolResult
End Function
I´ve made this class to post in twitter using API1.1.
It expects the oauth token, oauth token secret, oauth "consumer" key (this means API key) and oauth consumer secret (this means API secret) in the constructor. If you want to post in your own account, the four values will be in the API keys tab of your application in https://apps.twitter.com/. If you want to post on your visitors account you'll have to create some extra code to redirect them to twitter for login and get the access token.
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text
Imports System.Security.Cryptography
Imports System.Net
Imports System.IO
Public Class SBTwitter
Private oauth_token As String
Private oauth_token_secret As String
Private oauth_consumer_key As String
Private oauth_consumer_secret As String
Public Sub New(ByVal APIKey As String, ByVal APISecret As String, ByVal oauthToken As String, ByVal oauthTokenSecret As String)
oauth_token = oauthToken
oauth_token_secret = oauthTokenSecret
oauth_consumer_key = APIKey
oauth_consumer_secret = APISecret
End Sub
Public Function PostInTwitter(ByVal post As String) As String
Try
Dim oauth_version = "1.0"
Dim oauth_signature_method = "HMAC-SHA1"
Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim timeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, _
0, DateTimeKind.Utc)
Dim oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim resource_url = "https://api.twitter.com/1.1/statuses/update.json"
Dim status = post
Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" & "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}"
Dim baseString = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, _
oauth_version, Uri.EscapeDataString(status))
baseString = String.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString))
Dim compositeKey = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))
Dim oauth_signature As String
Using hasher As New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
End Using
Dim headerFormat = "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 = 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))
Dim postBody = "status=" & Uri.EscapeDataString(status)
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(resource_url), HttpWebRequest)
request.Headers.Add("Authorization", authHeader)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Using stream As Stream = request.GetRequestStream()
Dim content As Byte() = ASCIIEncoding.ASCII.GetBytes(postBody)
stream.Write(content, 0, content.Length)
End Using
Dim response As WebResponse = request.GetResponse()
Return response.ToString
Catch ex As Exception
Return ex.Message
End Try
End Function
End Class