【发布时间】:2018-07-27 06:35:15
【问题描述】:
我正在使用 Spring Boot 开发一个小应用程序。我的问题是,当用户正确验证时,我需要显示用户的 First name。每次身份验证(每次登录 - 输入用户名和密码)都会正确显示 名字。但是,如果我们在会话超时之前关闭浏览器并再次打开它不输入用户名和密码,则不会显示名字。
我通过身份验证时的配置
@Component
public class SecurityHandler implements AuthenticationSuccessHandler{
@Autowired
private UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
HttpSession session = request.getSession();
String userName = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
userName = ((UserDetails) principal).getUsername();
} else {
userName = principal.toString();
}
User user = userService.findBySSO(userName);
session.setAttribute("userName", user.getFirstName());
response.sendRedirect(request.getContextPath()+"/dashboard/index");
}
}
安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
//Autowired
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers() // antmachers
.and().formLogin().loginPage("/login").successHandler(securityHandler).loginProcessingUrl("/login").usernameParameter("ssoId").passwordParameter("password")
.and().rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
.tokenValiditySeconds(86400).and().csrf().and().exceptionHandling().accessDeniedPage("/Access_Denied")
.and()
.sessionManagement().invalidSessionUrl("/login").maximumSessions(1).expiredUrl("/login").and().sessionAuthenticationErrorUrl("/login").sessionFixation().migrateSession()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
http.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.invalidateHttpSession(true)
.permitAll();
}
}
会话监听器
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent event) {
event.getSession().setMaxInactiveInterval(-1);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
}
}
我提到了Java:Why http session is not destroyed when tab or browser is closed?,因为他们说我尝试使用JavaScript通过onunload事件调用注销,但它不起作用。很少有教程说它的工作取决于浏览器设置。
最后,如果他使用任何方法进入网站,我需要显示用户的名字。
【问题讨论】:
-
你使用 Spring Session 吗?问题标记为
spring-session,但您提供的代码 sn-ps 没有证据表明您确实使用了 Spring Session。如果有,请提供相关配置。
标签: spring spring-mvc spring-boot spring-security spring-session