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");
}
}
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.
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.
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With