Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Basic Authentication without Session (Stateless Session)

I have configured Basic Authentication my Spring-Boot application. Everything is Java Config, no xml.

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // Authenticate username -> admin, password -> admin & set role as "ROLE_USER"
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/login").permitAll()
            // All Requests should be Authenticated
            .anyRequest().authenticated()
            .and()
            // Enable Basic Authentication
            .httpBasic()
            .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/main", true)
                .loginProcessingUrl("/session")
                .usernameParameter("Username").passwordParameter("Password")
            .and()
            .logout().logoutUrl("/logout").permitAll()
            .and().csrf().disable();
    }

}

It's configured for both Basic authentication and normal form login. When I tested the basic authentication from Rest-Client on Firefox, I can access the secure url "/main". But in the response headers, I'm getting Set-Cookie: JSESSIONID=301225C7AE7C74B0892887389996785D;.

I don't want cookies to be generated for basic authentication. I want true Stateless session for Basic Authentication. Do note that I need cookies to be generated for form-login to work, so disabling cookies is not an option. I know about the create-session="stateless" in xml configuration, but is there any way to do the same in Java config so that Basic Authentication is Stateless and Form-Authentication is Statefull..?

like image 964
The Coder Avatar asked Jun 14 '16 19:06

The Coder


People also ask

What is stateless session in Spring boot?

But if the application creates one, Spring Security will make use of it. Finally, the strictest session creation option, “stateless“, is a guarantee that the application won't create any session at all.

Is WebSecurityConfigurerAdapter deprecated?

From Spring Boot 2.7, WebSecurityConfigurerAdapter is deprecated.

What is stateless and stateful in Spring boot?

Stateful expects a response and if no answer is received, the request is resent. In stateless, the client sends a request to a server, which the server responds to based on the state of the request. Design complexity. This makes the design heavy and complex since data needs to be stored.


1 Answers

For anyone else that comes across this, here's something else to check.

I was hitting this same problem with Spring Boot and even with

   sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

I was still seeing JSESSIONID cookies being set. In my case (using JWT), the missing piece seemed to be setting setAllowSessionCreation on the HttpSessionSecurityContextRepository object, like this:

    public class StatelessAuthenticationFilter extends GenericFilterBean {
        private final MyTokenAuthService authenticationService;
        private SecurityContextRepository repository = new HttpSessionSecurityContextRepository();
        protected final Logger logger = LoggerFactory.getLogger(getClass().getName());

        public StatelessAuthenticationFilter(MyTokenAuthService authenticationService) {
            this.authenticationService = authenticationService;
            ((HttpSessionSecurityContextRepository) repository).setAllowSessionCreation(false);
        }
     }

What pointed me this were these lines in HttpSessionSecurityContextRepository:

private boolean allowSessionCreation = true;
like image 190
MattW Avatar answered Sep 20 '22 03:09

MattW