You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny点击首标签页按钮触发shinymanager认证后显示其余标签页咨询

解决方案

你的需求完全可以通过shinymanager原生功能实现,不需要自行开发认证表单,不会存在额外的安全风险。

原代码失效原因

  • 你调用secure_app(ui)时默认会在应用启动时直接加载认证拦截页,不会先展示你编写的Welcome标签页
  • secure_server()是服务端初始化函数,不能放在observeEvent中动态调用,必须在服务端启动时完成初始化

修复后可运行代码

library(shiny)
library(shinymanager)
library(shinydashboard)
library(shinyWidgets)
library(shinythemes)

credentials <- data.frame(
  user = c("user1"),
  password = c("1"),
  stringsAsFactors = FALSE
)

# user interface
ui <- navbarPage(id="navbarid",
                 "TEST",  theme = shinytheme("cosmo"),
                 header = tagList(
                   useShinydashboard()),
                 
                 tabPanel(
                   "Welcome", fluidRow(align = "center", 
                                       column(6, offset=4,
                                              box(title = "Authentification", background = "black", 
                                                  fluidRow(column(6, align = "center", style='padding-top:20px;',
                                                                  actionButton(inputId = "connect", label = "Log in")),
                                                           column(6, align = "center", style='padding-top:20px;',
                                                                  actionButton(inputId = "register", label = "Register here"))))))),
                 
                 tabPanel("Tab2", verbatimTextOutput("label1")
                 ),
                 
                 tabPanel("Tab3", verbatimTextOutput("label2")
                 ))

# 关键:设置start_proxy = TRUE,应用启动时不直接触发认证
ui <- secure_app(ui, start_proxy = TRUE, enable_admin = FALSE)

server <- function(input, output, session) {
  
  # 初始化时隐藏需要权限的标签页
  hideTab(inputId = "navbarid", target = "Tab2")
  hideTab(inputId = "navbarid", target = "Tab3")
  
  res_auth <- secure_server(
    check_credentials = check_credentials(credentials)
  )
  
  # 点击登录按钮触发认证页
  observeEvent(input$connect, {
    trigger_auth()
  })
  
  # 认证通过后显示隐藏的标签页
  observe({
    req(res_auth()$user)
    showTab(inputId = "navbarid", target = "Tab2")
    showTab(inputId = "navbarid", target = "Tab3")
    # 可选:认证通过后自动跳转到Tab2
    updateNavbarPage(session, "navbarid", selected = "Tab2")
  })
  
  output$icon1 <- renderText(as.character(icon("sign-in-alt")))
  output$icon2 <- renderText(as.character(icon("users")))
  
  output$label1 <- renderText("First tab content here")
  output$label2 <- renderText("Second tab content here")
}

shinyApp(ui, server)

核心逻辑说明

  • start_proxy = TRUE是shinymanager提供的参数,作用就是让应用先正常加载页面,不自动触发认证拦截
  • trigger_auth()是配套的主动触发认证的函数,你可以绑定到任意交互事件上调用
  • 认证状态通过res_auth()响应式对象获取,当用户完成认证后该对象会返回用户相关信息,以此为条件控制标签页的显示即可

内容的提问来源于stack exchange,提问作者Linda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:48:01