<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/a-tale-of-two-shiny-apps-google-auth-shinyproxy/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://rtask.thinkr.fr/blog/a-tale-of-two-shiny-apps-google-auth-shinyproxy/"> (en) The R Task Force</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<blockquote>
<p><em>Once upon a time, there was a team of <a rel="nofollow" href="https://thinkr.fr/expert-logiciel-r/" target="_blank">fearless R knights</a> who started a new quest: they were missioned to bring the almighty Google Auth into the wonderful world of ShinyProxy. Here is their story, told from the inside.</em></p>
</blockquote>
<p> </p>
<h2>In the beginning, there was a container</h2>
<p>For those amongst our readers who do not know ShinyProxy, this <a rel="nofollow" href="https://www.shinyproxy.io/" target="_blank">open source project</a> by Open Analytics is designed to <strong>deploy a server which can run multiple Shiny Apps</strong>, and where each new shiny app is launched in a new session. In a few words, what ShinyProxy does is basically connecting a server to a list of Docker containers, and <strong>when a new user connects to the service and wants to open an app</strong>, a new container is run.</p>
<p>This process of “one user one container” allows to bypass the issue of R being single-threaded: on a classical Shiny App, if several users connect at the same time, the same R session is used. And if one launches a process that takes 15 seconds, the app is frozen for the rest of the users who need to wait for this process to be finished. You can find a nice example of this in <a rel="nofollow" href="https://www.rstudio.com/resources/videos/scaling-shiny-apps-with-async-programming/" target="_blank">Joe Chen – Scaling Shiny apps with async programming</a>, which presents another way to handle this issue: async programming with the <code>{promises}</code> <img alt="📦" src="https://i2.wp.com/s.w.org/images/core/emoji/11/72x72/1f4e6.png?w=456&ssl=1" class="wp-smiley" data-recalc-dims="1">.</p>
<p>I can hear your question: why would we need to deploy a Google Auth app with Shiny Proxy? There might not be that much computation in a dashboard context, and even if, we could still add more RAM. Well, no. <strong>If we deploy only one app</strong>, <strong>every user will have the same R session</strong>, meaning that once the first user is logged in, every new user coming to this app will be logged to the same Google Account.</p>
<p>Nothing that much complicated so far: <strong>once our Shiny App is developped, we just need to build a Docker image that runs it, copy it to the server, and let ShinyProxy do the rest</strong> (well, after a little bit of configuration, of course…).</p>
<h2>The first subquest: run Google Auth in Docker</h2>
<blockquote>
<p><em>Our story begins with a simple Shiny App.</em></p>
</blockquote>
<h3>A story of non interactive session</h3>
<p>Let’s draw a picture: we’ve got a Shiny App that connects to Google Analytics and builds a report. Here is a quick app, just for the example:</p>
<pre><code>library(shiny)
library(googleAnalyticsR)
ui &lt;- fluidPage(
  tagList(
    # hide the button after connection
    tags$script('Shiny.addCustomMessageHandler(&quot;hideButton&quot;, function(id) { $(id).hide(); });'),
    actionButton(&quot;connect&quot;, &quot;Retrieve data&quot;), 
    verbatimTextOutput(&quot;list&quot;)
  )
)
server &lt;- function(input, output, session) {
  observeEvent(input$connect, {
    account_list &lt;- ga_account_list()
    output$list &lt;- renderPrint({ account_list })
    # Hide the connection button once the connection is done
    session$sendCustomMessage(type = &quot;hideButton&quot;, &quot;#connect&quot;)
  })
}
shinyApp(ui, server)</code></pre>
<p>Now we’d like to bundle this in a Docker. Because, remember, we need to put containers on our server, so that it works with ShinyProxy. But here is what happens when we try to launch our container:</p>
<pre><code>Error in : Authentication options didn’t match existing session token and not interactive session
so unable to manually reauthenticate</code></pre>
<p>Yes, by default, the “Google-related packages suite” by <a rel="nofollow" href="https://github.com/MarkEdmondson1234" target="_blank">Mark Edmondson</a> <strong>does not allow to connect in a non-interactive session</strong>. Let’s digress on that for a minute.</p>
<h3>The manuscript of API connection</h3>
<p>When you create an app on an API backend (that being Twitter, Facebook, or in our case the Google Developer Console), you <strong>get identification parameters</strong> (usually called a client id and a client secret). On this same app you need to<strong> define a <em>callback URL</em>, which is the URL the users go to once the authentification is done</strong>, and that will contain the access token. These elements are passed from one point to the other through <em>URL parameters</em>, which are the strange elements you sometimes see after the <code>?</code> in your url.</p>
<p>In other words, if you own a site called A.com and want to establish a connection to an API on B.com, you’ll have to<strong> pass the connection info</strong> with <code>B.com?bla=pouet&amp;plop=12</code>, B.com here being the endpoint of the API. When you open B.com with these params, B.com parses this URL, creates an access token <code>blablabla</code>, and opens the <strong><em>callback URL</em> with the access token as a parameter</strong> (in our case, it opens <code>A.com?blablabla</code>). Once we are back on A, the URL is parsed and we have in A our access token to B.</p>
<p>When trying to connect to <code>B.com</code> from R, here is what happens (at least with <code>{httr}</code>):</p>
<ul>
<li>You <strong>give R your client id and secret</strong></li>
<li>R <strong>opens and listens</strong> to <code>http://127.0.0.1:1410</code></li>
<li>R opens a browser to <code>B.com?id=this&amp;secret=that</code></li>
<li>The website <code>B.com</code> <strong>parses the URL</strong>, does its magic, and opens the <em>callback URL</em> with the token as a parameter</li>
<li>As you have defined on <code>B.com</code> this callback to be <code>http://127.0.0.1:1410</code>, <code>B.com</code> opens <code>http://127.0.0.1:1410?mytokenhere</code></li>
<li>As <strong>R is listening on this 1410 port</strong>, it receives the URL with parameters, parses these params, does a <a rel="nofollow" href="https://www.youtube.com/watch?v=0p_1QSUsbsM" target="_blank">little bit of magic</a>, brings back the token into the user environment, and creates a little file called <code>.httr-oauth</code> with everything in it.</li>
</ul>
<p>Aaaand here’s the catch: <strong>when on a non-interactive session, R can’t open a browser nor a specific port in the host</strong>.</p>
<p>So, that explains the error we got just before: non-interactive R can’t open a web browser, and no <code>.httr-oauth</code> is found. One solution would be to create this file when in an interactive session, and copy it to the Docker image. But that means you could only get access to the google account you have previously connected. Not very scalable, as we want any user to be able to use our app.</p>
<p>(FYI, this, unfortunately, also happens with RMarkdown: when you knit your document, a new, non-interactive session is opened.)</p>
<h2>Saved by <code>{googleAuthR}</code></h2>
<p>So, how can we bypass this? Maybe use JavaScript solution? That’s what Mark developed in his package: <code>{googleAuthR}</code> contains a module called <code>gar_auth_js</code>and <code>gar_auth_jsUI</code>, which allows creating a button connecting to Google through JavaScript. On tadaa <img alt="🎉" src="https://i1.wp.com/s.w.org/images/core/emoji/11/72x72/1f389.png?w=456&ssl=1" class="wp-smiley" data-recalc-dims="1">, this works.</p>
<blockquote>
<p><em>Problem solved? Our heroes thought so, as they succeeded to deploy their application in a Docker. But their joy was short, because then came a feared but expected event: deployment with ShinyProxy.</em></p>
</blockquote>
<h2>Fighting the ShinyProxy dragon</h2>
<p>Here we are: authorizing our server IP on the Google Console, setting the callback, and making our app work by launching a Docker. Because yes, Google Console asks for two things when it comes to authorization: the URL to come FROM to use OAuth, and an URL to go TO once the connection is done.</p>
<h3>Launching our app into the wild</h3>
<p>So now, we were ready to start what we fought was gonna be our last battle: configuring ShinyProxy, and launching the apps. And here we stopped, bewildered: <strong>our app could not connect to Google Auth. No authorization. Error 400</strong>. With our only help being a friendly robot that muttered weird incantations:</p>
<p><img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i1.wp.com/rtask.thinkr.fr/wp-content/uploads/error_robot-1024x554.jpg?w=450&ssl=1" alt="" class="wp-image-671" data-recalc-dims="1"></p>
<p> </p>
<p>We endeavor to decipher the words this magic robot was telling us. And there it was: the issue. “The redirect URI in the request <code>.../endpoint/0ea5...</code> does not match the one authorized for the OAuth client”. Because yes, hidden from view, ShinyProxy creates an endpoint, appended to the end of your app URL for each instance of the app (which is not shown to the user):</p>
<p><img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i0.wp.com/rtask.thinkr.fr/wp-content/uploads/urlbar-1024x30.png?w=450&ssl=1" alt="" class="wp-image-672" data-recalc-dims="1"></p>
<p>So, that’s simple, can we just simply put this full URL as an authorized URL in the Google Console? Yes, we can. And it works.</p>
<blockquote>
<p><em>But as you might have guessed, this victory was not a victory, and this adventure is not over yet.</em></p>
</blockquote>
<h3>A chapter on random endpoints</h3>
<p>Here’s the new issue: ShinyProxy creates… <strong>random endpoints</strong> where it serves the app(s). That means that we can’t anticipate upfront the id of these endpoints. And, of course, <strong>the google console does not allow wildcards</strong> (that means you can’t put <code>url/app/endpoint/*</code> to specify that you want any URL that would match this expression).</p>
<p>We seemed to have come to a dead end: <strong>no wildcards on the Google Console, no way to predict endpoints ids</strong> (and even if, would we really want to copy and paste hundreds of ids?).</p>
<p>One idea came to our mind: <strong>what if we could access the Console through Command Line?</strong> If we could, we would simply have to get the id of the endpoint with JavaScript (it’s hidden at the top of the page), send it to R, authorize it to the Google Console programmatically, and then everything would be ok, and we could live happily ever after.</p>
<p><img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i1.wp.com/rtask.thinkr.fr/wp-content/uploads/html_endpoint-1024x507.png?w=450&ssl=1" alt="" class="wp-image-680" data-recalc-dims="1"></p>
<p>Though, the command line connection to Google Console was nowhere to be found. We screamed for help:</p>
<ul>
<li><a rel="nofollow" href="https://stackoverflow.com/questions/52226508/google-developper-console-changing-authorized-uri-from-command-line" target="_blank">https://stackoverflow.com/questions/52226508/google-developper-console-changing-authorized-uri-from-command-line</a></li>
<li><a rel="nofollow" href="https://support.openanalytics.eu/t/shiny-proxy-google-oauth/724" target="_blank">https://support.openanalytics.eu/t/shiny-proxy-google-oauth/724</a></li>
<li><a rel="nofollow" href="https://twitter.com/_ColinFay/status/1038328941055041536" target="_blank">https://twitter.com/_ColinFay/status/1038328941055041536</a></li>
</ul>
<p>But the internet was not willing to answer our desperate call, and (thanks Mark for your answer!) Twitter pointed out that this might not be possible to access the Google Console through command line.</p>
<h2>A happy ending</h2>
<blockquote>
<p><em>At this point of our story, our heroes might seem lost, without any chance of fulfilling their quest. But, in an unexpected turn of event, one of our brave khnight had an idea…</em></p>
</blockquote>
<h3> Dissecting <code>{googleAuthR}</code></h3>
<p>I couldn’t go along with “This is not possible”, and needed to find a way to solve this puzzle. And here comes a revelation: nowhere was it written that we should use only one shiny app to do this. We need two.</p>
<p>Let me explain: <strong>we use ShinyProxy because we want to control the connection, but also because we want each user to have its own R </strong>session,<strong> so that it’s easier to handle resources and auth</strong>. But Google Auth does not demand that much resources. So, aside these consuming Shiny Apps sent to a random endpoint of our server, we can have <strong>another Shiny app that just handles the connection</strong>. This shiny app is at a stable IP, so we can easily authorize it.</p>
<p>That, in theory, works. Well, if you can, of course, bring the token back from the Connection App to the main app. And make it easy for the user, with a friendly UI.</p>
<p>So here I was, dissecting the <code>{googleAuthR}</code> functions, just to identify one thing: <strong>what is the absolute minimum information R needs to create a token</strong>? And the answer is simple: a character vector defining the state of the connection, which is sent back to the callback URL as a parameter. So, if I get that, I can create a connexion (of course, you need to dig into <code>{googleAuthR}</code> internals and recode some elements to allow that). This is what our connection app will give to the user, who will only have to copy and paste this character vector into the main application.</p>
<p>And, to make it more user-friendly, let’s implement two little things</p>
<ul>
<li>The connection application does not open in a new tab/windows, but in a pop-up, which makes it a little bit more natural to the user, as it seems like you’re not opening a new app. As you can see here, I’m on two different ports of the server. Yet I can bet that 99% of the users won’t notice that.</li>
</ul>
<p><img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i1.wp.com/rtask.thinkr.fr/wp-content/uploads/pop_up_app-1024x645.png?w=450&ssl=1" alt="" class="wp-image-676" data-recalc-dims="1"></p>
<ul>
<li>Create a button to copy the token (just a little bit of JavaScript and it’s done)</li>
</ul>
<p><img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i2.wp.com/rtask.thinkr.fr/wp-content/uploads/javascript-copy-paste-1-1024x812.png?w=450&ssl=1" alt="" class="wp-image-679" data-recalc-dims="1"></p>
<p>I have to admit it’s not optimal (well, compared to the interactive authentification), but IT WORKS, and at the end of the day doesn’t feel that unnatural or complex from a user point of view: click, click, click, click, paste, click, and we’re done.</p>
<h2>It has been a good fight</h2>
<blockquote>
<p><em>Now that our heroes left for other exciting adventures, we hope their story would help you to conquer the almighty quest of bringing Google Auth to ShinyProxy. The moral of the story? Once faced with what seems like an unfulfillable quest, take a step back, get out of your shiny app, and maybe you just need to code another app.</em></p>
</blockquote>
<p> </p>
<p>The post <a rel="nofollow" href="https://rtask.thinkr.fr/blog/a-tale-of-two-shiny-apps-google-auth-shinyproxy/" target="_blank">A Tale of Two Shiny Apps: Google Auth &amp; ShinyProxy</a> appeared first on <a rel="nofollow" href="https://rtask.thinkr.fr/" target="_blank">(en) The R Task Force</a>.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://rtask.thinkr.fr/blog/a-tale-of-two-shiny-apps-google-auth-shinyproxy/"> (en) The R Task Force</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/vEbkqXtSMNA" height="1"></a></div>