4

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 ...

David Nimmagadda
  • 83
  • 1
  • 1
  • 4
  • http .authorizeRequests() .antMatchers("/resources/**").permitAll(), configuration like this will bypass the security, you will need to keep all such static contents in urls configured like above. – user3247727 Mar 16 '15 at 10:31
  • Yes, but my thing is to allow everything except antMatchers("/api/**") .. how to do this?? Or as you said I'll have to confine my static content to a base path ... that is a constraint na .. – David Nimmagadda Mar 16 '15 at 10:33
  • .ignoring() // ignore all URLs that start with /resources/ or /static/ .antMatchers("/resources/**", "/static/**"); you can add all such static urls in comma separated list, there is no other way in standard implementation. if you want something like that then you might need to override the default logic implemented in AntPathRequestMatcher which checks only for the urls which are matching. – user3247727 Mar 16 '15 at 11:00
  • Thanks for reply Mr. User ... Would there be a way to globally apply Spring security for my webservice base path like "/api/**" ... may be at the servlet dispatcher level or so as you have mentioned – David Nimmagadda Mar 16 '15 at 11:48

2 Answers2

9

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 */
}
holmis83
  • 15,922
  • 5
  • 82
  • 83
0

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

user3247727
  • 174
  • 1
  • 7