Spring Security Spring安全删除方法被禁止

vmdwslir  于 2023-10-20  发布在  Spring
关注(0)|答案(1)|浏览(134)

我创建了Web应用程序。pom.xml

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
     <version>3.1.4</version>
 </dependency>
https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
 <dependency>
     <groupId>org.yaml</groupId>
     <artifactId>snakeyaml</artifactId>
     <version>2.0</version>
 </dependency>

https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
 <dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-config</artifactId>
     <version>6.1.4</version>
 </dependency>

文件控制器

@RequestMapping("/passports")
@RequiredArgsConstructor
public class PassportController {

    @Operation(
description = "Удаление паспорта из таблицы",
summary = "delete passport",
hidden = false
    )
    @ApiResponse(responseCode = "200", description = "PassportResponse")
    @DeleteMapping("/{id}")
public void deleteById(
            @PathVariable(name = "id") final long id
throws Exception {
passportComponent.deleteById(id);
    }
}

文件WebSecurityConfigurer

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class WebSecurityConfigurer {

    @Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user = User.withUsername("user")
                .password(encoder().encode("userPass"))
                .roles("USER")
                .build();
return new InMemoryUserDetailsManager(user);
    }

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

XorCsrfTokenRequestAttributeHandler requestHandler = new XorCsrfTokenRequestAttributeHandler();

requestHandler.setCsrfRequestAttributeName(null);

http
            .cors(Customizer.withDefaults())
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests((authz) -> authz
                .requestMatchers(HttpMethod.GET).permitAll()
                .requestMatchers(HttpMethod.DELETE).permitAll()
                .anyRequest().authenticated()
             )
            .csrf((csrf) -> csrf
                .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
            )
            .csrf((csrf) -> csrf
                .csrfTokenRequestHandler(requestHandler)
            )
            .csrf((csrf) -> csrf
                .csrfTokenRepository(new HttpSessionCsrfTokenRepository())
            )
            .csrf((csrf) -> csrf
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            )
            .csrf((csrf) -> csrf
                .csrfTokenRequestHandler(new XorCsrfTokenRequestAttributeHandler())
            )
            .csrf((csrf) -> csrf
                .ignoringRequestMatchers("/no-csrf"))
            .csrf(Customizer.withDefaults()).csrf((csrf) -> csrf
                .csrfTokenRepository(new HttpSessionCsrfTokenRepository()))
            .csrf((csrf) -> csrf
                .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
            );
return http.build();
    }

    @Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager(){
List<UserDetails> userDetailsList = new ArrayList<>();
userDetailsList.add(User.withUsername("user").password(encoder().encode("userPass"))
                .roles("EMPLOYEE", "USER").build());
return new InMemoryUserDetailsManager(userDetailsList);
    }
    @Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
    }
}

@GetMapping()是OK我尝试使用删除方法在 Postman 。但是我收到的答案是"status": 403,"error": "Forbidden" .我做错了什么?我该怎么解决这个问题?

ghhkc1vu

ghhkc1vu1#

通常这个消息("status": 403,"error": "Forbidden" .)是因为你使用的CSRF启用,在这种情况下,你有一些错误的配置,因为首先在filterChain我看到你禁用它.csrf(AbstractHttpConfigurer::disable)和之后,你是做一些验证/核实它(

.csrf((csrf) -> csrf
                        .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
                    )
     ...
return http.build();

)。在我看来,什么是真正错误的方式。
为了确定问题出在这里,我建议你重写filterChain Bean方法。从你拥有的东西到类似的东西(避免在生产中使用它)。

@Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .cors(Customizer.withDefaults())
        .csrf(AbstractHttpConfigurer::disable)
        .authorizeHttpRequests((authz) -> authz
            .requestMatchers(HttpMethod.GET).permitAll()
            .requestMatchers(HttpMethod.DELETE).permitAll()
            .anyRequest().authenticated());
    return http.build();
  }

在它之后,HttpMethod.DELETE将工作。
顺便说一下,你还必须阅读有关CSRF的内容。
关于它的一些好的参考:
CSRF
OWASP CSRF

相关问题