I'm using Spring Boot for developing a small app. My problem is, I need to show the First name of user when a user authenticated correctly. Every authentication (every login - entering username and password) it shows the First name correctly. But if we close the browser and reopen it again before session time-out without entering username and password, First name isn't shown.
My confing when authenticated
@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");
}
}
Security config
@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();
}
}
Session listner
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent event) {
event.getSession().setMaxInactiveInterval(-1);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
}
}
I referred Java:Why http session is not destroyed when tab or browser is closed?, as they said I tried to use JavaScript to call logout through onunload event, but it does not work. few tutorials say that its working depend on the browser setting.
Finally anyhow I need to show the firstname of user if he users any method to enter into the site.