使用spring security处理成功的登录事件

时间:2013-12-24 17:21:04

标签: grails spring-security grails-plugin

我的Grails应用使用Spring Security插件。每当用户成功登录时,我想:

  • 在会话中存储内容
  • 将它们重定向到自定义页面(取决于他们的角色)

我需要类似地处理注销事件,这非常简单,因为插件提供了一个可以覆盖的名为logoutSuccessHandler的bean。我希望同样找到一个名为loginSuccessHandler的bean,但没有这样的运气。

我在插件的文档中读到了关于event handling的页面,但是这两种事件处理机制似乎都不允许我访问当前的请求或会话。

3 个答案:

答案 0 :(得分:4)

如果您想在成功登录后做一些事情。您可以收听InteractiveAuthenticationSuccessEvent

class AuthenticationSuccessEventListener implements    
                       ApplicationListener<InteractiveAuthenticationSuccessEvent> {


    @Override
    public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
         .......do some stuff here
    }
   }

然后在resources.groovy中将AuthenticationSuccessEventListener注册为spring bean 你可以在这里做任何你想做的事情,但是你无法从听众那里做重定向。

这是另一个类似的question

答案 1 :(得分:3)

添加配置参数:

grails.plugins.springsecurity.successHandler.defaultTargetUrl = '/myLogin/handleSuccessLogin'

然后在处理此URL的操作中添加自定义登录处理

class MyLoginController {

  def springSecurityService

  def handleSuccessLogin() {
    session.foo = 'bar'

    if (springSecurityService.currentUser.username == 'bob') {
      redirect action: 'bobLogin'
    } else {
      redirect action: 'defaultLogin'
    }         
  }  

  def bobLogin() {
    // bob's login handler
  }

  def defaultLogin() {
    // default login handler
  }
}

答案 2 :(得分:1)

我最近在一个项目中使用它来登录。它有点像黑客但对我有用。我正在使用插件的1.2.7.3版本。

def auth() {        

    def config = SpringSecurityUtils.securityConfig

    if (springSecurityService.isLoggedIn()) {
        def user = User.get(principal.id)

        def roles = user.getAuthorities()

        def admin_role = Role.findByAuthority("ROLE_ADMIN")

        //this user is not admin
        if(!roles.contains(admin_role)){
            //perform redirect to appropriate page
        }
        redirect uri: config.successHandler.defaultTargetUrl
        //log.info(getPrincipal().username + "logged in at :"+new Date())
        return
    }

    String view = 'auth'
    String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
    render view: view, model: [postUrl: postUrl,
                               rememberMeParameter: config.rememberMe.parameter]
}

对于注销我使用了一个Logout控制器,在重定向到注销处理程序之前执行了一些操作:

class LogoutController {

     /**
     * Index action. Redirects to the Spring security logout uri.
     */
     def index = {
         // perform some action here
         redirect uri: SpringSecurityUtils.securityConfig.logout.filterProcessesUrl 
     }
}