Search code examples
springspring-securityspring-security-oauth2

Why does setting sessioncreation policy to stateless break my oauth2 app


@Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

Why does setting SessionCreationPolicy to STATELESS break oauth2 login? After authenticating with facebook, the app goes on a never ending loop that eventually leads to "localhost redirected you too many times".

The loop goes like this:

  1. Authenticate with facebook and redirect to:
  2. Redirect-Uri - //login/oauth2/code/facebook?code=&state=
  3. Back to facebook authorization-Uri - /oauth2/authorization/facebook
  4. Repeat

This all happens with the SessionCreationPolicy being STATELESS. Can someone explain to my why this happens?


Solution

  • That's expected behavior. OAuth2 Clients need to store the tokens somehow for using them in later requests. By using a stateless session creation policy, every time you call the application, it won't find any token (i.e. it doesn't know you've already authenticated yourself in the previous request), so it will trigger again the authentication flow.

    On the other hand, OAuth2 Resource Servers can be stateless, since they don't rely on any session state. Every request sent to an OAuth2 Resource Server from an OAuth2 Client provides an Access Token in the HTTP request header (which is possible because the client stores the tokens in the session).