Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permit Post on a Rest endpoint Springboot

I have a rest application specification that allows any user send a POST request to an endpoint but restricts GET to only registered users of the system. Is there a way to expose certain methods of an endpoint such as (POST or PUT) and restrict others such as (GET or UPDATE) as opposed to just securing all the methods of an endpoint.

like image 748
F.O.O Avatar asked Mar 27 '26 05:03

F.O.O


1 Answers

Sure. You can specify the HTTP method you want to secure when you define your HttpSecurity :

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http.
            csrf().disable().
            sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
            and().
            authorizeRequests().
            antMatchers(HttpMethod.GET, "/rest/v1/session/login").permitAll().
            antMatchers(HttpMethod.POST, "/rest/v1/session/register").permitAll().
            antMatchers(HttpMethod.GET, "/rest/v1/session/logout").authenticated().
            antMatchers(HttpMethod.GET, "/rest/v1/**").hasAuthority("ADMIN").
            antMatchers(HttpMethod.POST, "/rest/v1/**").hasAuthority("USER").
            antMatchers(HttpMethod.PATCH, "/rest/v1/**").hasAuthority("USER").
            antMatchers(HttpMethod.DELETE, "/rest/v1/**").hasAuthority("USER").
            anyRequest().permitAll();
   }

   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth
               .inMemoryAuthentication()
               .withUser('admin').password('secret').roles('ADMIN');
   }

   @Bean
   @Override
   AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean()
   }
}
like image 106
Geoffroy Warin Avatar answered Mar 28 '26 23:03

Geoffroy Warin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!