Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticate only selected rest end points : spring boot

I have a Spring Boot web application exposing few rest endpoints. I wanted to know how we can enable basic authentication only for selected rest endpoints. Let's say I want only /employee/{id} request to be authenticated and ignore all the other rest endpoints. I am using the following code. My question is will the antMatcher only authenticate the request specified? Currently its enabling authentication for all rest endpoints:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
         // How does it work will it only authenticate employee & 
         // ignore any other request?? Its authenticating all the requests currently. 
         http
            .authorizeRequests()
                 .antMatchers("/employee/*").authenticated()
            .and()
            .httpBasic()
            .and()
            .csrf()
                .disable();    
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER");
    }
}
like image 629
Kalava Avatar asked Jul 15 '16 19:07

Kalava


People also ask

How do you restrict the endpoint of a spring boot?

Run the app using: ./gradlew bootRun . Navigate to the home endpoint, which is open: http://localhost:8080 . And the restricted endpoint, which requires authentication: http://localhost:8080/restricted . When Spring's login form appears, don't forget you can use the default credentials.

What is @API in spring boot?

It allows you to create REST APIs with minimal configurations. A few benefits of using Spring Boot for your REST APIs include: No requirement for complex XML configurations. Embedded Tomcat server to run Spring Boot applications.


1 Answers

By default Spring Boot will secure all endpoints when Spring Security is on the classpath.

You need to explicitly add an exclusion for all other endpoints to be permitted without authentication.

Example:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
               .antMatchers("/employee/*").authenticated()
               .anyRequest().permitAll()
             .and()
             .httpBasic()
             .and()
             .csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER");
    }

}
like image 198
Kyle Anderson Avatar answered Oct 24 '22 12:10

Kyle Anderson