2015-01-01 41 views
3

編輯:已解決。在此帖子後查看我的評論Spring AuthenticationFailureHandler和WebSecurityConfigurerAdapter loginPage()

我目前正在使用Spring-Security實現Web應用程序。我已經實現了一個自定義AuthenticationFailureHandler,它可以檢查用戶是否嘗試經常使用錯誤的憑據登錄(並阻止他幾分鐘)。但正常失敗的登錄應該將用戶重定向到具有參數錯誤的登錄頁面(/login?error)。此頁面顯示錯誤消息,如「您鍵入的密碼是錯誤的」

AutenticationFailureHandler看起來像這樣(沒有代碼uninteressting林斯)

public class CustomAuthenticationHandler implements AuthenticationFailureHandler { 
// Some variables 

@Override 
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { 

// some logic here.. 

request.setAttribute("param", "error"); 
response.sendRedirect("/login?error"); 

} 

我WebApplicationSecurity類看起來是這樣的:

現在
@Configuration 
@EnableWebMvcSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
CustomAuthenticationHandler customAuthenticationHandler; 

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

    http.formLogin() 
     .loginPage("/login") 
     .permitAll() 
     .failureHandler(customAuthenticationHandler) 
     .and() 
     .logout() 
     .permitAll(); 

    http.authorizeRequests() 
     .antMatchers("/css/**", "/img/**", "/js/**") 
     .permitAll() 
     .anyRequest() 
     .authenticated(); 

    http 
     .csrf() 
     .disable(); 
} 

@Bean 
CustomAuthenticationHandler authenticationHandler() { 
    return new CustomAuthenticationHandler(); 
} 

@Configuration 
protected static class AuthenticationConfiguration extends 
     GlobalAuthenticationConfigurerAdapter { 

    @Override 
    public void init(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication() 
      .withUser("*******") 
      .password("*******") 
      .roles("USER"); 
    } 
} 
} 

的問題是,AuthenticationFailureHandler重定向到/login?error但(我不知道爲什麼)另一個重定向是爲了/login

你能幫我解決我的問題嗎?

+0

你任何機會,在任何時候調用super.onAuthenticationFailure? Spring會因爲某種原因自動執行它嗎? – kaqqao

+1

好吧,我通過向'http.authorizeRequests()添加「/ login **」來解決它。antMatchers(「/ css/**」,「/ img/**」,「/ js/**」)' – smsnheck

+0

哦,所以登錄本身(使用params)是不可訪問的......書中最古老的錯誤:/ – kaqqao

回答

3

嗯,我解決它通過添加「/登錄**」來http.authorizeRequests().antMatchers("/css/**", "/img/**", "/js/**")

相關問題