允许在Rest端点Spring Boot上发布

时间:2014-06-05 00:31:04

标签: spring rest spring-boot

我有一个休息应用程序规范,允许任何用户向端点发送POST请求,但将GET限制为仅限系统的注册用户。有没有办法公开端点的某些方法,如(POST或PUT),并限制其他方法,如(GET或UPDATE),而不是仅仅保护端点的所有方法。

1 个答案:

答案 0 :(得分:6)

不确定。您可以在定义HttpSecurity时指定要保护的HTTP方法:

@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()
   }
}