代码之家  ›  专栏  ›  技术社区  ›  axk

Spring安全:添加“on successful login event listener”

  •  35
  • axk  · 技术社区  · 18 年前

    我是春季保安的新手。如何添加事件侦听器,该侦听器将作为用户成功登录而被调用?另外,我需要在这个监听器中获得某种独特的会话ID,这应该在后面的部分中提供。我需要这个ID来与另一个服务器同步。

    5 回复  |  直到 7 年前
        1
  •  46
  •   Dani cc1001    13 年前

    您需要定义一个实现 ApplicationListener .

    然后,在代码中,执行如下操作:

    public void onApplicationEvent(ApplicationEvent appEvent)
    {
        if (appEvent instanceof AuthenticationSuccessEvent)
        {
            AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;
            UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();
    
            // ....
        }
    }
    

    然后,在applicationcontext.xml文件中,只需定义该bean,它就会自动开始接收事件:)

        2
  •  42
  •   John29    12 年前

    authenticationSuccessEvent的问题是它不会在RememberMe登录时发布。如果您使用的是rememberMe身份验证,请改用interactiveAuthenticationSuccessEvent,它既适用于普通登录,也适用于rememberMe登录。

    @Component
    public class LoginListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
    
        @Override
        public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event)
        {
            UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();
            // ...
        }
    }
    
        3
  •  24
  •   Dani cc1001    13 年前

    类似于Phill的答案,但修改后考虑了仿制药:

    public class AuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {
    
      @Override
      public void onApplicationEvent(final AuthenticationSuccessEvent event) {
    
          // ...
    
      }
    
    }
    
        4
  •  10
  •   Wanderson Santos    15 年前

    在Grails中,使用Spring安全插件,可以在config.groovy中执行此操作:

    grails.plugins.springsecurity.useSecurityEventListener = true
    
    grails.plugins.springsecurity.onAuthenticationSuccessEvent = { e, appCtx ->
    
            def session = SecurityRequestHolder.request.getSession(false)
            session.myVar = true
    
    }
    
        5
  •  0
  •   Sujit    7 年前

    另一种使用方法 @EventListener

    @EventListener
    public void doSomething(InteractiveAuthenticationSuccessEvent event) { // any spring event
        // your code 
    
    }
    
    推荐文章