我有一個使用 Session 的非常基本的 Spring Security 設置。我的問題是我找不到使用任何類型的會話偵聽器(Spring 和 Servlet API 版本)來偵聽 SessionCreated 事件的方法。登錄正在工作並且會話正在正確創建。
我需要偵聽器的原因是因為我想初始化某些會話屬性(例如購物卡丁車、最近商品列表),以便我可以從@Controller
請求映射中無縫訪問它們,而不必擔心會話屬性是否已初始化。
安全配置代碼:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
.and()
.authorizeRequests()
.antMatchers("/secured/**").authenticated()
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/login")
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.and()
.rememberMe().key("unique");
}
...
}
首先,我嘗試了最基本的會話偵聽器:
@Component
public class InitHttpSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
...
}
}
我也試過這裡的答案,但也沒有用
從您的評論中可以清楚地看出,您正在使用Spring Session JDBC。由於 JDBC 的性質,它不支持會話事件的發布,因此您無法偵聽這些事件。
作為一種解決方法,您可以創建自己的AuthenticationSuccessHandler
並將用於填充的邏輯Session
放在那裡。或者AuthenticationSuccessEvent
使用 Spring 事件偵聽器收聽(進入會話會有點困難,但可行)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句