title: spring security manual login best practice
body: <p>I'm using spring security to implement a programmatic, manual user login. I have a scenario where I have positively established the user's identity, and wish to log them in. I don't know their password, and so can't use the regular login code path where you submit a form to a url, which spring intercepts via a servlet <code>Filter</code>, doing all of it's auth+session magic.</p>
  <p>I've searched, and it seems most people create their own <code>Authentication</code> object, and then tell spring about via:</p>
  <pre><code>PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(user, &quot;&quot;, user.getAuthorities());
  SecurityContextHolder.getContext().setAuthentication(authentication);
  </code></pre>
  <p>Indeed, this works. Spring even puts it into the session for me, making subsequent http requests maintain their auth status.</p>
  <p>However, I feel like this is a dirty hack. I'll present some details that I hope will give concrete examples of the problems associated with using <code>setAuthentication()</code> inside a controller to achieve a manual login:</p>
  <p>To give an idea, my config is:</p>
  <pre><code>httpSecurity
      .authorizeRequests()
      .antMatchers(&quot;/test/**&quot;).permitAll()
      .antMatchers(&quot;/admin/**&quot;, &quot;/api/admin/**&quot;).hasRole(&quot;USER_SUPER_ADMIN&quot;)
      .and()
      .formLogin()
      .loginPage(&quot;/sign-in?sp&quot;)
      .loginProcessingUrl(&quot;/api/auth/sign-in&quot;)
      .successHandler(createLoginSuccessHandler())
      .failureHandler(createLoginFailureHandler())
      .permitAll()
      .and()
      .logout()
      .logoutUrl(&quot;/api/auth/sign-out&quot;)
      .logoutSuccessHandler(createLogoutSuccessHandler())
      .and()
      .sessionManagement()
      .maximumSessions(1)
      .maxSessionsPreventsLogin(true)
      .sessionRegistry(sessionRegistry)
  ;
  </code></pre>
  <p>Key points in the above config:</p>
  <ul>
  <li>I use custom success and failure handlers for the form login</li>
  <li>I want to config behavior for max concurrent sessions per user</li>
  <li>I want to maintain spring's default session fixation protection (changing session id upon login).</li>
  <li>I want to use a session registry</li>
  <li>... more of these session/login functionalities, had I chosen to config it.</li>
  </ul>
  <p>I stepped through the code to see how spring processes a form login. As expected, Spring does all the session/login functionalities that my <code>HttpSecurity</code> config told it to do when I use the form login. But, when I do my own custom/manual login via <code>SecurityContextHolder.getContext().setAuthentication()</code>, it does NONE of those functionalities. This is because spring does all of it's session/login functionalities stuff inside of a servlet <code>Filter</code>, and my programmatic code can't really call a Filter. Now, I can attempt to add the missing functionalities myself, duplicating their code: I see that the spring Filter uses: <code>ConcurrentSessionControlAuthenticationStrategy</code>, <code>ChangeSessionIdAuthenticationStrategy</code>, and <code>RegisterSessionAuthenticationStrategy</code>. I can create these objects myself, configure them, and call them after my custom login. But, that's really lame to duplicate all that spring code. Furthermore, there's still other behaviors I'm missing - I noticed that when using the form login code path, that spring triggers some login events which don't get triggered when I do my custom login. And there's probably other stuff that I'm missing or don't understand. The whole process is pretty complicated, and I feel like there's a high chance of introducing bugs if this isn't done right, not to mention that library updates would be a pain if I started duplicating spring code.</p>
  <p>So, I feel like I'm approaching this from the wrong way. <strong>Should I be using a different strategy, so that I'm not bypassing so much of the stuff that spring does for me?</strong> Maybe I should try to make my own <code>AuthenticationProvider</code> to accomplish this custom login?</p>
  <p>*To clarify, my code more or less works. But, I feel like I accomplished it using a poor strategy because I had to write code duplicating a lot of stuff that spring does for me. Further, my code doesn't perfectly replicate what spring does, making me wonder what negative implications might result. There must be a better way to programatically achieve login.</p>