在spring security 3.2中发出每个请求https

时间:2014-02-03 21:34:46

标签: https spring-security

我使用命名空间配置使用spring security 3.2,我希望所有的调用都是https。我知道它会使性能降低大约1/10,但我仍然希望实现它。我知道你/可能会从tomcat本身实现这一点,但我想在security.xml中配置它

1 个答案:

答案 0 :(得分:11)

您可以通过在每个拦截网址上添加requires-channel attribute来配置https是必需的。例如:

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

您可以使用Spring Security Java Configuration更简洁地配置它。请注意,我们可以将通道配置与角色映射分开。例如:

@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");
    }
}

从Spring Security 3.2开始,您还可能希望确保使用Spring Security的标头支持。默认情况下,这在Spring Security Java Configuration中启用。在此特定情况下,元素可以向响应中添加名为Strict-Transport-Security的标头,以确保浏览器以后甚至不会发出HTTP请求。例如:

<headers>
  <hsts/>
</headers>

您需要在the Headers section of the reference中了解详情。