Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make every request https in spring security 3.2

I am using spring security 3.2 using the namespace configuration, and I want to make all the calls to be https. I know it would decrease the performance by about 1/10, but I still want to implement it. I know you/might achieve this from tomcat itself, but i want to configure it in security.xml

like image 868
Nikhil Thakur Avatar asked Dec 20 '22 18:12

Nikhil Thakur


1 Answers

You can configure that https is required by adding requires-channel attribute on each intercept-url. For example:

<http>
  <intercept-url pattern="/secure/**" access="ROLE_ADMIN" requires-channel="https"/>
  <intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
</http>

You can configure this more concisely using Spring Security Java Configuration. Notice that we can separate the channel configuration from the role mappings. For example:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/secure/**").hasRole("ADMIN")
                .anyRequest.hasRole("USER")
                .and()
            .requiresChannel()
                .anyRequest().requiresSecure();
    }
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

As of Spring Security 3.2 you also might want to ensure you use Spring Security's headers support. This is enabled by default in Spring Security Java Configuration. In this specific case, the element can add a header called Strict-Transport-Security to the response that ensures that browsers do not even make HTTP requests in the future. For example:

<headers>
  <hsts/>
</headers>

You will want to read more about this in the Headers section of the reference.

like image 142
Rob Winch Avatar answered Jan 04 '23 16:01

Rob Winch