Giter Club home page Giter Club logo

cognitor's Introduction

CognitoR

CRAN status

Credits


This package is developed and mantained by the Chi2Labs team.

Inspired on an initial contribution by Adi Sarid.

Disclaimer

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

Installation

You can install from CRAN with:

install.packages("cognitoR")

Or from github with:

devtools::install_github("chi2labs/cognitoR")

Requirements

You need to have:

  • Amazon AWS account.

About Amazon Cognito

If you do not have experience with Amazon Cognito, It is recommended to read the official documentation: Amazon Cognito

How it works ?

When a user accesses to your Shiny application with CognitoR, the user is redirected to your configured url in Amazon Cognito, there if user is not logged in, a login page will appear.

If the user is already logged or successful authentication is accomplished , the user is redirected back to your Shiny App with a code/token (depending of your configuration) in the url.

If the app is loaded with a code will get a token via oauth (this code can be used only once). If the app already has the token (via url or received it using the code) it will check authorization with Amazon Cognito via an OAUTH request using the token. A valid authorization will allow the Shiny app lo load, the user will be redirected back to the login page.

Steps

1 - Go to Amazon Cognito

Once you have logged with your Amazon AWS account, go to “Cognito” service and click on “Manage User Pools”.

2 - Create a User Pool

Name your user pool:

Create a client application (Application that will work with this user pool):

This will generate the client id and the client secret you will need to configure your shinyapp.

3 -Configure your domain for your Login Form

Go to App Integration -> Domain Name, to set the url for login form, you can use a Amazon subdomain or use your own domain.

Also remember the url for your configuration.

4 - Settings for Application

Go to App Integration -> App Client Settings and you must:

  • Enable Identity provider: Cognito User Pool
  • Set the “Callback URL” (Where will be redirect the user when login is succesful)
  • Set the “Sign Out Url” (Where will be redirect the user when logout is successful).
  • Enable OAuth 2.0 : You have support for “Authorization Code Grant” (recommended) and “Implicit Grant”.
  • Enable “Allowed OAuth Scope” (recommended: email and openid).
  • Save setting.

Your basic configuration in Amazon Cognito is ready.

5 - Configuration of your Shiny application with Amazon Cognito.

This package requires that you have a configuration file (“config.yml”) in your application folder with the following structure:

  • group_id: The ID Pool
  • group_name: The User Pool Name.
  • oauth_flow: Flow configured,(“code” for Authorization code grant flow or “token” for Implicit grant)
  • base_cognito_url: Your domain url for Client App.
  • app_client_id: Your app client id.
  • app_client_secret: Your app client secret id.
  • redirect_uri: Url configured in “Callback URL”
  • redirect_uri_logout: Url configured in “Sign Out Url”

Example:

default:
  cognito:
    group_id: ""
    group_name: "YOUR_POOL_NAME"
    oauth_flow: "code"
    base_cognito_url: "https://your_domain.auth.us-east-1.amazoncognito.com"
    app_client_id: "YOUR_CLIENT_ID"
    app_client_secret: "YOUR_SECRET_ID"
    redirect_uri: "YOUR_APP_URL"
    redirect_uri_logout: "YOUR_APP_URL"

6 - Add Support to your Shiny App

An example app can be found in inst/examples/simple-login-app.R.

The package has two main functions cognito_ui() and cognito_server(). cognito_ui() loads required UI for Cognito Module. cognito_server() which takes care of the logic and interaction with Cognito API. This method also returns reactive elements for:

  • Checking if user is logged in.
  • Redirecting to Amazon Cognito Login Page configured if user is not logged in.
  • Getting data for the authenticated user.
  • Callback for Logout of Amazon Cognito.

The example mentioned above includes the use of the Logout module (logout_ui() and logout_server()) which provide a “logout” button interacting with the reactive “isLogged” returned from Cognito Module to show the button and with the logout callback when button is pressed.

7 - Run your app

You will be redirect to Cognito Login Form , there you can create your account and log in.

Upon successful authentication, you will be redirect to your app:

8 - Running example application

The example app can be found in inst/examples/simple-login-app.R.

This app work with a config.yml configured to work with a Cognito instance of Chi2labs, this instance not allow to create user and is required that you run this shiny app using the port 5000 (because Cognito instance is configured to expect this port).

