CSRF Token
2023. 12. 28. 19:18ㆍSpring Boot
JAVA Spring boot에서 csrf 방지를 위한 토큰은 spring security를 이용하면 간단하게 구현할 수 있다
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf((csrf) -> csrf
.ignoringRequestMatchers(new AntPathRequestMatcher("/form/**")));
return http.build();
}
}
SecurityConfig를 만들어 주면 되는데
기본적으로 모든 요청에 csrf토큰 검사를 하기 때문에 그냥 form을 보내는 요청을 검사를 하지 않도록 수정하였다
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.demo.test;
@Controller
@RequestMapping("/csrf")
public class csrf_controller {
@RequestMapping(method = RequestMethod.GET)
public String form_get(Model model) {
model.addAttribute("test", new test());
return "form/form_post_csrf";
}
@RequestMapping(method = RequestMethod.POST)
public String form_post(@ModelAttribute test test, Model model) {
model.addAttribute("test", test);
System.out.print(test.getData());
return "form/form_get";
}
}
기본적으로 토큰의 작업은 security 알아서 하므로 나머지는 일반적인 form 요청에 관련한 page를 만드는 방법과 같다
<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>CSRF token test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:object="${test}" method="post">
<p>CSRF Token: <input th:name="${_csrf.parameterName}" th:value="${_csrf.token}" /></p>
<p>Title: <input type="text" th:field="*{title}" /></p>
<p>data: <input type="text" th:field="*{data}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>

이렇게 CSRF토큰이 요청시 자동으로 넘어오는데

토큰을 건드리지 않고 넘어온 그대로 다시 보내주면 문제가 없지만

토큰을 임의로 수정하면 403에러가 뜨는 모습을 볼 수 있다
'Spring Boot' 카테고리의 다른 글
| Json Web Token (2) | 2024.01.02 |
|---|---|
| CustomFilter (0) | 2024.01.02 |
| SecurityFilterChain (0) | 2024.01.02 |
| MongoDB (0) | 2023.12.28 |
| Form Post (0) | 2023.12.12 |