reCaptcha - reading JSON response - asp.net

I get a response from the reCapture and need to read the "success" value, but get the error:
Public member 'success' on type 'Dictionary(Of String,Object)' not found.
Response
{ "success": true, "challenge_ts": "2017-02-20T13:55:01Z", "hostname": "domain.co.uk" }
I'm trying to access it using:
data.success
Full code
Dim Response As String = Request.Form("g-recaptcha-response")
Dim Valid As Boolean = False
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(Convert.ToString("https://www.google.com/recaptcha/api/siteverify?secret=" & SecretKey & "&response=") & Response), HttpWebRequest)
Try
Using wResponse As WebResponse = req.GetResponse()
Using readStream As New StreamReader(wResponse.GetResponseStream())
Dim jsonResponse As String = readStream.ReadToEnd()
Dim js As New JavaScriptSerializer()
Dim data As Object = js.Deserialize(Of Object)(jsonResponse)
Valid = Convert.ToBoolean(data.success)
End Using
End Using
Return Valid
Catch ex As WebException
Throw ex
End Try

Got the answer in the end so in case this helps anyone it's:
data("success")
Rather than
data.success

Related

Convert cURL to ASP.Net

I'm looking for a way to convert the following cURL to ASP.Net.
curl -F f=#example.pdf "https://pdftables.com/api?key=ZZZ999&format=xml"
I've used the following function extensively to get virtually any URL/content, but I'm lost on how to include a file located on the hosted web server.
Public Shared Function GetRemoteURL(getURL As String) As String
Dim objReq As HttpWebRequest
Dim objRsp As HttpWebResponse = Nothing
Dim objRdr As StreamReader
Dim objRes As String = ""
Try
objReq = DirectCast(WebRequest.Create(getURL), HttpWebRequest)
objRsp = DirectCast(objReq.GetResponse(), HttpWebResponse)
objRdr = New StreamReader(objRsp.GetResponseStream())
objRes = objRdr.ReadToEnd()
Catch
objRes = ""
Finally
If Not objRsp Is Nothing Then objRsp.Close()
End Try
Return objRes.ToString()
End Function
Any advice/direction would be deeply appreciated.
John
You'll have to set the request body, something like:
Public Function GetRemoteURL(getURL As String) As String
Dim objReq As HttpWebRequest
Dim objRsp As HttpWebResponse = Nothing
Dim objRdr As StreamReader
Dim objRes As String = ""
Try
objReq = DirectCast(WebRequest.Create(getURL), HttpWebRequest)
objReq.Method = "POST"
Dim postData = "f=#example.pdf"
Dim encoding As New ASCIIEncoding()
Dim bytes = encoding.GetBytes(postData)
objReq.ContentLength = bytes.Length
Dim stream = objReq.GetRequestStream()
stream.Write(bytes, 0, bytes.Length)
objRsp = DirectCast(objReq.GetResponse(), HttpWebResponse)
objRdr = New StreamReader(objRsp.GetResponseStream())
objRes = objRdr.ReadToEnd()
Catch
objRes = ""
Finally
If Not objRsp Is Nothing Then objRsp.Close()
End Try
Return objRes.ToString()
End Function
note: i didn't test this so it might not directly work.

System.Net.WebException' occurred in System.dll but was not handled in user code

Try
Dim url = "something"
Dim request = WebRequest.Create(url)
request.Credentials = CredentialCache.DefaultCredentials
Dim httpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim dataStream = httpWebResponse.GetResponseStream()
If dataStream Is Nothing Then
Return ""
End If
Dim reader = New StreamReader(dataStream)
Return reader.ReadToEnd()
Catch ex As WebException
Return ""
End Try
Above code is working in LocalHost but in server it's not working and throwing an Exception.
System.Net.WebException' occurred in System.dll but was not handled
in user code
You're re-throwing the exception after the Catch.
Remove Throw.
Try
Dim url = "something"
Dim request = WebRequest.Create(url)
request.Credentials = CredentialCache.DefaultCredentials
Dim httpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim dataStream = httpWebResponse.GetResponseStream()
If dataStream Is Nothing Then
Return ""
End If
Dim reader = New StreamReader(dataStream)
Return reader.ReadToEnd()
Catch ex As WebException
Return ""
End Try

Consuming Webservice - Sending Signature- Error X509Certificate2 type was not expected

