RGoogleAnalytics Auth function wont open the browser for "Request for Permission" - r

I'm using the RGoogleAnalytics package in a remote Desktop (in a different country), i'm not using my local machine since Google blocks my local machine due to restrictions.
In my local machine, when i run the 'Auth' command:
token <- Auth(client.id = "XXXXXXXXXXXXXXXXXXXXXXX",
client.secret = "YYYYYYYYYYY")
the browser automatically opens a new tab ("Request for permission") in the browser for me to accept (natural part of authentication) - This is what should happen, though when i'm doing it through my remote machine (where i'm logged into the GA account, how it should work), My R console just gets stuck with the following command, without automatically opening a new request for permission tab in the browser:
token <- Auth(client.id = "XXXXXXXXXXXXXXXXXXXXXXX",
client.secret = "YYYYYYYYYYY")
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Has anyone ran into this issue at the past? I've actually used this package quit a lot and never ran into this weird issue
Thanks in advance for any help on this one :)

I solved this by launching a browser remotely :
ssh user#server -Y firefox
...and launching Rstudio as if it was on localhost.
Just make sure you have a port for Google API authentication response (likely 1410) open for TCP

Related

Rgoogleads - Issue with Service Account

I am trying to migrate my RAdwords code to rgoogleads and keep bumping into the same authentication nightmare. Some context:
Use R in my local computer, but all deployments are in a remote server that runs shiny, RStudio and other goodies.
I have managed to successfully activate the service account. I am (almost) sure about it since I successfully connect to Google Ads with Python.
I tried the same code with local OAuth2.0 and it works fine. However when I try to do so with the ServiceAccount authentication I keep getting the same error. I am sure I am doing something wrong.
This is a sample of my code:
library(rgoogleads)
gads_auth(path='../serviceAccount.json')
gads_auth(email='my_email#company.com',
developer_token = '_my_dev_token_'
)
gads_set_login_customer_id('xxx-xxx-0524')
gads_get_accessible_customers()
And this is the response
<error/rlang_error>
Request had insufficient authentication scopes.
Backtrace:
1. rgoogleads::gads_get_accessible_customers()
2. gargle::response_process(ans, error_message = gads_check_errors2)
8. rgoogleads:::error_message(resp)
9. rgoogleads:::gads_abort(paste(client_id, msg))
10. cli::cli_abort(message = message, ..., .envir = .envir)
Even when I try gads_has_token() it returns TRUE (!)
Any clues? I can't seem to get my head around this.

Why would a callback URL not work (for a GroupMe bot)?

I am creating a GroupMe bot, and I'm testing out the callback URL and the basic WSGI app I've set up so far. I am planning host the bot on Heroku, but am testing it on my local machine first. I registered a bot, with the callback URL http://MY_IP_ADDRESS:8000. When I open a different shell and run requests.post('http://MY_IP_ADDRESS:8000', data = 'something') in the Python interpreter, everything works fine. However, when there is activity in the GroupMe group, nothing happens, not even an error message.
Here's my (simplified) code:
from wsgiref.simple_server import make_serve
def app(environ, startResponse):
try:
requestBodySize = int(environ.get('CONTENT_LENGTH', 0))
except ValueError:
requestBodySize = 0
# requestBody = environ['wsgi.input'].read(requestBodySize)
print('something')
responseBody = bytes('successful', 'utf-8')
status = '200 OK'
responseHeaders = [('Content-Type', 'text/plain'), ('Content-Length', str(len(responseBody)))]
startResponse(status, responseHeaders)
return [responseBody]
server = make_server('', 8000, app)
server.serve_forever()
I'm sure I'm doing something obvious, but I can't for the life of me figure out what. I'd appreciate any help!
I never figured out why the callback URL wasn't working with localhost, but when I deployed the app on Heroku, everything worked fine! It must have had something to do with my firewall settings.
When you run servers on your local machine your firewall doesn't really like that. GroupMe also cant send to anything but public facing addressees, which is why Heroku works. One thing I can recommend in the future is using Ngrok, https://ngrok.com/ this will work with your server to make a public facing address on your machine that you can use as callback url. I use Ngrok to test my bots and quickly iterate before pushing to a dedicated server like Heroku, honestly looking through Heroku log files is a pain...

Authorization for accessing BigQuery from R session on server

I am using R and package bigrquery to access Bigquery from an R session.
This works great as long as I am on my local machine.
However, when I try to access Bigquery from R on a remote server it does not work at all.
I tried to copy the .httr-oauth file into my home directory on the server but this does not work.
I get the error message:
Auto-refreshing stale OAuth token.
Error in refresh_oauth2.0(self$endpoint, self$app, self$credentials) :
client error: (400) Bad Request
I really have no idea about where to store the necessary credentials and unfortunately I was not able to find anything useful about that by google-searching the topic.
By default httr, which is used by bigrquery for oauth, will look in the R session's current working directory for .httr-oauth. You can override this location with the following (perhaps putting it in your .Rprofile if you like):
options("httr_oauth_cache"="~/.httr-oauth")
But for error message you received, its seems like the location is not the issue and it might be easier to just redo the oauth flow on the remote server to cache a new credential. To trigger a new oauth flow on the remote server:
ensure the .httr-oauth file does not exist
restart R
perform one query with bigrquery
Note that if httr tries to redirect to localhost, you can force it to do an out-of-band oauth flow with:
options(httr_oob_default = TRUE)

