Rohan Sood Rohan Sood - 5 months ago 83
AngularJS Question

Manage user logged in sessions in Spring MVC + AngularJS

I was making an application with Spring which is providing the backend with the REST Api's and Angular managing the views part of the Application.

I was thinking of maintaining a sessions in the app so that I can track the logged in Users and also know when they logout and other things.
Moreover the Api's should be authenticated using token.
Is this possible with Spring + Angular?
I am using PostgreSQL for the Database and Hibernate as an ORM for accessing the database.

Answer
  1. To track login - You need to define a Spring Bean which implements org.springframework.context.ApplicationListener.

Then, in your code, do something like this:

import org.springframework.context.ApplicationListener;

@Component
public class myLoginListener implements ApplicationListener<ApplicationEvent> {

public void onApplicationEvent(ApplicationEvent appEvent)
{
    if (appEvent instanceof AuthenticationSuccessEvent)
    {
        AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;
        UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();

        //track the logged in Users here ....
    }
}

2.To track logout - write a listener by implementing HttpSessionListener and use Spring Security as below..

sessionDestroyed() will be called just before the session is going to destroyed.

@Component
public class mySessionListener implements javax.servlet.http.HttpSessionListener{

   @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();

    SecurityContextImpl springSecurityContext = (SecurityContextImpl)session.getAttribute("SPRING_SECURITY_CONTEXT");
    if(springSecurityContext!=null){
        Authentication authentication = springSecurityContext.getAuthentication();
        LdapUserDetails userDetails = (LdapUserDetailsImpl)authentication.getPrincipal();
     //track user logout here

}
...

You can refer this tutorial - Secure AnugularJS applications with spring security

and this tutorial from the official site.