Question

I have following method in my Spring application

public static String getCurrentUserStudentId() {
    return ((LdapPerson) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getID();
}

This works on the application run, but when I run a test calling this method, it gives

org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken cannot be cast to fi.utu.security.ldap.userdetails.LdapPerson

I'm not that familiar with Spring Security to give all the files this could be related, but ask me. I hope someone can tell what to do with this.

Était-ce utile?

La solution

SecurityContextHolder keeps a reference to a "strategy" in a static variable which means that this detail leaks from test to test.

You have several options:

  1. In your test, set the correct strategy using one of the setters of SecurityContextHolder

  2. Create a mock implementation for getCurrentUserStudentId which returns a fixed result for the test.

  3. Put the code to get the current user id into a bean and inject that instead of calling SecurityContextHolder. Implement two versions of this bean: One which calls SecurityContextHolder and another which returns a string.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top