2017-02-11 14 views
2

Я пытаюсь настроить собственные обработчики отказа и проверки подлинности. При ошибке аутентификации я хочу перенаправить обратно на мою страницу входа с параметром запроса, наличие этого параметра выведет сообщение об ошибке на моей странице входа. Однако, хотя по ошибке меня перенаправляют обратно на мою страницу входа, параметр запроса всегда null.Перенаправление отказа аутентификации с параметрами запроса не работает

код ниже:

protected void configure(HttpSecurity http) throws Exception { 
    http 
     .csrf().disable() 
     .authorizeRequests() 
      .antMatchers("/").permitAll() 
      .antMatchers("/login").permitAll() 
      .anyRequest().authenticated() 
      .and() 
     .formLogin() 
      .loginPage("/login.html").permitAll() 
      .usernameParameter("username") 
      .passwordParameter("password")            
      .loginProcessingUrl("/login") 
      .successHandler(successHandler()) 
      .failureHandler(handleAuthenticationFailure()); 
} 

@Autowired 
@Override 
protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    //database checks 
} 
}; 
} 

/** 
* Authentication success handler defines action when successfully authenticated 
* @return 
*/ 
@Bean 
public AuthenticationSuccessHandler successHandler(){ 
    return new AuthenticationSuccessHandler() { 

     @Override 
     public void onAuthenticationSuccess(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Authentication authentication) 
       throws IOException, ServletException { 

      // custom auth success here 
      httpResponse.setStatus(HttpServletResponse.SC_OK); 
      SavedRequest savedRequest = (SavedRequest) httpRequest.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"); 
      httpResponse.sendRedirect(savedRequest.getRedirectUrl()); 
     } 
    }; 
} 

@Bean 
public AuthenticationFailureHandler handleAuthenticationFailure() { 
    return new SimpleUrlAuthenticationFailureHandler() { 

     @Override 
     public void onAuthenticationFailure(HttpServletRequest httpRequest, HttpServletResponse httpResponse, 
              AuthenticationException authenticationException) throws IOException, ServletException { 

      // custom failure code here 
      setDefaultFailureUrl("/login.html?error=fail"); 
      super.onAuthenticationFailure(httpRequest, httpResponse, authenticationException); 
     } 
    }; 
} 
+1

Как вы получаете из параметров? Не могли бы вы проследить сеть, чтобы узнать, запрашивается ли url с 'error = fail'? – chaoluo

ответ

2

Попробуйте с этим:

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

    // ....... 

    response.sendRedirect("/login.html?error=fail");  
} 

Update:

Это очень важно, что "/login.html?error=fail" добавлен в разделе authorizeRequests(), иначе контроллер не будет отображать параметр ошибки.

Заменить .antMatchers("/login").permitAll() с .antMatchers("/login**").permitAll()

0

была также проблема с Params (в моем случае, когда Логин было не удалось, и некоторые запрос PARAMS был добавлен к URL он перенаправляется на страницу входа без Params).

Это решило мою проблему

.antMatchers("/login**").permitAll() 

 Смежные вопросы

  • Нет связанных вопросов^_^