kemal89
kemal89

Reputation: 961

Spring Security Logout From Stateless server

I am creating a stateless REST API with spring boot. Therefore I am using a token based authentication.

Currently the logout functionality is only implemented on the client side. I just clear all cookies.

Problem is that the user object seems to survive the request so it still exists in the next requests. My service to get the current user is simply:

@Service
public class UserService {
  private User user;

  @Autowired
  private UserRepository;

  public User get() {
    if (user != null) {
      return user;
    }
    Integer id = (Integer) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    user = userRepository.findById(id);
    return user;
  }
}

I would expect that the user variable is null on every request? The funny thing is that the correct user id is set in the security context. But the service returns the user object because it already exists.

Upvotes: 0

Views: 818

Answers (1)

desoss
desoss

Reputation: 622

You shouldn't use user as a class attribute.

UserService is a singleton, what happens when you have concurrent requests coming from different users? Move this variable inside the get method.

Moreover, if you are using JWT as the token based authentication take a look at this project.

With JWT you can retrieve the user required informations directly from the token without performing any queries.

Upvotes: 1

Related Questions