【问题标题】:Spring security core plugin: Different home page for user depending upon its RoleSpring security core plugin:根据其角色为用户提供不同的主页
【发布时间】:2013-01-18 11:10:48
【问题描述】:

我在我的 Grails 应用程序中集成了 Spring 安全核心插件。

grails.plugins.springsecurity.successHandler.defaultTargetUrl = "/user/home"

这是我在成功登录后设置默认主页所做的。但我想根据用户角色有不同的主页

目前我有 2 个用户角色 1)“ROLE_ADMIN” 2)“ROLE_USER”

我将如何实现这个?

【问题讨论】:

    标签: grails spring-security


    【解决方案1】:

    一种快速的方法是在控制器操作中执行逻辑。例如,home 操作可以根据角色呈现不同的视图,例如:

    import grails.plugin.springsecurity.annotation.Secured
    
    class UserController {
       def home() {
          String view
          if (SpringSecurityUtils.ifAllGranted('ROLE_ADMIN')) {
             view = 'admin'
          }
          else if (SpringSecurityUtils.ifAllGranted('ROLE_USER')) {
             view = 'user'
          }
          else {
             // ???
          }
    
          render view: view, model: [...]
       }
    }
    

    如果你想在不同的控制器之间分配逻辑,你可以根据角色重定向:

    import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
    
    class UserController {
       def home() {
          if (SpringSecurityUtils.ifAllGranted('ROLE_ADMIN')) {
             redirect controller: '...', action: '...'
             return
          }
          if (SpringSecurityUtils.ifAllGranted('ROLE_USER')) {
             redirect controller: '...', action: '...'
             return
          }
          // ???
       }
    }
    

    【讨论】:

    • 我认为您需要做的就是将导入从 import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils 更改为 import grails.plugin.springsecurity.SpringSecurityUtils
    【解决方案2】:

    您也可以配置身份验证成功处理程序,它将根据角色将用户重定向到特定控制器。

    class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
        LinkGenerator linkGenerator
        private static final ADMIN_ROLE = 'ROLE_Admin'
    
    
        @Override
        protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
            if(SpringSecurityUtils.ifAllGranted(ADMIN_ROLE)) {
                return linkGenerator.link(controller: 'admin', action: "index")
            }
    
            return super.determineTargetUrl(request, response);
        }
    
    }
    

    Spring Security Core : Redirect users to different screen based on role

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 2021-08-03
      • 2015-07-04
      • 2011-08-16
      相关资源
      最近更新 更多