2015-09-05 2 views
0

У меня есть одно приложение с весной 4 с весной безопасности для аутентификации и весенняя сессия для обмена сеансом по кластерной среде.Сессия Spring, хранящаяся по DB + Spring, проверяет подлинность, кластеризованное окружение

Я реализовал SessionRepository из сеанса Spring, чтобы сохранить сеанс в базе данных, поэтому, когда я вхожу на сеанс весны, создайте cookie с именем «SESSION» и сохраните его в БД.

Идея реализации этого сеанса БД здесь:

How can I do relational database-based HTTP Session Persistence in Spring 4?

На данный момент у меня есть одно печенье «SESSION». Когда я вхожу на сайт, весна безопасности создает еще один файл cookie «JSESSION», но это не хранится в БД, и этот файл cookie имеет «идентификационную информацию».

Мой вопрос: эта реализация правильна для кластерной среды? или мне нужно сделать еще одну модификацию?

Заранее спасибо.

EDIT 2:

Недавно я проверить мое приложение, я и сделать одну ошибку над моим объяснением, когда я вхожу на сайт У меня есть один печенье «SESSION», даже если я войти в «Сессия» куки кадры, но нет другого файла cookie, если я очищу таблицу сеанса и обновить сайт, на котором пользователь выполнил регистрацию. Это правильное поведение?

EDIT:

Вот мой "настроить" от SecurityConfig (простираются от WebSecurityConfigurerAdapter).

@Override 
protected void configure(final HttpSecurity http) throws Exception { 
    // @formatter:off 
    http 
     //.csrf().disable() 
     .authorizeRequests() 
     .antMatchers(
       "/login*", 
       "/logout*", 
       "/forgotPassword*", 
       "/user/initResetPassword*", 
       "/user/resetPassword*", 
       "/admin/saveConfiguration", 
       "/resources/**" 
     ).permitAll() 
     .antMatchers("/invalidSession*").anonymous() 
     .anyRequest().authenticated() 
    .and() 
     .formLogin() 
     .loginPage("/login.html") 
     .loginProcessingUrl("/login") 
     .defaultSuccessUrl("/homepage.html") 
     .failureUrl("/login.html?error=true") 
     .successHandler(myAuthenticationSuccessHandler) 
     .usernameParameter("username") 
     .passwordParameter("password") 
     .permitAll() 
    .and() 
     .addFilterBefore(this.sessionSessionRepositoryFilter, ChannelProcessingFilter.class) 
     .sessionManagement() 
     .invalidSessionUrl("/login.html") 
     .sessionFixation() 
     .migrateSession() 
    .and() 
     .logout() 
     .invalidateHttpSession(false) 
     .logoutUrl("/vu_logout") 
     .logoutSuccessUrl("/logout.html?ls=true") 
     .deleteCookies("JSESSION") 
     .logoutSuccessHandler(mySimpleUrlLogoutSuccessHandler) 
     .permitAll(); 
    // @formatter:on 
} 

Вот мой Логин обработчик успеха:

@Component("myAuthenticationSuccessHandler") 
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { 
private final Logger LOGGER = LoggerFactory.getLogger(getClass()); 

private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); 

public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { 
    handle(request, response, authentication); 
    HttpSession session = request.getSession(false); 

    if (session != null) { 
     session.setMaxInactiveInterval(60 * 10); 
    } 
    clearAuthenticationAttributes(request); 
} 

protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { 
    String targetUrl = determineTargetUrl(authentication); 

    if (response.isCommitted()) { 
     return; 
    } 

    redirectStrategy.sendRedirect(request, response, targetUrl); 
} 

protected String determineTargetUrl(Authentication authentication) { 
    boolean isUser = false; 
    boolean isAdmin = false; 
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); 
    for (GrantedAuthority grantedAuthority : authorities) { 
     if (grantedAuthority.getAuthority().equals("OPER") || grantedAuthority.getAuthority().equals("AUDITOR")) { 
      isUser = true; 
     } else if (grantedAuthority.getAuthority().equals("ADMIN")) { 
      isAdmin = true; 
      isUser = false; 
      break; 
     } 
    } 

    if(isUser || isAdmin) 
    { 
     return "/home.html"; 
    } 
    else 
    { 
     throw new IllegalStateException(); 
    } 
} 

protected void clearAuthenticationAttributes(HttpServletRequest request) { 
    HttpSession session = request.getSession(false); 
    if (session == null) { 
     return; 
    } 
    session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); 
} 

public void setRedirectStrategy(RedirectStrategy redirectStrategy) { 
    this.redirectStrategy = redirectStrategy; 
} 

protected RedirectStrategy getRedirectStrategy() { 
    return redirectStrategy; 
} 

}

ответ

0

Через несколько дней на исследования и тестирование этой реализации правильно работать над кластерной окружающей средой.

Если кому нужен образец проекта Мати имеет один над хранилище GitHub: https://github.com/Mati20041/spring-session-jpa-repository

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