CSRF란?
Cross-Site Request Forgery의 줄임말으로, 요청을 위조하여 사용자가 원하지 않아도 서버측으로 특정 요청을 강제로 보내는 방식. 예를 들어 회원 정보가 변경되거나 CRUD를 사용자 모르게 요청
개발환경에서 csrf disable()
로컬 환경에서 Security Config 클래스에 csrf설정을 disable해두는 것은 괜찮지만, 배포 환경에서는 csrf공격 방지를 위하여 csrf 토큰을 관리하는 추가적인 설정을 진행하여야 한다. 즉, 스프링 시큐리티는 CsrfFilter를 통하여 GET요청을 제외한 POST, PUT, DELETE요청에 대해서 토큰 검증을 진행하게 된다.
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ http .csrf((auth) -> auth.disable()); return http.build(); }로그아웃 설정
Security Config에서 로그아웃은 GET요청이기 때문에 csrf 토큰 검정을 하지 않아 로그아웃 요청이 제대로 처리되지 않는다.
따라서 따로 설정을 해주어야 한다.http .logout((auth) -> auth.logoutUrl("/logout") .logoutSuccessUrl("/"));컨트롤러
@Controller public class logoutController { @GetMapping("/logout") public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if(authentication != null) { new SecurityContextLogoutHandler().logout(request, response, authentication); } return "redirect:/"; } }RestAPI 서버(백엔드)의 경우 csrf.disable()
세션은 Stateless로 관리하기 때문에 따로 csrf.enable()을 설정하지 않아도 된다.
Reference