title: Unit testing with Spring Security
body: <p>My company has been evaluating Spring MVC to determine if we should use it in one of our next projects. So far I love what I've seen, and right now I'm taking a look at the Spring Security module to determine if it's something we can/should use. </p>
  
  <p>Our security requirements are pretty basic; a user just needs to be able to provide a username and password to be able to access certain parts of the site (such as to get info about their account); and there are a handful of pages on the site (FAQs, Support, etc) where an anonymous user should be given access.</p>
  
  <p>In the prototype I've been creating, I have been storing a "LoginCredentials" object (which just contains username and password) in Session for an authenticated user; some of the controllers check to see if this object is in session to get a reference to the logged-in username, for example. I'm looking to replace this home-grown logic with Spring Security instead, which would have the nice benefit of removing any sort of "how do we track logged in users?" and "how do we authenticate users?" from my controller/business code. </p>
  
  <p>It seems like Spring Security provides a (per-thread) "context" object to be able to access the username/principal info from anywhere in your app...</p>
  
  <pre><code>Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  </code></pre>
  
  <p>... which seems very un-Spring like as this object is a (global) singleton, in a way.</p>
  
  <p>My question is this: if this is the standard way to access information about the authenticated user in Spring Security, what is the accepted way to inject an Authentication object into the SecurityContext so that it is available for my unit tests when the unit tests require an authenticated user?</p>
  
  <p>Do I need to wire this up in the initialization method of each test case?</p>
  
  <pre><code>protected void setUp() throws Exception {
      ...
      SecurityContextHolder.getContext().setAuthentication(
          new UsernamePasswordAuthenticationToken(testUser.getLogin(), testUser.getPassword()));
      ...
  }
  </code></pre>
  
  <p>This seems overly verbose. Is there an easier way? </p>
  
  <p>The <code>SecurityContextHolder</code> object itself seems very un-Spring-like...</p>