1

In my application, when a user updates their username, I want to clear that authentication from the security context because the old username was used in basic auth calls.

In my controller doing the update, this is easy enough with

SecurityContextHolder.getContext().setAuthentication(null);

But I'm looking for a way to access the current security context without using static methods for ease of unit testing (not to mention the static call doesn't seem very "springy").

The answer here looks pretty close to what I'm looking for, but I'm hoping there's a way to do this without writing a wrapping class. I also tried to inject SecurityContextHolderStrategy into my controller constructor (as was implied I might be able to do in that answer and the related jira) and there was no bean defined of that type.

So: Is there a way to access the current SecurityContext in a Spring Controller without using SecurityContextHolder static methods?

My version of spring security is 3.2.5.RELEASE.

Community
  • 1
  • 1
Jason
  • 7,356
  • 4
  • 41
  • 48
  • Not afaik. Also why would it be bad, in your test you can also test this (there is even a nice mock for that) and you are explictly writing this for Spring Security so trying to hide that fact is bad imho. – M. Deinum Dec 11 '14 at 17:50
  • I agree that we should be clear about what we're doing, but I'm not sure what you mean about how to test this. What is this nice mock of which you speak, and how would you use it if you have a static call? Are you talking about PowerMock? – Jason Dec 11 '14 at 18:01
  • Regarding testing setup your pre-conditions correctly. Just set the context before running your tests (in a `@Before` annotated method). There is a `TestingAuthenticationToken` you can use for this, which you can set yourself in a `SecurityContextImpl` which you set using the `setContext` method. That way you have setup your preconditions nicely, make sure you call `SecurityContextHolder.clearContext()` in a `@After` annotated method. Just to be sure. – M. Deinum Dec 11 '14 at 18:44
  • Maybe this helps: http://stackoverflow.com/questions/8764545/how-to-get-active-users-userdetails – holmis83 Dec 11 '14 at 20:32
  • You mean use an argument resolver to obtain the SecurityContext statically but inject it at the controller method level? Interesting approach... – Jason Dec 11 '14 at 20:45

0 Answers0