options(shiny.port = 5000)
runApp('inst/examples/simple-login-app.R')

You can test the application with these credentials:

  • user: “demo”
  • password: “password”

cognitor's People

Contributors

andrie avatar dietrichson avatar dyfanjones avatar gdamjan avatar ppagnone avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cognitor's Issues

Callback URL issue

Hello.
First of all thank you for this really cool package. It is really neat and functional. I am working with your minimal example from here. I believe my setup and credentials are correct as I managed to create a new account from cognitoR, verify it with email code and see the changes on the AWS Cognito. I have a question about the callback and sign out URLs. When I launch cognitoR and put my credentials I get redirected to a link like https://localhost/?code=36d774ca-692b-4ed0-bffb-d368c62edcc0. And my browser says unable to connect, so I do not see any shiny UI elements. Is there something I am missing? My config and AWS Cognito are currently configured with https://localhost for both call back and sign out, as per the example.

Flexdashboard Usage

What would be the way to utilize this package within a Shiny app made using Flexdashboard? The dashboard has an ability to incorporate shiny modules directly: https://rstudio.github.io/flexdashboard/articles/shiny.html#inline-applications

In the example below, the app simply shows the spinner w/o reaching the Cognito Login UI. Likely I am doing something wrong and would appreciate some insights on what I am missing.

