2016-03-16 47 views
0

我試圖在Spring Security中成功/失敗的登錄/註銷之後記錄消息。如何在Spring Boot應用程序中使用Spring Security監聽登錄/註銷事件?

此外,我使用的是Spring Boot,所以幾乎沒有配置代碼。

我正在使用的窗體是自動生成的。

WebSecurityConfig.java

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 

     http 
      .authorizeRequests() 
       .antMatchers("/resources/**").permitAll() 
       .anyRequest().fullyAuthenticated() 
       .and() 
      .formLogin(); 

    } 

    @Configuration 
    protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter { 

     @Override 
     public void init(AuthenticationManagerBuilder auth) throws Exception { 
      auth 
       .ldapAuthentication() 
       .userSearchFilter("(uid={0})") 
       .contextSource() 
       .url("ldap://...:389/ou=...,dc=...,dc=...") 
       .managerDn("cn=...,dc=...,dc=...") 
       .managerPassword("..."); 
     } 
    } 
} 

logback.xml

<?xml version="1.0" encoding="UTF-8"?> 
<configuration> 
    <include resource="org/springframework/boot/logging/logback/base.xml"/> 
</configuration> 

我的登錄成功的代碼如下:

LoginSuccessService.java

import java.util.Date; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.context.ApplicationListener; 
import org.springframework.security.authentication.event.*; 
import org.springframework.stereotype.Component; 
import org.springframework.stereotype.Service; 

@Component 
public class LoginSuccessService implements ApplicationListener<InteractiveAuthenticationSuccessEvent>{ 

    private static final Logger logger = LoggerFactory.getLogger(LoginSuccessService.class); 

    @Override 
    public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { 
     logger.debug("You have been logged in successfully."); 
     Date loginDate = new Date(); 
     logger.debug("Login Time: " + loginDate.toString()); 
    } 
} 

它不會工作。我在日誌中什麼也沒得到。

需要額外的代碼,如果有的話?我需要在任何地方初始化這個監聽器嗎?

我也用this link作爲參考,但我覺得我不需要寫一個出版商,因爲我沒有爲這個活動寫自己的課。

我也嘗試用AuthenticationSuccessEvent而不是InteractiveAuthenticationSuccessEvent,但同樣的事情。

如果有幫助,登陸失敗將產生以下輸出(預期的輸出應包含「無法登錄」和當前日期,這與調試日誌=在application.properties TRUE):

