Google API v3 OAuth2 Service Account Token URL 404 Error - google-analytics-api

I'm getting a 404 error when attempting to post to this url:
https://www.googleapis.com/oauth2/v3/token
which is referenced in the Google Oauth documentaiton here:
https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatingjwt
Here's a snippet of code in case it helps:
Dim tokenRequestURL As String = "https://www.googleapis.com/oauth2/v3/token?grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9." & GetJWTclaimSet() & "." & GetJWTsignature()
Dim client As New WebClient()
Dim json = client.DownloadString(tokenRequestURL)
update copied from comment:
Dim tokenRequestURL As String "https://www.googleapis.com/oauth2/v3/token"
Dim client As New WebClient()
Dim params As New Specialized.NameValueCollection
params.Add("grant_type", "urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer")
params.Add("assertion", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9." & GetJWTclaimSet() & "." & GetJWTsignature())
Dim responsebytes = client.UploadValues(tokenRequestURL, "POST", params)

Related

How can I get a JWT Access Token using Docusign 4.0.4.0

I have a legacy application written in VB6 (I Know!!) to which I am adding a DocuSign feature. I a using InterOp to run .NET code written is VS2019 VB.Net. The reason I am using 4.0.4.0 as this is the version I can successfully call using InterOp. I have all the code working except for requesting a JWT token. Does anyone have JWT code working under this version of the API ?
This is what I have working under later versions of DocuSign and am trying to replace
`Dim privatekey As Byte() = File.ReadAllBytes("docusign_private_key.key")
Dim result As Object = x.RequestJWTApplicationToken(gsSIGNERCLIENTID, docuSignAuthServer, privatekey, 1, scopes)
txtAccessToken.Text = result
'
' Second attempt at alternative
'
` Dim authToken As OAuth.OAuthToken = x.RequestJWTUserToken(gsSIGNERCLIENTID, gsUserIDGUID, docuSignAuthServer, privatekey, 1)
txtAccessToken.Text = authToken.access_token`
'
' Third attempt
'
Dim request = TryCast(System.Net.WebRequest.Create("https://account-d.docusign.com/oauth/token"), System.Net.HttpWebRequest)
request.Method = "POST"
request.Headers.Add("username", "user123")
request.Headers.Add("password", "123")
request.Headers.Add("auth_access_type", "read")
request.ContentLength = 0
Dim responseContent As String = ""
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
Using reader = New System.IO.StreamReader(response.GetResponseStream())
responseContent = reader.ReadToEnd()
End Using
End Using
'
' Fifth attempt
'
Dim apiClient5 As New ApiClient(gsBASEPATH)
Dim authToken5 As OAuth.OAuthToken = apiClient5.RequestJWTUserToken(gsINTEGRATIONKEY, gsUserIDGUID, "https://account-d.docusign.com/oauth/token", privatekey, 1, scopes)
All results in 'Error while requesting server, received a non-successful HTPC code Error with response Body'
Your second attempt is correct:
Dim authToken As OAuth.OAuthToken = x.RequestJWTUserToken(gsSIGNERCLIENTID, gsUserIDGUID, docuSignAuthServer, privatekey, 1)
txtAccessToken.Text = authToken.access_token
AuthServer has to be "account-d.docusign.com"
The privateKey has to be the exact thing you got from DocuSign, including the new lines and all. To get it use this code:
File.ReadAllBytes(path) where path is the path on the disk to a plain text file with your private key.
gsSIGNERCLIENTID should be the GUID for the user that you use that has consent. You must make sure user gave consent by building a consent URL as explained in here:
https://developers.docusign.com/platform/auth/consent/obtaining-individual-consent/
If you did all of this correctly - it should work.

Paypal Sandbox PDT FAIL Error: 4020

Dim authToken, txToken
Dim query
Dim objHttp
Dim sQuerystring
Dim sParts(), iParts(), aParts
Dim sResults(0, 0), sKey, sValue
Dim i, result
Dim firstName, lastName, itemName, mcGross, mcCurrency
authToken = "%Token From SandBox%"
txToken = Request.QueryString("tx")
query = "cmd=_notify-synch&tx=" & txToken & "&at=" & authToken
set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
objHttp.open "POST", "https://www.sandbox.paypal.com/cgi-bin/webscr", False
objHttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHttp.Send query
sQuerystring = objHttp.responseText
I am getting Error "FAIL Error: 4020". Please guide me what I am missing.
It could be because:
LIVE account PDT token is used instead of Sandbox.
Incorrect token(check for white spaces,spelling)
If you still face issues, you can submit a ticket to MTS

Twitter oAuth 1.1 vb.net (401) unauthorized when posting tweet

I have spent some time on this and cannot figure out why I cannot post to twitter from my web site. I keep getting 401 unauthorized. I think that I was successfully posting to the 1.1 auth at one point but something changed in the last 6 weeks or so (not in my code, did oauth get stricter?).
Does anyone see anything that could be potentially causing the problem? Is there anything I can add to the code to get more info on why it's failing?
Private Function NewTweet(status As String) As WebResponse
Try
Dim oauth_token = "token" 'access token
Dim oauth_token_secret = "secret" 'acces token secret
Dim oauth_consumer_key = "key" 'consumer key
Dim oauth_consumer_secret = "secret" 'consumer secret
Dim oauth_version As String = "1.0"
Dim oauth_signature_method As String = "HMAC-SHA1"
Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture)))
Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauth_timestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString(CultureInfo.InvariantCulture)
Dim resource_url As String = "https://api.twitter.com/1.1/statuses/update.json"
Dim baseFormat As String = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}"
Dim baseString As String = 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 As String = 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_consumer_key=""{0}"", " & _
"oauth_nonce=""{1}"", " & _
"oauth_signature=""{2}"", " & _
"oauth_signature_method=""{3}"", " & _
"oauth_timestamp=""{4}"", " & _
"oauth_token=""{5}"", " & _
"oauth_version=""{6}"""
Dim authHeader = String.Format(headerFormat, _
Uri.EscapeDataString(oauth_consumer_key), _
Uri.EscapeDataString(oauth_nonce), _
Uri.EscapeDataString(oauth_signature), _
Uri.EscapeDataString(oauth_signature_method), _
Uri.EscapeDataString(oauth_timestamp), _
Uri.EscapeDataString(oauth_token), _
Uri.EscapeDataString(oauth_version))
'-------------------------------------------------------
Dim postBody As String = "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;charset=UTF-8"
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
Catch ex As Exception
Return Nothing
End Try
End Function

InvalidTokenException was unhandled by user code - "Unauthorized"

This is my code:
string accessToken = "##";
string accessTokenSecret = "##";
string consumerKey = "##";
string consumerSecret = "##";
string appToken = "##";
string realmId = "##"; //company id in quickbooks online
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
ServiceContext context = new ServiceContext(oauthValidator, appToken, realmId, IntuitServicesType.QBO);
I am receiving: InvalidTokenException was unhandled by user code - {"Unauthorized"}
in the creating the new ServiceContext line. Not sure what the problem is.
Thanks for any help provided.
This error message:
InvalidTokenException was unhandled by user code - {"Unauthorized"}
Occurs when the OAuth tokens you're using are no longer valid.
I would double-check that:
You're using a valid set of OAuth tokens that you got from Intuit
The tokens are not expired (the Developer Playground tokens are very
short lived, longer-lived 6-month tokens are available if you set up
your own actual OAuth endpoint)
Here is Intuit's documentation for setting up your own OAuth endpoint:
http://docs.developer.intuit.com/0025_Intuit_Anywhere/0010_Getting_Started/0020_Connect/0010_From_Within_Your_App/Implement_OAuth_in_Your_App

How do I include scripting (classic ASP pages, vbscript, etc.) to TcpListener and Socket Web Server Console Application?

Forgive me, as I am new to this. I found some code online that I'm using in a console application that can set up a local web server, and serve HTML pages locally. I will post the code - but I need to be able to serve ASP pages and pages with vbscripting. Is it possible with this code below, and if so, what can I add to do so? Since this code is so simple, I'm really hoping to modify it to add ASP/Vbscript, and continue on. Thanks in advance!!
Public ip As String = "127.0.0.1"
Public port As String = "80"
Public rootpath As String = "C:\wwwroot\"
Public defaultpage As String = "default.asp"
Public Sub Main()
Try
Dim hostName As String = Dns.GetHostName()
Dim serverIP As IPAddress = IPAddress.Parse(ip)
Dim tcpListener As New TcpListener(serverIP, Int32.Parse(port))
tcpListener.Start()
Console.WriteLine("Web server started at: " & serverIP.ToString() & ":" & Port)
Dim httpSession As New HTTPSession(tcpListener)
Dim serverThread As New Thread(New ThreadStart(AddressOf httpSession.ProcessThread))
serverThread.Start()
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
End Try
End Sub
Public Class HTTPSession
Private tcpListener As System.Net.Sockets.TcpListener
Private clientSocket As System.Net.Sockets.Socket
Public Sub New(ByVal tcpListener As System.Net.Sockets.TcpListener)
Me.tcpListener = tcpListener
End Sub
Public Sub ProcessThread()
While (True)
Try
clientSocket = tcpListener.AcceptSocket()
' Socket Information
Dim clientInfo As IPEndPoint = CType(clientSocket.RemoteEndPoint, IPEndPoint)
Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString())
' Set Thread for each Web Browser Connection
Dim clientThread As New Thread(New ThreadStart(AddressOf ProcessRequest))
clientThread.Start()
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
If clientSocket.Connected Then
clientSocket.Close()
End If
End Try
End While
End Sub
Protected Sub ProcessRequest()
Dim recvBytes(1024) As Byte
Dim htmlReq As String = Nothing
Dim bytes As Int32
Try
' Receive HTTP Request from Web Browser
bytes = clientSocket.Receive(recvBytes, 0, clientSocket.Available, SocketFlags.None)
htmlReq = Encoding.ASCII.GetString(recvBytes, 0, bytes)
Console.WriteLine("HTTP Request: ")
Console.WriteLine(htmlReq)
Dim strArray() As String
Dim strRequest As String
strArray = htmlReq.Trim.Split(" ")
' Determine the HTTP method (GET only)
If strArray(0).Trim().ToUpper.Equals("GET") Then
strRequest = strArray(1).Trim
If (strRequest.StartsWith("/")) Then
strRequest = strRequest.Substring(1)
End If
If (strRequest.EndsWith("/") Or strRequest.Equals("")) Then
strRequest = strRequest & defaultPage
End If
strRequest = rootPath & strRequest
sendHTMLResponse(strRequest)
Else ' Not HTTP GET method
strRequest = rootPath & "Error\" & "400.html"
sendHTMLResponse(strRequest)
End If
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
If clientSocket.Connected Then
clientSocket.Close()
End If
End Try
End Sub
' Send HTTP Response
Private Sub sendHTMLResponse(ByVal httpRequest As String)
Try
' Get the file content of HTTP Request
Dim streamReader As StreamReader = New StreamReader(httpRequest)
Dim strBuff As String = streamReader.ReadToEnd()
streamReader.Close()
streamReader = Nothing
' The content Length of HTTP Request
Dim respByte() As Byte = Encoding.UTF8.GetBytes(strBuff)
'Dim respByte() As Byte = Encoding.ASCII.GetBytes(strBuff)
' Set HTML Header
Dim htmlHeader As String = _
"HTTP/1.0 200 OK" & ControlChars.CrLf & _
"Server: WebServer 1.0" & ControlChars.CrLf & _
"Content-Length: " & respByte.Length & ControlChars.CrLf & _
"Content-Type: " & getContentType(httpRequest) & _
ControlChars.CrLf & ControlChars.CrLf
' The content Length of HTML Header
'Dim headerByte() As Byte = Encoding.ASCII.GetBytes(htmlHeader)
Dim headerByte() As Byte = Encoding.UTF8.GetBytes(htmlHeader)
Console.WriteLine("HTML Header: " & ControlChars.CrLf & htmlHeader)
' Send HTML Header back to Web Browser
clientSocket.Send(headerByte, 0, headerByte.Length, SocketFlags.None)
' Send HTML Content back to Web Browser
clientSocket.Send(respByte, 0, respByte.Length, SocketFlags.None)
' Close HTTP Socket connection
clientSocket.Shutdown(SocketShutdown.Both)
clientSocket.Close()
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
If clientSocket.Connected Then
clientSocket.Close()
End If
End Try
End Sub
' Get Content Type
Private Function getContentType(ByVal httpRequest As String) As String
If (httpRequest.EndsWith("html")) Then
Return "text/html"
ElseIf (httpRequest.EndsWith("asp")) Then
Return "text/html"
ElseIf (httpRequest.EndsWith("htm")) Then
Return "text/html"
ElseIf (httpRequest.EndsWith("txt")) Then
Return "text/plain"
ElseIf (httpRequest.EndsWith("gif")) Then
Return "image/gif"
ElseIf (httpRequest.EndsWith("jpg")) Then
Return "image/jpeg"
ElseIf (httpRequest.EndsWith("jpeg")) Then
Return "image/jpeg"
ElseIf (httpRequest.EndsWith("pdf")) Then
Return "application/pdf"
ElseIf (httpRequest.EndsWith("pdf")) Then
Return "application/pdf"
ElseIf (httpRequest.EndsWith("doc")) Then
Return "application/msword"
ElseIf (httpRequest.EndsWith("xls")) Then
Return "application/vnd.ms-excel"
ElseIf (httpRequest.EndsWith("ppt")) Then
Return "application/vnd.ms-powerpoint"
Else
Return "text/plain"
End If
End Function
End Class
I think you have two choices.
Stop doing that because its certain to be world of pain and cost.
However if you are determined to try and make it happen then take a look at the ASP Classic Compiler codeplex project.