title: spring Authentication.setAuthenticated(boolean) java.lang.IllegalArgumentException: Cannot set this token to trusted
body: <p>I have the following code (attempting to log a user in programatically):</p>
  
  <pre><code>List&lt;GrantedAuthority&gt; authorities = new ArrayList&lt;GrantedAuthority&gt;();
  authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
  ...
  User tempUser = new User(correctUsername, 
      correctPassword, 
      true, true, true, true, // logging them in...
      authorities // type is List&lt;GrantedAuthority&gt;
  );
  ...
  Authentication authentication 
      = new UsernamePasswordAuthenticationToken(tempUser, authorities);
      // I'm using authorities again (List&lt;GrantedAuthority&gt;)
      // is this the right spot for it?
  ...
  // this is the line causing the error
  authentication.setAuthenticated(true);
  </code></pre>
  
  <p>When I try to run that I get the following:</p>
  
  <pre><code>java.lang.IllegalArgumentException: Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead
  </code></pre>
  
  <p>Note that I'm using the <code>authorities</code> list of <code>GrantedAuthority</code>s both in the <a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/core/userdetails/User.html" rel="noreferrer"><code>User</code></a> and <a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/core/Authentication.html" rel="noreferrer"><code>Authentication</code></a> objects.  I'm not sure where I should be using those.  I'm trying to replicate the answer for <a href="https://stackoverflow.com/questions/2466312/authenticate-user-manually">another SO question</a> but am running into the exception posted above.  Other similar questions that didn't quite answer my question:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/7614541/">How to programmatically log user in with Spring Security 3.1</a></li>
  <li><a href="https://stackoverflow.com/questions/7900994/">Programmatically login in a user using spring security</a></li>
  </ul>
  
  <p>After some searching the closest I've found to an answer was at <a href="http://forum.springsource.org/showthread.php?69761-User-registers-confirmation-email-account-activated-user-logged-in-automatically" rel="noreferrer">the forum at springsource.org</a>, and that person's using a <a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/core/userdetails/User.html#User%28java.lang.String,%20java.lang.String,%20boolean,%20boolean,%20boolean,%20boolean,%20org.springframework.security.core.GrantedAuthority%5B%5D%29" rel="noreferrer">deprecated method</a>, but it's a similar approach.  How can I log a user in programatically?</p>