2

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
varman
  • 8,704
  • 5
  • 19
  • 53
  • Do you use Spring Session? Question is tagged with `spring-session` but there's no evidence from the code snippets you provided that you actually do use Spring Session. If you do, please provide relevant configuration. – Vedran Pavic Mar 02 '18 at 13:23

2 Answers2

0

Your session listener should be a bean I believe

Could you try this:

@WebListener
public class SessionListener implements HttpSessionListener{

@Override
public void sessionCreated(HttpSessionEvent se) {
    System.out.println("Session created");
}

@Override
public void sessionDestroyed(HttpSessionEvent se) {
    System.out.println("session Destroyed");
}

}

mwangii
  • 11
  • 2
0

You should make access to the web page that includes the first name of the user limited to only those authorized ,your user after closing the browser IS logged out since you don't see their first name.
you understood the problem wrongfully thus not getting the correct way to do your research. hope this helps

MrMisery
  • 406
  • 7
  • 19