0

I am sorry in advance if the question is not build correctly, I would like to store last user login timestamp, not every time user updates the page or switches to another but until the session is closed. How can I approach that?

I have a controller that checks if user allowed to to enter at all

 @GetMapping("/current")
    public ResponseEntity<UserDto> getCurrent() {
        Optional<UserDetails> currentFromSecurity = userSecurityService.getCurrentFromSecurity();
        if (!currentFromSecurity.isPresent()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        } else {
            UserEntity userEntity = currentUser.get();
            return ResponseEntity.ok(new UserDto(userEntity.getPdmUid(), userEntity.getRole().name(), userEntity.isOnlineSystem()));

        }
    }

My configuration

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

private final ApifyAuthConfigurer authConfigurer;
private final PrincipalProvider principalProvider;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors()
            .and()
            .csrf()
            .disable()
            .exceptionHandling()
            .authenticationEntryPoint(new ApifyAuthenticationEntryPoint())
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    authConfigurer.configure(http, principalProvider);
}

My Principal function

public class PrincipalProvider implements UserPrincipalProvider<UserDetails> {

private final UserService userService;

@Override
public Optional<UserDetails> getPrincipal(Claims claims) {
    log.debug("#getPrincipal - {}", claims);
    userService.createIfNotExist(claims);

    return Optional.of(new UserEntity().setPdmUid((Integer) claims.get("pdmUid")));
}

}

okey1992
  • 45
  • 5
  • 1
    Spring security fires events when a logon is succesful and not succesful. You can create an `ApplicationListener` which listens to those events and do whatever you like, like storing the information you want. – M. Deinum Aug 19 '20 at 11:09
  • @M.Deinum yeh i actually found some info about SessionDestroyedEvent currently reading, could you let me know when exactly new token is generated in my case – okey1992 Aug 19 '20 at 11:13
  • 1
    It isn't about the session destroyed it is about an `AuthenticationSuccessEvent` or `InteractiveAuthenticationSuccessEvent`. On a different note, using an `Optional` with an `if/else` and `isPresent` is basically an anti-pattern. Instead use `currentFromSecurity.map(ok-stuff).orElse(error-stuff)`. – M. Deinum Aug 19 '20 at 11:18
  • Maybe this link can help you https://stackoverflow.com/questions/41076500/eventlistener-for-authenticationsuccessevent-or-interactiveauthenticationsucces – doctore Aug 19 '20 at 11:22

0 Answers0