title: Handle OAuth2 callback in Spring Boot
body: <p>I am trying to build a Spring Boot project with requires being signed into an OAuth2 SSO.
  I have the following Maven dependencies:</p>
  
  <pre><code>org.springframework.boot:spring-boot-starter-web
  org.springframework.security:spring-security-oauth2-client
  org.springframework.security:spring-security-config
  </code></pre>
  
  <p>I use <code>HttpSecurity</code> to enforce OAuth2 authentication for the app, using the following:</p>
  
  <pre><code>@EnableWebSecurity
  @Order(101)
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .authorizeRequests()
              .antMatcher("/api/auth/oauth2/callback").permitAll()
              .anyRequest().authenticated()
              .and()
              .oauth2Login();
      }
  
  }
  </code></pre>
  
  <p>Now, what this does is: it sees that the user is not logged in, redirects them to the SSO, and after they have signed in it redirects the user back to the <code>/api/auth/oauth2/callback?code=...&amp;state=...</code> endpoint. That all works fine. However, I am fairly new to Spring Boot and I don't understand how I persist the fact the user is now authenticated (I know I still need to validate the callback, that's not a problem).</p>
  
  <p>Here is the authentication model that I would like to implement: I want to generate a hash within the callback endpoint, and store that hash in-memory within the app, and as a cookie on the user's browser. Then, in any subsequent requests, the app would read that cookie's value, find the row in the in-memory database with the hash in it and grab the corresponding user data from the  database row.</p>
  
  <p>I have looked <em>extensively</em> for a good example of this, however, all of the Spring Boot based OAuth2 examples use Github/Google OAuth and it seems to handle a lot of stuff under the hood (or perhaps I'm not understanding those properly).</p>
  
  <p>Any help/guidance would be greatly appreciated!</p>
  
  <p>In case it helps, here is my <code>application.yml</code> file:</p>
  
  <pre><code>spring:
    security:
      oauth2:
        client:
          registration:
            custom_sso_name:
              clientId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
              clientSecret: SUPER_SECRET
              authorizationGrantType: authorization_code
              redirectUri: https://dev.localhost/api/auth/oauth2/callback
          provider:
            custom_sso_name:
              userInfoUri: https://sso.example.com/nidp/oauth/nam/userinfo
              authorizationUri: https://sso.example.com/nidp/oauth/nam/authz
              tokenUri: https://sso.example.com/nidp/oauth/nam/token
              preferTokenInfo: false
  </code></pre>