Rohan Sood Rohan Sood - 7 months ago 100
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.

  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;

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.

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

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

    SecurityContextImpl springSecurityContext = (SecurityContextImpl)session.getAttribute("SPRING_SECURITY_CONTEXT");
        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.