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

Nik*_*kur 4 https spring-security

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

Rob*_*nch 11

您可以通过在每个拦截网址上添加requires-channel属性来配置所需的https .例如:

<http>
  <intercept-url pattern="/secure/**" access="ROLE_ADMIN" requires-channel="https"/>
  <intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
</http>
Run Code Online (Sandbox Code Playgroud)

您可以使用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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<headers>
  <hsts/>
</headers>
Run Code Online (Sandbox Code Playgroud)

您将需要在参考的"标题"部分中阅读有关此内容的更多信息.