2016-03-16 18:50:12.779 DEBUG 8895 --- [nio-8080-exec-7] o.s.b.c.web.OrderedRequestContextFilter : Bound request context to thread: [email protected] 
2016-03-16 18:50:12.779 DEBUG 8895 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy  : /login at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter' 
2016-03-16 18:50:12.779 DEBUG 8895 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy  : /login at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 
2016-03-16 18:50:12.779 DEBUG 8895 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: '[email protected]979972: Authentication: org.springframew[email protected]56979972: Principal: or[email protected]a96aab26: Dn: cn=User,ou=users,dc=vs,dc=local; Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; CredentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]2cd90: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 524F4F9744824535095B43C18FBA71F4; Not granted any authorities' 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy  : /login at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter' 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.se[email protected]3a3c5471 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy  : /login at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter' 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy  : /login at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter' 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/logout' 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy  : /login at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/login' 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] w.a.UsernamePasswordAuthenticationFilter : Request is to process authentication 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] o.s.s.authentication.ProviderManager  : Authentication attempt using org.springframework.security.ldap.authentication.LdapAuthenticationProvider 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] o.s.s.l.a.LdapAuthenticationProvider  : Processing authentication request for user: iprnein 
2016-03-16 18:50:12.780 DEBUG 8895 --- [nio-8080-exec-7] o.s.s.l.s.FilterBasedLdapUserSearch  : Searching for user 'iprnein', with user search [ searchFilter: '(uid={0})', searchBase: '', scope: subtree, searchTimeLimit: 0, derefLinkFlag: false ] 
2016-03-16 18:50:12.781 DEBUG 8895 --- [nio-8080-exec-7] o.s.l.c.support.AbstractContextSource : Got Ldap context on server 'ldap://192.168.10.41:389/ou=users,dc=vs,dc=local' 
2016-03-16 18:50:12.788 DEBUG 8895 --- [nio-8080-exec-7] o.s.s.ldap.SpringSecurityLdapTemplate : Searching for entry under DN 'ou=users,dc=vs,dc=local', base = '', filter = '(uid={0})' 
2016-03-16 18:50:12.789 DEBUG 8895 --- [nio-8080-exec-7] o.s.b.f.s.DefaultListableBeanFactory  : Returning cached instance of singleton bean 'loginFailureService' 
2016-03-16 18:50:12.790 DEBUG 8895 --- [nio-8080-exec-7] o.s.b.f.s.DefaultListableBeanFactory  : Returning cached instance of singleton bean 'delegatingApplicationListener' 
2016-03-16 18:50:12.790 DEBUG 8895 --- [nio-8080-exec-7] w.a.UsernamePasswordAuthenticationFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials 
2016-03-16 18:50:12.790 DEBUG 8895 --- [nio-8080-exec-7] w.a.UsernamePasswordAuthenticationFilter : Updated SecurityContextHolder to contain null Authentication 
2016-03-16 18:50:12.790 DEBUG 8895 --- [nio-8080-exec-7] w.a.UsernamePasswordAuthenticationFilter : Delegating to authentication failure handler org.springframework.se[email protected]19d8353 
2016-03-16 18:50:12.790 DEBUG 8895 --- [nio-8080-exec-7] .a.SimpleUrlAuthenticationFailureHandler : Redirecting to /login?error 
2016-03-16 18:50:12.790 DEBUG 8895 --- [nio-8080-exec-7] o.s.s.web.DefaultRedirectStrategy  : Redirecting to '/login?error' 
2016-03-16 18:50:12.790 DEBUG 8895 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 
2016-03-16 18:50:12.790 DEBUG 8895 --- [nio-8080-exec-7] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed 
2016-03-16 18:50:12.790 DEBUG 8895 --- [nio-8080-exec-7] o.s.b.c.web.OrderedRequestContextFilter : Cleared thread-bound request context: [email protected] 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.b.c.web.OrderedRequestContextFilter : Bound request context to thread: [email protected] 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy  : /login?error at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter' 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy  : /login?error at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: [email protected] A new one will be created. 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy  : /login?error at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter' 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.se[email protected]3a3c5471 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy  : /login?error at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter' 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy  : /login?error at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter' 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /login' doesn't match 'POST /logout 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy  : /login?error at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /login' doesn't match 'POST /login 
2016-03-16 18:50:12.800 DEBUG 8895 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy  : /login?error at position 7 of 13 in additional filter chain; firing Filter: 'DefaultLoginPageGeneratingFilter' 
2016-03-16 18:50:12.801 DEBUG 8895 --- [nio-8080-exec-9] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 
2016-03-16 18:50:12.801 DEBUG 8895 --- [nio-8080-exec-9] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed 
2016-03-16 18:50:12.801 DEBUG 8895 --- [nio-8080-exec-9] o.s.b.c.web.OrderedRequestContextFilter : Cleared thread-bound request context: [email protected] 
+0

我也懷疑表單不知道應該在事件發生後觸發事件,或者我的偵聽器配置不正確。 – cst1992

+0

爲'org.springframework.security.web.session.HttpSessionEventPublisher'創建一個bean並檢查 –

+0

@KarthikeyanVaithilingam沒有變化。 – cst1992

回答

1

錯誤原來是與配置有關的。

爲了捕獲登錄事件,我用的對象

InteractiveAuthenticationSuccessEventAuthenticationSuccessEvent(註銷不具備實施監聽的是,你可能有運氣HttpSessionEvent)。

此外,查看記錄器是否配置爲記錄您的軟件包很重要;該應用程序未默認配置爲記錄應用程序消息。這就是爲什麼我沒有得到任何輸出。

因此,兩件事情:

  • 如果你的包名是com.mycompany,你應該添加一行在application.propertiesapplication.yml文件(通常在<PROJ_DIR>/src/main/resources/發現;如果沒有,創建你自己的)進行日誌記錄:

application.properties

logging.level.com.mycompany=DEBUG/INFO/WARN/ERROR 
    #debug is lowest, error is highest 

或:

application.yml

logging: 
    level: 
     com: 
      mycompany: DEBUG/INFO/WARN/ERROR 
  • 如果你嘗試登錄的外包裝,用debug()方法記錄它或它可能顯示不出來(我用info(),我什麼都沒有)。
相關問題