Am trying to create a simple page that connects to an external website, logs in, and then passes a bunch of parameters.
When I run the page I get a bad request 400 error and when I check using Fiddler I can see there are both 401 and 400 errors being returned. Under 'Auth' in Fiddler I see:
"No Proxy-Authorization Header is present.
No Authorization Header is present." < Is this relevant? As when I test using PHP cUrl the page can log in fine and Fiddler says the same under Auth.
Dim UserName As String = "testusername"
Dim password As String = "testpassword"
Dim siteCredentials As New NetworkCredential(UserName, password)
Dim URLAuth As String = "http://service.someurl.com/process.xml"
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
Const contentType As String = "application/x-www-form-urlencoded"
System.Net.ServicePointManager.Expect100Continue = False
Dim cookies As New CookieContainer()
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(URLAuth), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.ContentType = contentType
webRequest__1.CookieContainer = cookies
webRequest__1.ContentLength = postBytes.Length
webRequest__1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
webRequest__1.Referer = "http://service.someurl.com/process.xml"
webRequest__1.Credentials = siteCredentials
Try
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim testcapture As String = requestStream.ToString
Dim thing As String = "stop"
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
Catch ex As Exception
Lbl_ConnTest_error.Text = ex.Message
End Try
Seems the login credentials are not being passed what am I doing wrong? I am obviously using vb in an asp.net application but am connecting to an XML file held on Linux Apache, does this have any implications at all?
Fiddler appears to be doing strange things for me now so if anyone else can see anything using Fiddler a link to the test file is here:
http://www.filemanage.co.uk/Pubs/Default.aspx
Related
I am trying to send emails through gmail host by using google oauth 2.0, I am confused where to use the access code instead of user password to send emails,
this code is used to open up the consent screen and ask for permissions,
Dim Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" & googleplus_redirect_url & "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile%20https://mail.google.com/%20https://www.googleapis.com/auth/gmail.send&client_id=" + googleplus_client_id
Session("loginWith") = "google"
Response.Redirect(Googleurl)
after getting permissions, this is how I obtained access code,
If url <> "" Then
Dim queryString As String = url.ToString()
Dim delimiterChars As Char() = {"="c}
Dim words As String() = queryString.Split(delimiterChars)
Dim code As String = words(1)
If code IsNot Nothing Then
Dim webRequest As HttpWebRequest = CType(webRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
webRequest.Method = "POST"
Parameters = "code=" & code & "&client_id=" & googleplus_client_id & "&client_secret=" + googleplus_client_secret & "&redirect_uri=" + googleplus_redirect_url & "&grant_type=authorization_code"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(Parameters)
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.ContentLength = byteArray.Length
Dim postStream As Stream = webRequest.GetRequestStream()
postStream.Write(byteArray, 0, byteArray.Length)
postStream.Close()
Dim response As WebResponse = webRequest.GetResponse()
postStream = response.GetResponseStream()
Dim reader As StreamReader = New StreamReader(postStream)
Dim responseFromServer As String = reader.ReadToEnd()
Dim serStatus As GooglePlusAccessToken = JsonConvert.DeserializeObject(Of GooglePlusAccessToken)(responseFromServer)
If serStatus IsNot Nothing Then
Dim accessToken As String = String.Empty
accessToken = serStatus.access_token
If Not String.IsNullOrEmpty(accessToken) Then
getgoogleplususerdataSer(accessToken)
End If
End If
End If
End If
and using the below code to send emails:
mm.Subject = LetterSubject.Text
Dim body As String
body = LetterBody.Text
mm.Body = body
Dim smtp As New Mail.SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
smtp.Port = 587
smtp.UseDefaultCredentials = False
Dim service = New GmailService(New BaseClientService.Initializer With {.HttpClientInitializer = cred})
Dim NetworkCred As New NetworkCredential(SenderEmailAddress.Text, SenderPassword.Text)
smtp.Credentials = NetworkCred
smtp.Send(mm)
Can someone please help me how to use token here to send emails without using the user gmail password?
Imports System
Imports System.Threading.Tasks
Imports Google.Apis.Discovery.v1
Imports Google.Apis.Discovery.v1.Data
Imports Google.Apis.Services
Class Program
<STAThread>
Private Shared Sub Main(ByVal args As String())
Console.WriteLine("Discovery API Sample")
Console.WriteLine("====================")
Try
New Program().Run().Wait()
Catch ex As AggregateException
For Each e In ex.InnerExceptions
Console.WriteLine("ERROR: " & e.Message)
Next
End Try
Console.WriteLine("Press any key to continue...")
Console.ReadKey()
End Sub
Private Async Function Run() As Task
Dim service = New DiscoveryService(New BaseClientService.Initializer With {
.ApplicationName = "Discovery Sample",
.ApiKey = "[YOUR_API_KEY_HERE]"
})
Console.WriteLine("Executing a list request...")
Dim result = Await service.Apis.List().ExecuteAsync()
If result.Items IsNot Nothing Then
For Each api As DirectoryList.ItemsData In result.Items
Console.WriteLine(api.Id & " - " + api.Title)
Next
End If
End Function
End Class
''Your Authentication key should be static
''Dim NetworkUserName As String= "apikey"
' Dim YOUR_API_KEY_HERE As String = "SG.EEyBZDVAS622C6Rt7yu1sw.jwRdfkjJddfsJfgfsyuJuyuHutytr876RuQsffhghdf1d"
I have suddenly started receiving the following error when connecting to the LinkedIn oAuth2 API...
The underlying connection was closed: An unexpected error occurred on a send.
This is normally caused by ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 not being set.
The line of code that errors is
Dim oStream As Stream = oWebRequest.GetRequestStream()
I have set this in code;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
But continue getting the error. If I run the code locally it works fine but not on the deployed server. The server is Windows 2012 R2. I have disabled all versions of SSL / TLS prior to TLS 1.2 on the server and performed a restart of the server but still the error persists even with ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 set in the code.
The code runs locally but I still receive the error on the server and I am out of ideas!
Dim sSocialMediaClientID = String.Empty
Dim sSocialMediaSecretKey = String.Empty
Dim sAuthServiceUrl As String = String.Empty
Dim sProfileAccessServiceUrl As String = String.Empty
Dim sEmailAddressAccessServiceUrl As String = String.Empty
sCallBackURL = String.Concat(sCallBackURL, "/RequestHandler/LinkedInCallBack")
sSocialMediaClientID = "Client ID"
sSocialMediaSecretKey = "Client Secret"
sAuthServiceUrl = "https://www.linkedin.com/oauth/v2/accessToken"
sProfileAccessServiceUrl = "https://api.linkedin.com/v2/me?oauth2_access_token={0}"
sEmailAddressAccessServiceUrl = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))&oauth2_access_token={0}"
Dim sCode As String = Request.QueryString("code")
sAuthToken = pf_ProcessAuthRequest(sAuthServiceUrl, sCode, sCallBackURL, sSocialMediaClientID, sSocialMediaSecretKey)
Private Function pf_ProcessAuthRequest(ByVal inAuthServiceUrl As String, ByVal inAuthCode As String, ByVal inCallBackUrl As String, ByVal inClientID As String, ByVal inClientSecret As String) As String
Dim sAuthToken As String = String.Empty
Dim oPostData As New StringBuilder()
oPostData.AppendFormat("grant_type=authorization_code")
oPostData.AppendFormat("&code={0}", inAuthCode)
oPostData.AppendFormat("&redirect_uri={0}", HttpUtility.UrlEncode(inCallBackUrl))
oPostData.AppendFormat("&client_id={0}", inClientID)
oPostData.AppendFormat("&client_secret={0}", inClientSecret)
Dim oByteArray As Byte() = Encoding.UTF8.GetBytes(oPostData.ToString())
'
' Create the web request
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim oWebRequest As WebRequest = WebRequest.Create(inAuthServiceUrl)
oWebRequest.Method = "POST"
oWebRequest.ContentType = "application/x-www-form-urlencoded"
oWebRequest.ContentLength = oByteArray.Length
'
' Add the post data
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
'the next line errors!
Dim oStream As Stream = oWebRequest.GetRequestStream()
oStream.Write(oByteArray, 0, oByteArray.Length)
oStream.Close()
'
' Get the response
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim oResponse As WebResponse = oWebRequest.GetResponse()
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim sResultStatus As String = CType(oResponse, HttpWebResponse).StatusDescription
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
oStream = oResponse.GetResponseStream()
Dim oReader As StreamReader = New StreamReader(oStream)
Dim sJSON As String = oReader.ReadToEnd()
Dim oJObj As JObject = JObject.Parse(sJSON)
sAuthToken = oJObj("access_token").ToString
oReader.Close()
oStream.Close()
oResponse.Close()
Return sAuthToken
End Function
Try changing sAuthServiceUrl = "https://www.linkedin.com/oauth/v2/accessToken"
to sAuthServiceUrl = "https://api.linkedin.com/oauth/v2/accessToken"
This is my code it is in vb.net . I did'nt get response from soap request , i have no idea what is the wrong with this code , its showing 500 Internal Server Error.
Dim webRequest__1 As WebRequest = WebRequest.Create("https://login.twinfield.com/webservices/session.asmx?wsdl")
Dim httpRequest As HttpWebRequest = DirectCast(webRequest__1, HttpWebRequest)
httpRequest.Method = "POST"
httpRequest.ContentType = "application/soap+xml;charset=UTF-8;action='http://www.twinfield.com/Logon'"
httpRequest.Host = "login.twinfield.com"
httpRequest.Headers.Add("SOAPAction:https://login.twinfield.com/webservices/session.asmx")
httpRequest.ProtocolVersion = HttpVersion.Version11
httpRequest.Credentials = CredentialCache.DefaultCredentials
Dim requestStream As Stream = httpRequest.GetRequestStream()
'Create Stream and Complete Request
Dim streamWriter As New StreamWriter(requestStream, Encoding.ASCII)
' <soap:Envelope xmlns:soap='http://www.w3.org/2003/05/soap-envelope' xmlns:twin='http://www.twinfield.com/'>
Dim soapRequest As New StringBuilder("<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap='http://www.w3.org/2003/05/soap-envelope' xmlns:twin='http://www.twinfield.com/'><soap:Header/><soap:Body><twin:Logon><twin:user>dgf</twin:user> <twin:password>cfg</twin:password><twin:organisation>dfd</twin:organisation></twin:Logon></soap:Body></soap:Envelope>")
'soapRequest.Append(" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" ")
'soapRequest.Append("xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""><soap:Body>")
'soapRequest.Append("<GetMyName xmlns=""http://tempuri.org/""><name>Sam</name></GetMyName>")
'soapRequest.Append("</soap:Body></soap:Envelope>")
streamWriter.Write(soapRequest.ToString())
streamWriter.Close()
'Get the Response
Dim htttpresponse As HttpWebResponse = CType(httpRequest.GetResponse(), HttpWebResponse)
'Dim wr As HttpWebResponse = CType(httpRequest.GetResponse(), HttpWebResponse)
'DirectCast(httpRequest.GetResponse(), HttpWebResponse)
Dim srd As New StreamReader(htttpresponse.GetResponseStream())
Dim resulXmlFromWebService As String = srd.ReadToEnd()
'Return resulXmlFromWebService
To call a soap web service, I think it is better to add the service url as a web reference (i.e. name as twinfield) in visual studio. Then you can use the service as a function as below.
twinfield.Session s = new twinfield.Session();
twinfield.LogonAction ac;
string cl = "";
twinfield.LogonResult k = s.Logon("dsfa", "Sadfsa", "sdfas", out ac, out cl);
I'm trying to view the HTTP request being sent/received to twitter. I tried downloading fiddler4 but it's not registering the 401 error and I'm only receiving the 500 page error. Any ideas on how to view the request being sent so I can trouble shoot the reason?
I tried viewing the site as localhost, 127.0.0.1, and machinename.
Dim oAuthRequest As New Dictionary(Of String, String)
oAuthRequest.Add("resource_url", "https://api.twitter.com/oauth/request_token")
oAuthRequest.Add("oauth_callback", Server.UrlEncode("https://www.site.com/callback/"))
oAuthRequest.Add("oauth_consumer_key", "xxxxxxxx")
oAuthRequest.Add("oauth_nonce", Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())))
oAuthRequest.Add("oauth_signature_method", "HMAC-SHA1")
oAuthRequest.Add("oauth_timestamp", CInt((DateTime.UtcNow - New DateTime(1970, 1, 1)).TotalSeconds).ToString)
oAuthRequest.Add("oauth_token", "authorization_code")
Dim baseFormat As String = "oauth_callback=""{0}""&oauth_consumer_key=""{1}""&oauth_nonce=""{2}""&oauth_signature_method=""HMAC-SHA1""&oauth_timestamp=""{3}""&oauth_version=""" & Uri.EscapeDataString("1.0") & """"
Dim baseString As String = String.Format(baseFormat,
oAuthRequest("oauth_callback"),
oAuthRequest("oauth_consumer_key"),
oAuthRequest("oauth_nonce"),
oAuthRequest("oauth_timestamp"))
baseString = String.Concat("POST&", Uri.EscapeDataString(oAuthRequest("resource_url")), "&", Uri.EscapeDataString(baseString))
oAuthRequest.Add("oauth_signature", SHA1Base64Hash("xxxxxxx&", baseString))
Dim authHeaderFormat As String = "OAuth oauth_callback=""{0}"",oauth_consumer_key=""{1}"",oauth_nonce=""{2}"",oauth_signature=""{3}"",oauth_signature_method=""HMAC-SHA1"",oauth_timestamp=""{4}"",oauth_version=""1.0"""
Dim authHeader As String = String.Format(authHeaderFormat,
Uri.EscapeDataString(oAuthRequest("oauth_callback")),
Uri.EscapeDataString(oAuthRequest("oauth_consumer_key")),
Uri.EscapeDataString(oAuthRequest("oauth_nonce")),
Uri.EscapeDataString(oAuthRequest("oauth_signature")),
Uri.EscapeDataString(oAuthRequest("oauth_timestamp")))
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest = CType(WebRequest.Create(oAuthRequest("resource_url")), HttpWebRequest)
request.Headers.Add("Authorization", authHeader)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Try
Dim response As WebResponse = request.GetResponse()
Catch ex As Exception
Text.text = ex.Message
End Try
If Fiddler shows you a HTTP/500 rather than a HTTP/401, that's because the server is returning HTTP/500. Unless you tell it to do so, Fiddler does not invent responses.
I am trying to access a page where I need to log into the website and pass a a list of parameters. I appear to be able to log into the site (if I change the log in details I get a 401 unauthorised error) but then I get a 400 bad request error. The code is a bit hashed together so I know something is wrong but don't know where.
EDITED CODE
Public Sub TestConn()
Dim customeremailaddress As String = HttpUtility.UrlEncode("r.test#test.com")
Dim customername As String = HttpUtility.UrlEncode("Ryan")
Dim referenceid As String = HttpUtility.UrlEncode("ordertest123")
Dim languagecode As String = HttpUtility.UrlEncode("1043")
Dim expirydays As String = HttpUtility.UrlEncode("30")
Dim UserName As String = "testusername"
Dim password As String = "testpassword"
Dim siteCredentials As New NetworkCredential(UserName, password)
Dim URLAuth As String = "http://service.someurl.com/process.xml"
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
Const contentType As String = "application/x-www-form-urlencoded"
System.Net.ServicePointManager.Expect100Continue = False
Dim cookies As New CookieContainer()
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(URLAuth), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.ContentType = contentType
webRequest__1.CookieContainer = cookies
webRequest__1.ContentLength = postBytes.Length
webRequest__1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
webRequest__1.Referer = "http://service.someurl.com/process.xml"
webRequest__1.Credentials = siteCredentials
Try
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
Catch ex As Exception
Lbl_ConnTest_error.Text = ex.Message
End Try
End Sub
You need to send the bytes of the postString not the string itself:
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
...
webRequest__1.ContentLength = postBytes.Length
...
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
More information here.