How to ignore Spring Security config for every thi

2019-02-18 17:35发布

问题:

I have a rest webservice configured as a spring boot application. All my rest urls have a base path "/api/...". I am also serving static content from my application. I need to configure security ONLY for the web service i.e., URLs that start with "/api/..." but give the other static content w/o applying security.

I've only seen examples where we filter some url patterns via:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/*");
}

but not otherwise ...

回答1:

Use the antMatcher method of HttpSecurity class:

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/api/**");
        // add security constraints for /api/... here
    }

    /* rest of config */
}


回答2:

Instead of antMatcher, you can you regexMatcher wich can be a negation pattern

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().regexMatchers(XXXXX);
}

Answer to your last comment, if you are using latest spring framework and spring security then define below class and security config as per the config standards.

package org.springframework.security.samples.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class MessageSecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}

Also, look at below URL if you still find it difficult to get started with spring security.

http://docs.spring.io/spring-security/site/docs/3.2.6.RELEASE/reference/htmlsingle/#hello-web-security-java-configuration