ShinyApps.io部署OAuth授权Shiny应用遇登录无响应问题
问题原因
oauth2.0_token()函数在Shiny服务器端执行时,会尝试在服务器本地打开浏览器完成认证,这在ShinyApps.io的托管环境中无法和用户的浏览器交互,导致应用卡住,无法触发后续逻辑。- 手动访问认证URL完成登录后,跳转回应用时,服务器没有监听回调URL中的授权码(
code参数),因此无法完成token的交换流程,导致应用无响应。
解决方案
调整为授权码授权流程,让用户在前端浏览器完成认证,服务器通过回调URL获取授权码后再换取token。修改后的代码如下:
library(shiny) library(httr) # OAuth应用配置 korap_app <- oauth_app( "korap-client", key = "tmNm9RMf3hnFMpnTN4NbFT", secret = NULL, redirect_uri = "https://danieljach.shinyapps.io/KED_interface/" ) korap_endpoint <- oauth_endpoint( NULL, authorize = "settings/oauth/authorize", access = "api/v1.0/oauth2/token", base_url = "https://korap.ids-mannheim.de" ) # UI ui <- fluidPage( titlePanel("OAuth Shiny App Template"), mainPanel( actionButton("loginButton", "Login with OAuth"), textOutput("authStatus") ) ) # Server server <- function(input, output, session) { authenticated <- reactiveVal(FALSE) # 处理登录按钮点击:跳转至认证页面 observeEvent(input$loginButton, { # 生成授权URL auth_url <- oauth2.0_authorize_url( korap_endpoint, korap_app, scope = "search match_info" ) # 让用户浏览器跳转至认证页面 session$sendCustomMessage( type = "redirect", message = list(url = auth_url) ) }) # 处理回调URL中的授权码,换取token observe({ query <- parseQueryString(session$clientData$url_search) if (!is.null(query$code)) { tryCatch({ # 用授权码换取token token <- oauth2.0_access_token( korap_endpoint, korap_app, code = query$code, cache = FALSE ) if (!is.null(token)) { authenticated(TRUE) output$authStatus <- renderText("Authentication Successful!") } else { output$authStatus <- renderText("Authentication Failed: Token is null.") } }, error = function(e) { output$authStatus <- renderText(paste("Authentication Error:", e$message)) }) } }) # 根据认证状态展示内容 observe({ if (authenticated()) { # 这里添加已认证用户的内容 } else { # 未认证用户的内容 } }) } # 运行应用 shinyApp(ui, server)
关键修改说明
- 替换
oauth2.0_token()为oauth2.0_authorize_url()生成认证URL,通过session$sendCustomMessage让用户浏览器跳转至认证页面,而非在服务器端尝试打开浏览器。 - 添加监听回调URL中
code参数的逻辑,一旦获取到授权码,调用oauth2.0_access_token()换取token。 - 加入
tryCatch捕获认证过程中的错误,便于排查问题。
额外注意事项
- 确保在Korap平台的OAuth应用设置中,回调URI与代码中的
redirect_uri完全一致(包括末尾的斜杠)。 - ShinyApps.io的应用URL必须是公开可访问的,否则认证提供商无法完成回调。
- 避免在代码中硬编码密钥,建议使用ShinyApps.io的环境变量存储敏感信息(如
Sys.getenv("KORAP_CLIENT_KEY"))。
内容的提问来源于stack exchange,提问作者Daniel Jach
相关产品推荐
相关产品推荐

