2017-01-11 3 views
0

Я продлил WebSecurityConfigurerAdapter весной-безопасности 4.1.3 для входа на мой сайт. Вот мой метод настройкиSpring WebSecurityConfigurerAdapter login не работает несколько раз перед началом работы

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); 
    successHandler.setDefaultTargetUrl("/index"); 
    http 
     .authorizeRequests() 
      .antMatchers("/register", "/registerattempt", "/registeractivate").permitAll() 
      .antMatchers("/assets/**", "/images/**", "/favicon**", "/min/**").permitAll() 
      .anyRequest().hasRole("USER") 
      .and() 
     .formLogin() 
      .loginPage("/login") 
      .failureUrl("/login?error") 
      .permitAll() 
      .successHandler(successHandler) 
      .and() 
     .logout() 
      .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET")) 
      .deleteCookies("JSESSIONID") 
      .invalidateHttpSession(true) 
      .logoutSuccessUrl("/login") 
      .and() 
     .exceptionHandling() 
      .accessDeniedHandler(new CustomAccessDeniedHandler()); 
} 

Моя форма использует действие thymeleaf размещать как этот

<form id="loginform" role="form" th:action="@{/login}" 
         method="post"> 

Я на самом деле не есть метод POST контроллера сопоставлен /login в моем коде, только WebSecurityConfigurerAdapter. Когда я попытаюсь войти в систему, он просто перезагрузит страницу входа в систему 2 или 3 раза, я нажму кнопку входа, а /loginPOST будет иметь код состояния 302 в сетевом журнале, а также будет 200 GET для /login. Затем третий или четвертый раз он будет работать, и все равно будет 302 для /loginPOST, но он будет GET мой index.html.

Это происходит только в том случае, если я вхожу в систему в первый раз за время, если я вхожу в систему и выхожу из системы снова и снова, журнал всегда работает нормально. Я использую redis для хранения сеанса. Почему требуется несколько попыток входа в систему?

Единственное различие, которое я вижу в заголовке ответа является

Location:http://localhost:8090/index 

, когда он работает и

Location:http://localhost:8090/login 

, когда он не работает

Update Журналы отладочные очень многословный, но я вижу это в журналах, когда он терпит неудачу, которого нет, когда он работает

13 Jan 2017 20:20:58.923 [http-nio-8090-exec-8] DEBUG org.springframework.security.web.csrf.CsrfFilter - Invalid CSRF token found for http://localhost:8090/login 

Вот отрывок, когда он не

13 Jan 2017 20:20:58.923 [http-nio-8090-exec-8] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists 
13 Jan 2017 20:20:58.923 [http-nio-8090-exec-8] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created. 
13 Jan 2017 20:20:58.923 [http-nio-8090-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /login at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter' 
13 Jan 2017 20:20:58.923 [http-nio-8090-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /login at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter' 
13 Jan 2017 20:20:58.923 [http-nio-8090-exec-8] DEBUG org.springframework.security.web.csrf.CsrfFilter - Invalid CSRF token found for http://localhost:8090/login 
13 Jan 2017 20:20:58.923 [http-nio-8090-exec-8] DEBUG org.springframework.security.web.header.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.se[email protected]1f8411e9 
13 Jan 2017 20:20:58.923 [http-nio-8090-exec-8] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 
13 Jan 2017 20:20:58.931 [http-nio-8090-exec-8] DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed 

И когда он работает

13 Jan 2017 20:25:44.244 [http-nio-8090-exec-5] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT 
13 Jan 2017 20:25:44.244 [http-nio-8090-exec-5] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.springframework.session.web.http.SessionRepo[email protected]3e3a840e. A new one will be created. 
13 Jan 2017 20:25:44.244 [http-nio-8090-exec-5] DEBUG org.springframework.security.web.FilterChainProxy - /login at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter' 
13 Jan 2017 20:25:44.244 [http-nio-8090-exec-5] DEBUG org.springframework.security.web.FilterChainProxy - /login at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter' 
13 Jan 2017 20:25:44.244 [http-nio-8090-exec-5] DEBUG org.springframework.security.web.FilterChainProxy - /login at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter' 
+0

Я не вижу ничего другого в журналах браузера или сервера после создания этого изменение. Что я должен искать? – gary69

+0

попытайтесь удалить ваш successHandler.setDefaultTargetUrl ("/ index"); – Boldbayar

+0

Это происходит, когда я удаляю объект successHandler и вместо этого использую defaultSuccessUrl ("/ index") – gary69

ответ

-1

Try добавление входа-обработки-URL на свой HTTP экземпляр (HttpSecurity):

.loginProcessingUrl("/login") 
+0

Это не сработало – gary69

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