PushSharp GCM "Authentication Failed"

I have been using PushSharp for Apple notifications for some time in both a web service and a windows service without any issues.
On adding the code for Google GCM, it works perfectly fine on my web service and a console app I converted the service to, but it fails miserably in the windows service even when run on the same server (Amazon EC2 Instance)
The following code gives an "Authentication Failed" error for the GCM notification and has no error for the Apple notification. However, If I run the same code in my web service or a console app on the same server, it works fine.
Dim push As PushBroker = New PushBroker
Try
AddHandler push.OnNotificationSent, AddressOf NotificationSent
AddHandler push.OnNotificationFailed, AddressOf NotificationFailed
Dim appleCert = File.ReadAllBytes("FILENAME")
push.RegisterAppleService(New ApplePushChannelSettings(False, appleCert, "PASSWORD"))
push.RegisterGcmService(New GcmPushChannelSettings("API_KEY"))
push.QueueNotification(New GcmNotification().ForDeviceRegistrationId("ANDROID-TOKEN").WithJson("{""alert"":""Hello World!"",""badge"":1,""sound"":""sound.caf""}"))
push.QueueNotification(New AppleNotification().ForDeviceToken("IOS-TOKEN").WithContentAvailable(1))
Catch ex As Exception
End Try
If I remove the line:
push.QueueNotification(New GcmNotification().ForDeviceRegistrationId("ANDROID-TOKEN").WithJson("{""alert"":""Hello World!"",""badge"":1,""sound"":""sound.caf""}"))
it works perfectly on both the windows service and the web service.
Can anyone see what I am doing wrong? It is not a firewall issue. I turned off the firewall and it still didn't work. I had a lot of other code and have distilled it down to the above code to make sure there were no hidden issues.
EDIT. I set up a console app copying the code from the windows service and used the Browser API Key instead of the Server API key.
This works perfectly on both my local machine and the server machine. However the windows service still gets the same error whichever API key I use.
UPDATE: Although the Windows Service is receiving the error, it does actually send two notifications and then no more. If I stop the service and start it again, I get another two notifications even though the notification error is still being returned.
I'm really stuck. I can just continuously run the console app for now, but its hardly perfect. Any help would be gratefully received.
I had a similar issue - everything worked fine in Visual Studio but on the production server AndroidGcm authentication failed.
I figured it was something to do with the IP list in the 'Key for server applications' so I tried regenerating one with the IP address of my server. This didn't work.
Eventually in response to one of the above comments and another thread elsewhere I logged onto the Google Play Developer Console from the server and created a new key, without specifying any IP addresses.
Using this key then fixed my problem

Calling https process from ASP Net

I have an ASP NET web server application that calls another process running on the same box that creates a pdf file and returns it. The second process requires a secure connection via SSL.
The second process has issued my ASP NET application with a digital certificate but I still cannot authenticate, getting a 403 error.
The code is a little hard to show but here's a simplified method ...
X509Certificate cert = X509Certificate.CreateFromCertFile("path\to\cert.cer");
string URL = "https://urltoservice?params=value";
HttpWebRequest req = HttpWebRequest.Create(URL) as HttpWebRequest;
req.ClientCertificates.Add(cert);
req.Credentials = CredentialCache.DefaultCredentials;
req.PreAuthenticate = true;
/// error happens here
WebResponse resp = req.GetResponse();
Stream input = resp.GetResponseStream();
The error text is "The remote server returned an error: (403) Forbidden."
Any pointers are welcome.
Finally fixed (wasted 6 hours on this *&%$##&)
I needed to grant access to the private keys on the digi cert to the account that the calling ASP.NET application runs under. This account is NETWORK SERVICE by default although you may want to run under a more restricted account.
Access is granted with the winhttpcertcfg tool, here's what got it working for me:
winhttpcertcfg -g -s "cert name" -c "LOCAL_MACHINE\MY" -a "NETWORK SERVICE"
where "cert name" is the CN of the digi cert.
More info at http://support.microsoft.com/kb/901183
Thanks to all who helped out with pointers on how to get this working :)
A 403 sounds like an authorization problem, not an authentication problem. It might be caused by the NTFS security settings on the files and folders accessed by your PDF service. Maybe it doesn't have permission to create the PDF file in the output folder?
Can you install the client certificate into your browser, and then access your PDF service through the browser? When you do that, do you still get a 403 or does it work?
Can you temporarily configure the PDF service to allow unencrypted HTTP connections? Does that make the problem go away?
From Windows Explorer, can you grant the "Network Service" account full control over the physical folder corresponding to the root of the PDF service site? Also grant it full control over any other directories it accesses. You should lock things down later after you've figured things out.
Or you can change the application pool to run under a different account - e.g. your own account.
Finally: if you're running IIS 7, you can turn on failed request tracing, which should give you a lot more info about why it failed.

Resources