티스토리 뷰

에러

spring security postmapping 403 에러

여행자0 2024. 11. 20. 03:02

스프링부트에 스프링 시큐리티를 적용하여 프로젝트를 진행하다가 발견했다.

GetMapping은 되는데 PostMapping에서  403 Forbidden error가 발생했다....

 

 

스프링 시큐리티는 CSRF 공격에 대비하여 CSRF 토큰을 사용한다.

이 토큰은 웹 페이지의 폼에 포함되어 사용자의 브라우저가 이를 서버에 전송하도록 한다.

서버는 이 토큰을 검증하여 요청의 유효성을 확인한다.

Spring Security에서 CSRF 토큰을 활성화하면 insert, delete, update 같은 변경을 가하는 요청 (post 요청)에 대해 해당 토큰이 필요하게 된다.

* CSRF : 공격자가 사용자의 권한을 사용하여 웹 애플리케이션에서 의도하지 않은 요청을 만들도록 속이는 공격 방법

 

 

 

해결방안

csrf.disable()을 해주면 PostMapping이 가능해진다.

@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig{
	
	
	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
		http.csrf().disable();
        
		return http.build();
	}

}

 

 

그러나 위처럼 작성했을 시, ...is deprecated and marked for removal 이라는 오류가 발생했다.

 

구글링 해본 결과, 

스프링 시큐리티 6.1.0 버전부터는 메서드 체이닝 사용을 지양하고 람다식으로 설정하도록 되어 있다.

람다식으로 작성한 코드는 다음과 같다.

@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig{
	
	
	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{

		http
		.csrf(csrfConfig -> csrfConfig.disable()
		)					// spring security postmapping 가능하도록 세팅
		
		.authorizeHttpRequests(auth -> auth
			.anyRequest().permitAll()  // 모든 경로에 대해 인증 없이 접근 허용
		)
        ; 
        
		
		return http.build();
	}

}

SecurityConfig 파일에

http.csrf(csrfConfig -> csrfConfig.disable()); 

을 작성하면 된다.

 

 

참고블로그

https://velog.io/@woosim34/Spring-Security-6.1.0%EC%97%90%EC%84%9C-is-deprecated-and-marked-for-removal-%EC%98%A4%EB%A5%98

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/11   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함