I'm consume an external webservice for sending data, using a web application in asp.net and Visual Studio 2010. The
sending of data must be digitally signed using a digital signature. The webservice contains the Signature class, where I
can fill all required values ​​(SignedInfo, SignatureValue, KeyInfo).
I'm trying to fill the KeyInfo structure with the certificate like this:
Dim Sig As New RSP.SignatureType
(...)
Sig.SignedInfo = Sig_info
(...)
Sig.SignatureValue = Sig_value
Dim rspKey_info As New RSP.KeyInfoType()
Dim rspX509 As New RSP.X509DataType()
Dim arrCertificate As X509Certificate2()
arrCertificate = myF.ReturnCertificateCC()
rspKey_info.ItemsElementName = New RSP.ItemsChoiceType2(0) {}
rspKey_info.ItemsElementName(0) = RSP.ItemsChoiceType2.X509Data
rspKey_info.Items = New Object(0) {}
rspX509.ItemsElementName = New RSP.ItemsChoiceType2(0) {}
rspX509.ItemsElementName(0) = RSP.ItemsChoiceType2.X509Data
rspX509.Items = New Object(0) {}
rspX509.Items(0) = arrCertificate (0)
Sig.KeyInfo = rspKey_info
xmlString = myF.SerializeAnObject(Sig)
When I try to serialize the Signature Object, an error occur:
"Error generating the XML document."
InnerException:
"{ " The System.Security.Cryptography.X509Certificates.X509Certificate2 type was not expected . Use XmlInclude or
SoapInclude attribute to specify types that are not known statically. "}"
Public Function SerializeAnObject(ByVal obj As Object) As String
Dim doc As System.Xml.XmlDocument = New XmlDocument()
Dim serializer As System.Xml.Serialization.XmlSerializer = New System.Xml.Serialization.XmlSerializer(obj.GetType())
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream()
Try
serializer.Serialize(stream, obj)
stream.Position = 0
doc.Load(stream)
Return doc.InnerXml
Catch ex As Exception
Return ""
Finally
stream.Close()
stream.Dispose()
End Try
'#utilização
'dim xmlObject As string = SerializeAnObject(myClass)
End Function
Please help me...
I'm at several days trying to solve this...
Thanks in advance!
Regards!
rspX509.ItemsElementName = New RSP.ItemsChoiceType(0) {}
rspX509.ItemsElementName(0) = RSP.ItemsChoiceType.X509Certificate
rspX509.Items = New Object(0) {}
rspX509.Items(0) = arrCertificate (0)
rspKey_info.Items(0) = rspX509

Capturing 401 errors with Fiddler - Twitter OAUTH 1.0

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.

HttpWebRequests Returning error from Youtube

I cannot seem to understand what I'm doing wrong here.
My code below keeps returning a 400 code from youtube....
If Not Page.Request.QueryString("code") Is Nothing Then
Dim code As String = "code=" & Page.Request.QueryString("code") & "&client_id=myclientid&client_secret=mysecret&redirect_uri=http://localhost:61163/Testing/YoutubeAPI.aspx&grant_type=authorization_code"
Dim request As HttpWebRequest = WebRequest.Create("https://accounts.google.com/o/oauth2/token")
Dim byteData As Byte() = Encoding.UTF8.GetBytes(code)
With request
.Method = "POST"
.ContentType = "application/x-www-form-urlencoded"
.ContentLength = byteData.Length
End With
Dim requestStream As Stream = request.GetRequestStream()
requestStream.Write(byteData, 0, byteData.Length)
requestStream.Close()
Dim WebResponse As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim responseStream As Stream = WebResponse.GetResponseStream()
Dim sb As StringBuilder = New StringBuilder
Using reader As New StreamReader(responseStream, System.Text.Encoding.UTF8)
Dim line As String = reader.ReadLine()
If Not line Is Nothing Then
sb.Append(line)
End If
End Using
End If
the error occurs at request.GetRequestStream()... the best I can figure out at this stage is that google doesn't like what i'm asking for but cannot seem to find out why?
(My client ID and secret have been swopped incidentally....)
well am not sure if the etiquette is correct here in answering my own question but you may find it useful nonetheless.
The answer lay in the URL encoding of content string...
so now slightly amended the awesomeness of OAuth2 is unleashed and I can get pretty much whatever I want from the youtube API :) (although NO thanks to the black hole rabbit-hole of google documentation...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.Request.QueryString("code") Is Nothing Then
Dim Token As String = CodeTrade("code=" & Server.UrlEncode(Page.Request.QueryString("code")) & "&redirect_uri=" & Server.UrlEncode("http://localhost:61163/Testing/YoutubeAPI.aspx") & "&client_id=xxx=&client_secret=xxx&grant_type=authorization_code")
'now i CAN do something with the magical and elusive access_token from this point forward....
End If
End Sub
Public Shared Function CodeTrade(code As String) As String
Dim apiResponse As String
Dim postData As String = code
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
apiResponse = DirectCast(response, HttpWebResponse).StatusDescription.ToString()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Return responseFromServer
End Function

Resources