---
title: "test"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r global, include=FALSE}
library(flexdashboard)
library(cognitoR)
options(shiny.port = 5000)
```

```{r}
shinyApp(
    ui = function() {
        fluidPage(
            # Load UI logout
            logout_ui("logout"),
            # Load UI Cognito.
            cognito_ui("cognito"),
            # Output to show some content.
            uiOutput("content"))
    },
    
    server = function(input, output, session) {

        # Call Cognito module. ####
        cognitomod <- callModule(cognito_server, "cognito")

        # Call Logout module ####
        logoutmod <- callModule(logout_server,
                                "logout",
                                reactive(cognitomod$isLogged),
                                sprintf("You are logged in as '%s'", cognitomod$userdata$email))

        # To Click on button logout of logout module, call logout in cognito module. ####
        observeEvent(logoutmod(),{
            cognitomod$logout()
        })

        # Check if user is already logged, and show a content. ####
        observeEvent(cognitomod$isLogged, {
            if (cognitomod$isLogged) {
                # User is logged
                userdata <- cognitomod$userdata
                # Render user logged.
                output$content <- renderUI({
                    p(paste("User: ", unlist(userdata$username)))
                })
            }
        })

    },
    
    options = list(port = 5000)
)
```

Integration with {lambdr}

Can you add integration with {lambdr} to make use of AWS Cognito Triggers (like the Pre sign-up trigger)

Don't export internal functions

It is not clear if the end-user of the package needs access to get_config(). There may be other functions as well that are only meant for package use, and should not be exported.

Add option to create own cookie when is logged in Cognito

This is not secure and is not recommended in Oauth implementations .. but can be useful in shiny apps to persist the authentication even when the page is reloaded (and session rebooted) avoiding multiples redirection flow to Amazon Cognito to validate the account.

This must be optional and by default must be disabled.

Support for ui <- function(request) {}

@ppagnone @dietrichson Appreciate this package as a whole! Have you ever built an app with a ui <- function(request) {} function that would support shiny bookmarking or know of any reason this wouldn't work?

I've ran into an issue deploying an update to my previously working shiny app that would support bookmarking. The app deploys fine without the request or with shinymanager around the request, but once integrated with cognitoR it seems to trigger initialization of the app on the EC2 instance in a loop that crashes it. I'm having trouble figuring out what is causing this - happy to provide a reprex of some sort but figured I'd see if you had any ideas first.

Using a ZIP-downloadHandler in combination with CognitoR log-in breaks the RShiny App

Hi,

I have been working on an RShiny app in which files can be created and downloaded, which uses the cognitoR package for the log-in. One of the possible download options is a downloadHandler in which multiple files will be combined into a zip. When the zip is downloaded and I try to refresh the page, the entire link breaks, and it can only be restored by re-commiting the entire code in GitHub, hence this is not a standard error.

The error that is produced is:
Warning: Error in module: Your configuration for Cognito Service is not correct.
45: stop
44: module
39: callModule
38: server [/srv/shiny-server/app.R#321]
1: runApp
Error in module(childScope$input, childScope$output, childScope, ...) :
Your configuration for Cognito Service is not correct.
Terminated

It looks like using the cognitoR for a login, in combination with a zip download (in which multiple temporary paths are created) breaks the link. The package works perfectly when I download a single CSV / XLSX, so it seems to be ZIP related.

Do you perhaps have a solution for this issue?

Appreciate your time and I'm happy to provide more information if necessary!

Does cognitoR require usage of app.R?

Hello,

I recognize that this is not an issue per se as much as a question, so feel free to close if it is not the right avenue. We are trying to implement the cognitoR framework to our app, except that it's split over a ui.R, server.R, and global.R file, and we're running into difficulties in making the app go live.

As we're trying to troubleshoot, I note that all your examples are of the app.R variety - is this a requirement for the successful implementation of cognitoR into an app?

shinyapps.io

Hi guys!

Thanks for the nice package! I am currently testing a deployment of my app in shinyapps.io. The app works locally, but when I deploy to shinyapps.io I can never get to the login page. The app looks like it goes into a loop that tries to redirect the page, and then comes back.. My first impression was that shinyapps.io has some sort of page redirect too, which kind of messes up the cognito setup. Any ideas or experiences with that?

config.yml parsing issue?

Awesome tool. Just want to share that there is a warning message :

"incomplete final line found on 'C:\Users......."

Also the redirect_uri and redirect_uri_logout in the config file needs a "/" at the end of the url. Might trip some people up during the testing. =)

Test cognitoR with latest version of paws.common 0.6.0

Hi all,

I am in the process in releasing the latest version of paws.common 0.6.0 paws-r/paws#657. paws.common 0.6.0 comes with a new xml parser that has increased performance: paws-r/paws#621. However I am going around all paws dependent packages to ensure the new xml parser doesn't break any existing code.

Is it possible to run your existing tests with the latest version of paws.common 0.6.0? If not please let me know how to set up my environment so that I can test these changes on your behalf.

To install paws.common 0.6.0 you can use r-universe:

install.packages('paws.common', repos = 'https://paws-r.r-universe.dev')

Authenticate with `scope=openid` to be able to retrieve all user attributes

This is more of a feature request to support all user attributes than a bug.
I could not retrieve custom user attributes via the userdata values and wanted to know what might be the issue since the userInfo endpoint from Cognito is providing them.

According to stackoverflow scope need to be defined as scope=openid during the authentication.

A short tryout with adding this to the build of the url in get_url_auth_redirect, it can retrieve all user attributes including the custom ones.

...
 aws_auth_redirect <- paste0(cognito_config$base_cognito_url, 
    "/oauth2/authorize?", "scope=openid", "&", "response_type=", 
    cognito_config$oauth_flow, "&", "client_id=", cognito_config$app_client_id, 
    "&", "redirect_uri=", cognito_config$redirect_uri, "&", 
    paste0("state=", params))
...

Error in login

When i delete cookies from web-browser and i login in aws cognito there is the error:

Warning: Error in : $ operator is invalid for atomic vectors
  96: renderUI [/opt/shiny-server/samples/sample-apps/rmd/app.R#47]
  95: func
  82: origRenderFunc
  81: output$logout-who
   1: runApp
Warning: Error in $: $ operator is invalid for atomic vectors
  100: unlist
   96: renderUI [/opt/shiny-server/samples/sample-apps/rmd/app.R#64]
   95: func
   82: origRenderFunc
   81: output$content
    1: runApp

Do not import config

Hi, maintainer of config here.

I am in the process of submitting a new version of config to CRAN, but my reverse dependencies fail on your package.

The reason seems to be that you are importing all of config, but you only actually use config::get() in your package.

The fix is quite simple, use:

# @importFrom config get

instead of

# @import config

I'll submit a PR to fix this, but can you please submit a new version to CRAN of your package to CRAN as soon as possible?

Andrie

using cognitoR authentication for S3 service

Hi, first of all, thanks for this nice package.
I will try to explain my situation here, and let me know if something is wrong in my reasoning (I am quite new on AWS world).
In Amazon Cognito, I have a user pool, and each of the users belongs to a group, and each group has an IAM role associated which will determine which S3 resources (files) are able to retrieve.
Running my Shiny APP,

  • I authenticate the user with Cognito, using one App Client (defined in General Settings/App clients), that is, App client id and App client secret.
  • The authentication is successful and CognitoR package gives me the session_token.
  • Then, I want to use the role of the authenticated user to access a file in an S3 bucket which is accessible by the policy of the role of the user. However, when I use the App Client id and secret, using both "paws" or "aws.s3" R packages, I get the same error respectivelly:
    Error during wrapup: InvalidAccessKeyId (HTTP 403). The AWS Access Key Id you provided does not exist in our records.
    or
    List of 5
    $ Code : chr "InvalidAccessKeyId"
    $ Message : chr "The AWS Access Key Id you provided does not exist in our records."

Is there something I am missing?
I thought I would be able to use AppClient id and secret for S3 access, but maybe I am wrong...?
Thank you in advance!

cognitoR breaks appending tabPanel with Bootstrap 4+

Hi,

This is a very specific issue, but I found that when the following conditions are fulfilled:

  • Using cognitoR
  • Using Bootstrap 4+ (with bslib::bs_theme())
  • Using appendTab

Then trying to remove or update the tabPanel doesn't work.

Here is a reproducible example (you will need to have a Cognito config file set up):

library(shiny)

ui <- fixedPage(
  theme = bslib::bs_theme(version = 4),
  # cognitoR::cognito_ui("cognito"),
  actionLink("newTab", "Append tab"),
  actionLink("removeTab", "Remove current tab"),
  actionLink("oneTab", "Go to tab 1"),
  tabsetPanel(id="myTabs", type="pills"),
)

server <- function(input, output, session) {
  
  cognitoModule <- callModule(
    cognitoR::cognito_server,
    "cognito"
  )
  
  tabIndex <- reactiveVal(0)
  observeEvent(input$newTab, {
    tabIndex(tabIndex() + 1)
    appendTab("myTabs", tabPanel(tabIndex(), tags$p(paste("I'm tab", tabIndex()))), select=TRUE)
  })
  observeEvent(input$removeTab, {
    removeTab("myTabs", target=input$myTabs)
  })
  observeEvent(input$oneTab, {
    updateTabsetPanel(
      inputId = "myTabs",
      selected = "1"
    )
  })
  observe({
    print(input$myTabs)
  })
}

shinyApp(ui, server)

This code can be used to add new tabPanel by clicking on a button. There is a 2nd button to remove the currently selected tabPanel. The 3rd button is used to select the 1st panel (if it exists).

To make this code work, I need to either:

  1. Downgroad the bootstrap version to 3.
  2. Not use cognitoR by commenting the lines loading the Cognito module.

I do not understand where this comes from and what Cognito has to do with that. I noticed that in the broken version, the tabPanel have missing CSS classes (they should have class="nav-item" and they don't have it).

For now my solution will be to downgrade to Bootstrap 3.

Direct Authentication

Hi! Your package is awesome but I needed something that do not send me to another UI and back. I searched about it a lot. I use paws package for communications with AWS. It was a complicated process to extract that info from docs and Google searches but implementation is straightforward. Consider this a feature request :)

Here is a starter code. I'm sorry it is not that clean for a pull request.

https://gist.github.com/berkorbay/45b84c2a98445887bb85d4b58540206f

Update rStudio breaks simple demo app - Cogntio redirect URL repeatedly called

Hi,

I have been using your package for a year, and it has worked great. I have recently updated to the most recent rStudio (Version 2023.09.0+463); however, this has caused an error with the cognito_server function. The function is now repeatedly called and opens new Google tabs, asking users to log in through the AWS Cognito portal continuously, even when loading your simple-example-app.

I'm happy to provide more information if you need it - do you have a solution?

Cheers

paws 0.4.0 reverse dependency warning

Hi All,

During the paws 0.4.0 we received the following warning message:

Changes to worse in reverse depends:

Package: cognitoR
Check: whether package can be installed
New result: WARNING
  Found the following significant warnings:
    Warning: replacing previous import ‘httr::config’ by ‘paws::config’ when loading ‘cognitoR’

From checking your code, I don't believe you use httr::config and therefore won't be affected. Can you please confirm this is ok so that paws 0.4.0 can be fully released to the cran.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.