Spring Security JavaConfig: Configure required Cha

2019-07-19 07:32发布

问题:

I'm trying to serve all static resources (css, javascript and images) through any channel but can't get it to work in combination with .anyRequest().requiresInsecure():

@Configuration
@EnableWebMvcSecurity
@PropertySource("classpath:security.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${security.auth_urls}")
    private String[] authUrls;
    @Value("${security.secured_urls}")
    private String[] securedUrls;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers(authUrls).authenticated()
                .and()
            .formLogin()
                .loginPage("/login.html")
                .permitAll()
                .and()
            .logout()
                .logoutUrl("/logout.html")
                .permitAll()
                .and()
            .requiresChannel()
                .antMatchers("/resources/**,/res/**").requires(ChannelDecisionManagerImpl.ANY_CHANNEL)
                .antMatchers(securedUrls).requiresSecure()
                .anyRequest().requiresInsecure();
    }

    // ...
}

When commenting out .anyRequest.requiresInsecure() it works.

I would like to serve specific pages with HTTPS, all other pages with HTTP and static resources with both.

回答1:

In my app I need to have home urls unsecured (require http), and other to be secured (https only). I managed to do that by following the next order:

...
.and().requiresChannel().antMatchers(homeUrls).requiresInsecure()
.and().requiresChannel().anyRequest().requiresSecure()
...

i.e. first goes rules, that permit (unsecure | both), then goes rules, that forbid (secure only).

HTH



回答2:

Using

.antMatchers("/resources/**", "/res/**").requires(ChannelDecisionManagerImpl.ANY_CHANNEL)

instead of

.antMatchers("/resources/**,/res/**").requires(ChannelDecisionManagerImpl.ANY_CHANNEL)

did the trick.