如何在 R Shiny 中验证 auth0 令牌并处理错误?

How to Validate an auth0 token in R Shiny and handle errors?

我不是编程新手,但我对 R Shiny 非常陌生。

一个门户网站将链接到我的 R Shiny 应用程序(该应用程序将部署到 docker 容器中的闪亮服务器),并且该门户网站将向我传递一些查询字符串参数app - 一个 auth0 令牌、aud 值和我应该验证令牌的 auth0 url。

我想要做的是,一旦我的应用程序启动,它就会从查询字符串中获取查询参数,使用 auth0 url 验证令牌,并检查“aud”值是否匹配在经过验证的令牌中。

我还想捕获任何错误并仅显示“403 Forbidden”文本。目前,我一直在绞尽脑汁试图让它发挥作用,但由于我在 R 和闪亮方面的经验有限,我的代码中几乎没有什么用处。对代码解决方案的任何详尽解释都将非常有帮助。

我目前有什么

server <- function(input, output, session){
  # gets query string values
  token <- reactive({getQueryString()$token})
  authurl <- reactive({getQueryString()$authurl})
  aud <- reactive({getQueryString()$aud})

  # this currently makes sure the token validates and compares the "aud" value to what
  # was received in the query string but i need to break this apart some how, to:
  # 1) show "403 Forbidden" if the authurl is not present/bad/cannot connect
  # 2) show "403 Forbidden" if the token is not present/bad
  # 3) show "403 Forbidden" if the aud is not present/bad
  # 4) show "OK" (eventually the app itself) if result is True and all is valid
  result <- reactive({jwt_decode_sig(token(), read_jwk(fromJSON(rawToChar(GET(paste0("https://",authurl(),"/.well-known/jwks.json"))[["content"]]))$keys[[1]]))$aud == aud()})
  
  # I'm using this to printout the value of the result() call as a test
  output$token <- renderText({result()})

  # this is what I'd like to use (or something like this) to determine if the user should 
  # be shown a "403" or the app itself. In running some tests, I don't believe this code 
  # actually executes. I don't know why.
  shinyCatch(
    if(result() == TRUE){
      shinyjs::show("app-content")
      shinyjs::hide("loading-content")
    }
    else{
      shinyjs::show("error")
      shinyjs::hide("loading-content")
    }
  )
}

TIA

在@MrFlick 的建议的帮助下,我能够让它按照我想要的方式工作。这就是我所做的:

在 ui 函数中,这是我的 div:

div(
    id = "loading-content",
    h2("Authenticating...")
  ),
hidden(
    div(
      id = "app-content",
      ...
       )
      ),
hidden(
    div(
      id = "error",
      h2("Error 403: Forbidden User")
    )
  )

在我的服务器函数中,代码更改在“结果”function/value 中。基本上,如果令牌、aud 或 authurl 无效,它将显示错误文本。如果一切都经过验证,它将显示该应用程序。

token <- reactive({getQueryString()$token})
  authurl <- reactive({getQueryString()$authurl})
  aud <- reactive({getQueryString()$aud})
  
  result <- reactive({
    tryCatch(
      {jwt_decode_sig(token(), read_jwk(fromJSON(rawToChar(GET(paste0("https://",authurl(),"/.well-known/jwks.json"))[["content"]]))$keys[[1]]))$aud == aud()},
      error = function(e){
        message("bad authentication params: token or authurl")
        return(FALSE)
      }
    )
    
  })
  
  observe({
  if(result() == TRUE){
    shinyjs::show("app-content")
    shinyjs::hide("loading-content")
  }
  else{
    shinyjs::show("error")
    shinyjs::hide("loading-content")
  }
  })