Spring REST Security - Protecting Different URLs Differently

I have a REST API running under Spring 4 using basic authentication. These REST services are located under the / api / v 1 / ** URL. However, I want to add another set of REST endpoints under different url / api / v2 / **, but it is protected by token-based authentication.

Is it possible to do this with a single servlet? How to configure Spring Security to use different forms of authentication for different URLs?

Thanks.

+4
source share
1 answer

Java, UserDetailsService URL:

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .antMatcher("/api/v1/**")
                    .httpBasic()
                        .realmName("API")
                        .and()
                    .csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/api/v1/**").authenticated();
        }
    }

    @Configuration
    @Order(2)
    public static class ApiTokenSecurityConfig extends WebSecurityConfigurerAdapter{

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .antMatcher("/api/v2/**")
                    /* other config options go here... */
        }

    }
}
+14

Source: https://habr.com/ru/post/1610933/


All Articles