title: Authentication token passed to ControllerAdvice is null when running through MockMvc
body: <p>I am using Spring Boot 1.3, Spring 4.2 and Spring Security 4.0. I am running integration tests using MockMvc, for example:</p>
  
  <pre><code>mockMvc = webAppContextSetup(webApplicationContext).build();
  MvcResult result = mockMvc.perform(get("/"))
              .andExpect(status().isOk())
              .etc;
  </code></pre>
  
  <p>In my tests I am simulating a user login like this:</p>
  
  <pre><code>CurrentUser principal = new CurrentUser(user);
  Authentication auth =
                  new UsernamePasswordAuthenticationToken(principal, "dummypassword",
                      principal.getAuthorities());
  
  SecurityContextHolder.getContext().setAuthentication(auth);
  </code></pre>
  
  <p>This works fine for my methods that are annotated with <code>@PreAuthorize</code>, for example when calling a method like this from a test:</p>
  
  <pre><code>@PreAuthorize("@permissionsService.canDoThisThing(principal)")
  public void mySecuredMethod()
  </code></pre>
  
  <p>the principle, my CurrentUser object, is non-null in <code>PermissionsService#canDoThisThing</code>.</p>
  
  <p>I have a class annotated with @ControllerAdvice that adds the currently logged-in user to the model so it can be accessed in every view:</p>
  
  <pre><code>@ControllerAdvice
  public class CurrentUserControllerAdvice {
      @ModelAttribute("currentUser")
      public CurrentUser getCurrentUser(Authentication authentication) {
          if (authentication == null) {
              return null;
          }
  
          return (CurrentUser) authentication.getPrincipal();
      }
  }
  </code></pre>
  
  <p>This works fine when running the application, however (and this is my problem) - when running my tests the authentication parameter passed in to the getCurrentUser method above is always null. This means any references to the currentUser attribute in my view templates cause errors, so those tests fail.</p>
  
  <p>I know I could get round this by retrieving the principle like this:</p>
  
  <pre><code>authentication = SecurityContextHolder.getContext().getAuthentication();
  </code></pre>
  
  <p>but I would rather not change my main code just so the tests work.</p>