0
votes

Is it possible to have Token based (stateless) authentication along side traditional cookie / JSESSION based authentication?

Scenario:

Application already has an existing Spring MVC + Thymeleaf implementation that serves as the administration / super user portal. When you login you get a JESSIONID. We need to create an RESTful API using Jersey (JAX-RS) for client consumption. It is required to be stateless. Essentially we still need the Spring MVC + Thymeleaf piece but now need to expose an API for consumption that uses stateless authentication. Is this possible with Spring Security?

1

1 Answers

2
votes

Spring Security supports multiple configurations in the same application. For example, assume the stateless service is completely located under the URL /api/. You could use the following outline for XML based configuration:

<http pattern="/api/**" create-session="stateless">
    <intercept-url pattern="/**" access="hasRole('ADMIN')" />
    <http-basic />
</http>

<http>
    <intercept-url pattern="/**" access="authenticated" />
    <form-login login-page="/login" default-target-url="/home.htm"/>
    <logout />
</http>

or the following for Java Configuration:

@EnableWebSecurity
public class MultiHttpSecurityConfig {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) { 1
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
    }

    @Configuration
    @Order(1)                                                        2
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/api/**")                               3
                .authorizeRequests()
                    .anyRequest().hasRole("ADMIN")
                    .and()
                .httpBasic();
        }
    }

    @Configuration                                                   4
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                .formLogin();
        }
    }
}