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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

how do i generate tokens for login and do i track them using spring or angular?
0

Take a look into Spring security framework:

spring security official documentation

Spring security getting started example

2 Comments

any way to do it in angular? have any more links for examples?
For spring security you will have to define a login form (which is an html file), so yes, inside this page you can use angular.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.