我使用的是Spring Security版本6.1.2和Spring Boot版本3.1.2.下面是我的Spring安全配置.HTTP方法GET、POST、PUT工作正常,但DELETE不能处理禁止的消息403.我需要添加任何特殊配置才能允许在Spring安全配置中删除HTTP吗?

WebSecurityConfig:

@Configuration
@EnableWebSecurity // 1
public class WebSecurityConfig {

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests((authorizeRequests) -> authorizeRequests.requestMatchers("/**").hasAnyAuthority("USER"))
                .httpBasic(withDefaults());
        return http.build();
    }

    @Bean
    WebSecurityCustomizer ignoringCustomizer() {
        return (web) ->          web.ignoring().requestMatchers(HttpMethod.GET).requestMatchers("/user");
    }
}

UserService code:

@Service
public class UserServiceSecurity implements UserDetailsService {
    @Autowired
    UserRepoSecurity userRepo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final UserPojo user = userRepo.findByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        UserDetails userr = User.withUsername(user.getUserName()).password(user.getPassword()).authorities("USER")
                .build();
        return userr;
    }

}

Controller:

@RestController
@RequestMapping(value = "/products")
public class ProductController {
    @Autowired
    ProductService productService;

    @GetMapping("/{id}")
    public ProductPojo getById(@PathVariable Long id) {
        return productService.getByID(id);
    }

    @GetMapping
    public Iterable<ProductPojo> getAll() {
        return productService.getAll();
    }

    @PostMapping
    public ProductPojo createProduct(@RequestBody ProductPojo product) {
        return productService.createProduct(product);
    }

    @PutMapping
    public ProductPojo update(@RequestBody ProductPojo product) {
        return productService.update(product);

    }

    @DeleteMapping("/{id}")
    public String remove(@PathVariable Long id) {
        productService.remove(id);
        return "Record delete successfully";
    }
}

Below is error on postman:

Error at postman when I hit HTTP DELETE

当我试图使用postman 点击HTTP删除时,它给出了403禁止. Http删除的url:http://localhost:8080/products/1

推荐答案

@EnableWebSecurity启用了Spring安全,并且在默认情况下启用了CSRF支持.

此外,authorizeRequests也已弃用,取而代之的是authorizeHttpRequests. 此外,您还应该添加允许特定请求的CORS配置.

securityFilterChainBody方法应该是这样的.

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

    http.cors(corsConfigurer -> corsConfigurer.configurationSource(corsConfiguration()))
        .csrf(AbstractHttpConfigurer::disable);
    http.authorizeHttpRequests(authorizeRequests->
            authorizeRequests.requestMatchers("/**").hasAnyAuthority("USER"))
        .httpBasic(withDefaults());
    return http.build();
  }

  @Bean
  public CorsConfigurationSource corsConfiguration() {
    return request -> {
      org.springframework.web.cors.CorsConfiguration config = 
          new org.springframework.web.cors.CorsConfiguration();
      config.setAllowedHeaders(Collections.singletonList("*"));
      config.setAllowedMethods(Collections.singletonList("*"));
      config.setAllowedOriginPatterns(Collections.singletonList("*"));
      config.setAllowCredentials(true);
      return config;
    };
  }

Java相关问答推荐

如何在Docker容器中使用wireock—Webhooks阻止请求?

为什么如果数组列表中有重复项,我的代码SOMETIMES不返回true?

在Java Stream上调用collect方法出现意外结果

如何在带有Micronaut的YAML中使用包含特殊字符的字符串作为键

如何找到MongoDB文档并进行本地化?

使用GridBagLayout正确渲染

放气总是压缩整个街区吗?

如何在JavaFX中处理多个按钮

在Frege中,我如何将一个字符串安全地转换为一个可能的Int?

Java页面筛选器问题

来自外部模块的方面(对于Java+Gradle项目)不起作用

我可以在@Cacheable中使用枚举吗

为什么我不能建立输入/输出流?Java ServerSocket

如何使用jooq更新记录?

Java递归泛型是否可以被视为继承和重写的语法糖

HBox内部的左对齐按钮(如果重要的话,在页码内)

Java返回生成器的实现

升级版本后出现非法访问错误

转换为JSON字符串时,日期按天递减-Java

using case default on switch语句返回;预览特征切换中的模式匹配仅在源级别20及以上的情况下可用;