0

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 had a couple of questions.

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.

My setup is Spring + Angular and PostgreSQL for Database and Hibernate as ORM.

Rohan Sood
  • 178
  • 1
  • 14

2 Answers2

0

Take a look into Spring security framework:

spring security official documentation

Spring security getting started example

Ruben Pirotte
  • 386
  • 2
  • 11
0
  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.

Sundararaj Govindasamy
  • 8,180
  • 5
  • 44
  • 77