title: Spring Security OAuth2 Login using External Login Page
body: <p>I'm wondering if it's possible to configure Spring Security to use an externally hosted login page during the OAuth login process.  Nevermind that this is not a good idea and defeats one of the purposes of OAuth (separating login / credentials / auth concerns from clients and resource servers).</p>
  
  <p>I have the following setup:</p>
  
  <ul>
  <li>A client SPA application, where the login page I want to use resides</li>
  <li>An OAuth Auth server (using Spring Security OAuth / <code>@EnableAuthorizationServer</code>)</li>
  <li>One or more OAuth resource servers</li>
  </ul>
  
  <p>The OAuth flow that I seek is as follows:</p>
  
  <ul>
  <li>User attempts to access a secured route in the SPA</li>
  <li>Client redirects user to OAuth server's authorize page (with parameters including state, nonce, etc)</li>
  <li>OAuth server detects no token and redirects to SPA's login page</li>
  <li>User logs in; posts to login url (login url lives on the OAuth server; CORS configuration required to allow cross-origin post from SPA to OAuth server)</li>
  <li>Login successful; Spring redirects to the originally requested authorize page with parameters that were originally present</li>
  <li>authorize redirects to token; user gets token; SPA detects that user now has a token and allows access to the secured route</li>
  </ul>
  
  <p>I'm able to configure Spring Security to specify an absolute url in order to make the redirect to my SPA's login page happen:</p>
  
  <pre><code>@Override
  protected void configure(HttpSecurity http) throws Exception {
      http.cors()
          .and()
          ... config ...
          .and()
          .formLogin()
          .loginPage("http://angular-spa-app/login") 
          .loginProcessingUrl("/login")
          .permitAll();
  }
  </code></pre>
  
  <p>When I go through this flow, I see the first request made to <code>oauth/authorize?state=...&amp;nonce=...&amp;etc...</code>, then the redirect to <code>http://angular-spa-app/login</code>.  But when I login, Spring is unable to detect that it should redirect to back to the <code>oauth/authorize</code> url that was saved in the session.</p>
  
  <p>Digging in to this further, I discovered that when the first request to <code>oauth/authorize</code> is made, the full url with params is saved in the session (<code>HttpSessionRequestCache.saveRequest(...)</code>.</p>
  
  <p>When the login form is submitted and authentication is successful, Spring attempts to retrieve the saved request in order to get the redirect url to send as the 302 Location header.  But when it does this, the session is null and therefore Spring cannot retrieve any saved request.  Why is this?  Do I need to modify Spring session settings in order to work around this?</p>