Spring安全核心插件:用户的不同主页,具体取决于其角色

时间:2013-02-03 17:25:36

标签: grails spring-security

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

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

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

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

我该如何实现?

2 个答案:

答案 0 :(得分:6)

一种快捷方式是在控制器动作中执行逻辑。例如,home操作可以基于角色呈现不同的视图,例如

import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils

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
      }

      // ???
   }
}

答案 1 :(得分:0)

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

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