spring - 允许在 Rest 端点 Spring Boot 上发布

标签 spring rest spring-boot

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

最佳答案

当然。您可以在定义 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()
   }
}

关于spring - 允许在 Rest 端点 Spring Boot 上发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24049784/

相关文章:

Spring Boot : how to configure autowired WebTestClient

java - 无法克服这个 org.springframework.dao.dataaccessException

Spring Boot : Can't infer the SQL type to use for an instance of java. time.LocalDateTime

java - 通过 Spring 和 CXF 同时公开一个端点的 Rest 和 Soap

java - 在 Payara 4 上部署 Jersey Web 服务不会公开方法

web-services - 设置 Content-Type 以从 Firefox 进行测试

javascript - 在相同 ip 但不同端口上使用 Rest API

java - Spring Data Jpa 入门

javascript - JSTL 复选框不起作用

java - 以编程方式加载 Spring 属性文件