• Stars
    star
    137
  • Rank 266,121 (Top 6 %)
  • Language
    R
  • License
    Other
  • Created about 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Authentication in shinyapps using Auth0 service

auth0

CRAN_Status_Badge Lifecycle: stable R-CMD-check

The goal of {auth0} is to implement an authentication scheme to Shiny using OAuth Apps through the freemium service Auth0.

Installation

You can install {auth0} from CRAN with:

install.packages("auth0")

You can also install the development version from github with:

# install.packages("devtools")
remotes::install_github("curso-r/auth0")

Tutorial

To create your authenticated shiny app, you need to follow the five steps below.

Step 1: Create an Auth0 account

  • Go to auth0.com
  • Click “Sign Up”
  • You can create an account with a user name and password combination, or by signing up with your GitHub or Google accounts.

Step 2: Create an Auth0 application

After logging into Auth0, you will see a page like this:

  • Click on “+ Create Application”
  • Give a name to your app
  • Select “Regular Web Applications” and click “Create”

Step 3: Configure your application

  • Go to the Settings in your selected application. You should see a page like this:

  • Add http://localhost:8080 to the “Allowed Callback URLs”, “Allowed Web Origins” and “Allowed Logout URLs”.
    • You can change http://localhost:8080 to another port.
  • Add the remote server where you are going to deploy your shiny app to the same boxes.
    • Just make sure that these addresses are correct. If you are placing your app inside a folder (e.g. https://johndoe.shinyapps.io/fooBar), don’t include the folder (fooBar) in “Allowed Web Origins”.
  • Click “Save”

Now let’s go to R!

Step 4: Create your shiny app and fill the _auth0.yml file

  • Create a configuration file for your shiny app by calling auth0::use_auth0():
auth0::use_auth0()
  • You can set the directory where this file will be created using the path= parameter. See ?auth0::use_auth0 for details.
  • Your _auth0.yml file should be like this:
name: myApp
remote_url: ''
auth0_config:
  api_url: !expr paste0('https://', Sys.getenv("AUTH0_USER"), '.auth0.com')
  credentials:
    key: !expr Sys.getenv("AUTH0_KEY")
    secret: !expr Sys.getenv("AUTH0_SECRET")
  • Run usethis::edit_r_environ() and add these three environment variables:
AUTH0_USER=johndoe
AUTH0_KEY=5wugt0W...
AUTH0_SECRET=rcaJ0p8...

There’s how you identify each of them (see the image below):

  • AUTH0_USER is your username, which can be found on the top corner of the site.
  • AUTH0_KEY is your Client ID, which can be copied from inside the app page.
  • AUTH0_SECRET is your Client Secret, which can be copied from the app page.

More about environment variables here. You can also fill these information directly in the _auth0.yml file (see below). If you do so, don’t forget to save the _auth0.yml file after editing it.

  • Save and restart your session.
  • Write a simple shiny app in a app.R file, like this:
library(shiny)

ui <- fluidPage(
  fluidRow(plotOutput("plot"))
)
  
server <- function(input, output, session) {
  output$plot <- renderPlot({
    plot(1:10)
  })
}

# note that here we're using a different version of shinyApp!
auth0::shinyAppAuth0(ui, server)

Note: If you want to use a different path to the auth0 configuration file, you can either pass it to shinyAppAuth0() or set the auth0_config_file option by running options(auth0_config_file = "path/to/file").

Step 5: Run!

You can try your app running

options(shiny.port = 8080)
shiny::runApp("app/directory/")

If everything is OK, you should be forwarded to a login page and, after logging in or signing up, you’ll be redirected to your app.

If you are running your app in a remote server like shinyapps.io or your own server, and if your app is in a subfolder of the host (like https://johndoe.shinyapps.io/fooBar), you must include your remote URL in the remote_url parameter in the _auth0.yml file.

You can also force {auth0} to use the local URL setting options(auth0_local = TRUE). This can useful if you’re running an app inside a Docker container.


Environment variables and multiple Auth0 apps

If you are using {auth0} for just one shiny app or you are running many apps for the same user database, the recommended workflow is using the environment variables AUTH0_KEY and AUTH0_SECRET.

However, if you are running many shiny apps and want to use different login settings, you must create many Auth0 apps. Hence, you’ll have many Cliend IDs and Client Secrets to use. n this case, global environment variables will be unproductive because you’ll need to change them every time you change the app you are developing.

There are two options in this case:

  • (Recommended) Add environment variables inside the repository of your application, using usethis::edit_r_environ("project").
  • (Not recommended) Add the Client ID and Secret directly in the _auth0.yml file:

The best option in this case is to simply add the Client ID and Secret directly in the _auth0.yml file:

name: myApp
remote_url: ''
auth0_config:
  api_url: https://<USERNAME>.auth0.com
  credentials:
    key: <CLIENT_ID>
    secret: <CLIENT_SECRET>

Example:

name: myApp
remote_url: ''
auth0_config:
  api_url: https://johndoe.auth0.com
  credentials:
    key: cetQp0e7bdTNGrkrHpuF8gObMVl8vu
    secret: C6GHFa22mfliojqPyKP_5K0ml4TituWrOhYvLdTa7veIyEU3Q10R_-If-7Sh6Tc

Although possible, the latter option is less secure and consequently not recommended because it’s easy to forget passwords there and commit them in public repositories, for example.


ui.R/server.R

To make {auth0} work using an ui.R/server.R framework, you’ll need to wrap your ui object/function with auth0_ui() and your server function with auth0_server(). Here’s a small working example:

ui.R

library(shiny)
library(auth0)

auth0_ui(fluidPage(logoutButton()))

server.R

library(auth0)

auth0_server(function(input, output, session) {})

{auth0} will try to find the _auth0.yml using the same strategy than the app.R framework: first from options(auth0_config_file = "path/to/file") and then fixing "./_auth0.yml". Both auth0_ui() and auth0_server() have a info= parameter where you can pass either the path of the _auth0.yml file or the object returned by auth0_info() function.


Audience parameter

To authorize a client to make API calls against a remote server, the authorization request should include an audience parameter (Auth0 documentation).

To do this with {auth0}, add an audience parameter to the auth0_config section of your _auth0.yml file. For example:

name: myApp
remote_url: ''
auth0_config:
  api_url: !expr paste0('https://', Sys.getenv("AUTH0_USER"), '.auth0.com')
  audience: https://example.com/api
  credentials:
    key: !expr Sys.getenv("AUTH0_KEY")
    secret: !expr Sys.getenv("AUTH0_SECRET")

When an audience parameter is included in the request, the access token returned by Auth0 will be a JWT access token rather than an opaque access token. The client must include the access token with API requests to authenticate the requests.


RStudio limitations

Because RStudio is specialized in standard shiny apps, some features do not work as expected when using {auth0}. The main issues are is that you must run the app in a real browser, like Chrome or Firefox. If you use the RStudio Viewer or run the app in a RStudio window, the app will show a blank page and won’t work.

If you’re using a version lower than 1.2 in RStudio, the “Run App” button may not appear in the right corner of the app.R script. That’s because RStudio searches for the “shinyApp(” term in the code to identify a shiny app.


Bookmarking

Since v0.2.0, auth0 supports shiny’s state bookmarking, but because of URL parsing issues, bookmarking only works with server storage. To activate this feature, you must call the app with the following lines in your app.R file:

enableBookmarking(store = "server")
shinyAppAuth0(ui, server)

Also note that Auth0 adds code and state to the URL query parameters.

This solution works normally in the ui.R/server.R framework.


Managing users

You can manage user access from the Users panel in Auth0. To create a user, click on “+ Create users”.

You can also use many different OAuth providers like Google, Facebook, Github etc. To configure them, go to the Connections tab.

In the near future, our plan is to implement Auth0’s API in R so that you can manage your app using R.


Logged information

After a user logs in, it’s possible to access the current user’s information using the session$userData$auth0_info reactive object. The Auth0 token can be accessed using session$userData$auth0_credentials. Here is a small example:

library(shiny)
library(auth0)

# simple UI with user info
ui <- fluidPage(
  verbatimTextOutput("user_info")
  verbatimTextOutput("credential_info")
)

server <- function(input, output, session) {

  # print user info
  output$user_info <- renderPrint({
    session$userData$auth0_info
  })
  
  output$credential_info <- renderPrint({
    session$userData$auth0_credentials
  })

}

shinyAppAuth0(ui, server)

You should see objects containing the user and credential info.

User info

$sub
[1] "auth0|5c06a3aa119c392e85234f"

$nickname
[1] "jtrecenti"

$name
[1] "[email protected]"

$picture
[1] "https://s.gravatar.com/avatar/1f344274fc21315479d2f2147b9d8614?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fjt.png"

$updated_at
[1] "2019-02-13T10:33:06.141Z"

Note that the sub field is unique and can be used for many purposes, like creating customized apps for different users.

Credential info (abridged)

$access_token
[1] "y5Yv..."

$id_token
[1] "eyJ0..."

$scope
[1] "openid profile"

$expires_in
[1] 86400

$token_type
[1] "Bearer"

The id_token may be used with applications that require an Authorization header with each web request.

Logged information and ui.R/server.R

If you’re running {auth0} using ui.R/server.R framework and you want to access logged information, you’ll need to use the same object returned auth0_info() function in both auth0_ui() and auth0_server().

This is possible using the global.R file. For example:

global.R

a0_info <- auth0::auth0_info()

ui.R

library(shiny)
library(auth0)

auth0_ui(fluidPage(), info = a0_info)

server.R

library(auth0)

auth0_server(function(input, output, session) {

  observe({ 
    print(session$userData$auth0_info) 
  })
  
}, info = a0_info)

Logout

You can add a logout button to your app using logoutButton().

library(shiny)
library(auth0)

# simple UI with logout button
ui <- fluidPage(logoutButton())
server <- function(input, output, session) {}
shinyAppAuth0(ui, server)

Costs

Auth0 is a freemium service. The free account lets you have up to 7000 connections in one month and two types of social connections. You can check all the plans here.

Disclaimer

This package is not provided nor endorsed by Auth0 Inc. Use it at your own risk.

Also, I am NOT a security expert, and as Bob Rudis pointed out, adding the word “secure” on something has broad implications of efficacy and completeness. So this package may be lying when it tells it’s secure.

If you’re a security expert and liked the idea of this package, please consider testing it. We’ll be really, really grateful for any help.


Roadmap

{auth0} 0.2.0

  • [] Remove the need for local and remote URLs in the config_file.
  • [] Solve bookmarking and URL parameters issue (Issue #22).
  • [] shinyAppDirAuth0() function to work as shiny::shinyAppDir() (Issue #21).
  • [] Support to ui.R/server.R apps.

{auth0} 0.3.0

  • Implement {auth0} API functions to manage users and login options throusgh R.
  • [] Hex sticker.

Licence

MIT

More Repositories

1

material

Material base para cursos de R.
CSS
95
star
2

treesnip

Parsnip backends for `tree`, `lightGBM` and `Catboost`
R
85
star
3

chess

An R package to read, write, create and explore chess games
R
64
star
4

shinyhttr

Give httr::progress the ability to talk to shinyWidgets::progressBar.
R
32
star
5

stockfish

An R package to analyze chess games with the Stockfish engine
C++
29
star
6

zen-do-r

Um livro sobre programação para não-programadores.
CSS
23
star
7

site

Site da Curso-R
HTML
20
star
8

droll

An R package to analyze roll distributions
R
16
star
9

scryr

An R package to access Scryfall's Magic: The Gathering API
R
15
star
10

lives

HTML
14
star
11

verao2017

Site do Curso R - Verão 2017
CSS
13
star
12

CursoR

Usethis da Curso-R.
R
12
star
13

latinr-shiny

R
11
star
14

curso-r.github.com

Página do curso R
HTML
11
star
15

munifacil

Ajuda a recuperar códigos do IBGE dos municípios do Brasil
R
10
star
16

livro-material

Livro com o conteúdo do material de aulas e do site da Curso-R
R
9
star
17

202011-web-scraping

Material do curso de Web Scraping, da Curso-R, ministrado em Novembro/2020
HTML
9
star
18

kuber

Automate cluster execution via Kubernetes
R
9
star
19

slides2017

Slides da aula 01 2017
HTML
8
star
20

draft

Package to create and upload R drafts
R
6
star
21

201811-deep-learning-R

R
6
star
22

201901-intro-programacao-em-r

Repositório com o material do curso de introdução à programação em R realizado em janeiro de 2019 no programa de verão do IME-USP.
R
6
star
23

intro-programacao-em-r-mestre

Diretório mestre para o curso Introdução à programação em R.
HTML
6
star
24

main-visualizacao

Repositório principal do curso Visualização de dados e relatórios.
JavaScript
6
star
25

202202-intro-ml

Repositório da turma de 02/2022 do curso Introdução ao Machine Learning. Página do curso: https://curso-r.github.io/202202-intro-ml
HTML
5
star
26

main-r4ds-1

Repositório principal do curso R para Ciência de Dados 1
HTML
4
star
27

202011-deep-learning

Repositório para o curso de Deep Learning com R
JavaScript
4
star
28

main-dashboards

Diretório mestre para o curso de Dashboard em R.
HTML
4
star
29

amostra2017

HTML
4
star
30

scrapeBook

Livro sobre Web Scraping em R.
TeX
4
star
31

202109-dashboards

Repositório da turma de 09/2021 do curso Dashboards.
R
4
star
32

202402-intro-estatistica

Repositório da turma de 02/2024 do curso Introdução à Estatística com R. Página do curso: https://curso-r.github.io/202402-intro-estatistica
HTML
4
star
33

201906-dashboard

Repositório para o curso de Dashboard ministrado em junho de 2019
HTML
4
star
34

advent-of-r

🎄 Solving the Advent of Code with R
R
4
star
35

201810-curso-rmarkdown

Curso rmd aMostra
HTML
4
star
36

201812-curso-kantar

Repositório com o material do curso ministrado no Kantar em dezembro de 2018.
HTML
4
star
37

main-pacotes

Repositório principal do curso Pacotes.
JavaScript
3
star
38

201909-intro-r-esalq

HTML
3
star
39

lightgbm-build

Builds of lightgbm R package
3
star
40

verao2016

Site do curso-r de verão de 2016
HTML
3
star
41

202202-web-scraping

Repositório da turma de 02/2022 do curso Web scraping.
R
3
star
42

site-v2

Códigos-fonte do site da Curso-R. Open-source até a alma :)
HTML
3
star
43

basesCursoR

R
3
star
44

cafecomdados

Códigos do episódio dO Café com Dados do dia 14/11/2020
R
3
star
45

shinyNetflix

R
3
star
46

202104-r4ds-2

Repositório da turma de abril de 2021 do curso R para Ciência de Dados II.
R
3
star
47

main-python-r

Jupyter Notebook
3
star
48

201801-r-para-ciencia-de-dados

Repositório com materiais de aula e exercícios para o curso "R para Ciência de Dados" ministrado em Janeiro e Fevereiro de 2018 no IME-USP
HTML
3
star
49

202211-pacotes

Repositório da turma de 11/2022 do curso Pacotes. Página do curso: https://curso-r.github.io/202211-pacotes
CSS
3
star
50

202006-deploy

Workshop Deploy ministrado em 20/06/2020
R
3
star
51

202107-visualizacao

Repositório da turma de 07/2021 do curso Relatórios e visualização de dados.
HTML
3
star
52

main-relatorios

Repositório principal do curso Relatórios e apresentações automáticas
HTML
3
star
53

statsBook

Material do curso de Estatística I e Estatística II
CSS
2
star
54

programando-em-shiny

R
2
star
55

deploy-machine-learning

Apresentação sobre deploy de modelos de Machine Learning com docker + tidymodels + plumber
JavaScript
2
star
56

rladies-GYN-github-actions

2
star
57

201806-workshop-web-scraping

Repositório com o material do workshop de Web scraping ministrado em junho de 2018.
JavaScript
2
star
58

main-r4ds-2

R para Ciência de Dados II
HTML
2
star
59

202011-rcpp

Workshop de Rcpp ministrado em 11/2020
JavaScript
2
star
60

gatitos

Pacote De Exemplo Do GitHub Actions
R
2
star
61

202203-workshop-dsp

HTML
2
star
62

202003-intro-ml

Material do curso online de introdução ao Machine Learning com R, realizado em março e abril de 2020
R
2
star
63

202106-web-scraping

Repositório da turma de 6 de 2021 do curso Web scraping.
HTML
2
star
64

rday-keras

Apresentação R-Day: "Keras: Deep Learning com R"
JavaScript
2
star
65

201903-intro-ml

Repositório para o curso de introdução ao machine learning ministrado em março de 2019.
R
2
star
66

202209-r4ds-1

Repositório da turma de 09/2022 do curso R para Ciência de Dados I. Página do curso: https://curso-r.github.io/202209-r4ds-1
HTML
2
star
67

demo-quarto

TeX
2
star
68

202110-r4ds-1

Repositório da turma de 10/2021 do curso R para Ciência de Dados I.
HTML
2
star
69

amostra2018-EDA-R

R
2
star
70

googleclassroom

Google Classroom API
R
2
star
71

livro-shiny

Repositório para o desenvolvimento do livro "Programando em Shiny"
R
2
star
72

202205-web-scraping

Repositório da turma de 05/2022 do curso Web scraping. Página do curso: https://curso-r.github.io/202205-web-scraping
R
2
star
73

tidynetflix

Ferramentas Para Analise Do Tidytuesday
HTML
2
star
74

202204-r4ds-2

Repositório da turma de 04/2022 do curso R para Ciência de Dados II. Página do curso: https://curso-r.github.io/202204-r4ds-2
HTML
2
star
75

201805-introducao-a-programacao-em-r

Repositório com materiais de aula e exercícios para o curso "Introdução à Programação em R" ministrado em Maio de 2018.
HTML
2
star
76

202303-visualizacao

Repositório da turma de 03/2023 do curso Visualização de dados.
R
2
star
77

site-v3

Versão 3 do site da Curso-R
HTML
2
star
78

202004-web-scraping-2

Material do Workshop 2 de Web Scraping, realizado no dia 25/04/2020
HTML
2
star
79

rightgbm

Easier way for installing LightGBM for R
R
2
star
80

2021-hacktoberfest

HTML
2
star
81

201810-intro-ml

Repositório com o material do curso de introdução ao machine learning em R ministrado no IME em outubro e novembro de 2018.
JavaScript
2
star
82

ragmatic

Minicurso "R pragmático" para aMostra IME-USP 2016.
2
star
83

202210-relatorios

Repositório da turma de 11/2022 do curso Relatórios e apresentações. Página do curso: https://curso-r.github.io/202210-relatorios
HTML
2
star
84

exemploBlogdown

HTML
1
star
85

bandeiras

Jogo das Bandeiras
R
1
star
86

202105-faxina

Repositório da turma de 5 de 2021 do curso Faxina de dados.
HTML
1
star
87

shinygcp

Demo shiny app package for cloud deployment
R
1
star
88

aMostra

PHP
1
star
89

202005-deep-learning

JavaScript
1
star
90

main-intro-ml

Diretório mestre para o curso Introdução ao Machine Learning com R.
HTML
1
star
91

202008-r4ds-2

R
1
star
92

deep-learning-R

JavaScript
1
star
93

aMostra2023-organizacao-dados

JavaScript
1
star
94

202102-r4ds-1

Repositório da turma de fevereiro de 2021 do curso R para Ciência de Dados I.
HTML
1
star
95

bltm

Bayesian Latent Threshold Models using R, based on Nakajima & West (2013)
R
1
star
96

202103-visualizacao

Repositório da turma de 3 de 2021 do curso Visualização de dados e relatórios.
HTML
1
star
97

201909-workshop-r-fgv

Material para o Workshop de R para o curso de MBA da FGV. 2019-09-09
R
1
star
98

202107-deploy

Repositório da turma de 07/21 do curso Deploy.
R
1
star
99

pollsapi

R client for Polls API service
R
1
star
100

pu.shiny

R
1
star