Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 람다표현식
- webflux
- n+1
- GC
- try-catch
- try-with-resources
- circuitbreaker
- try-catch-finally
- jetbrain
- intelij
- AutoCloseable
- java
- wagon-ssh
- Runtime data area
- springboot
- Class Loader
- 코딩테스트
- closeable
- 4-way-handshake
- tcp
- Kotlin
- 날짜쿼리
- jvm
- optional
- Hotspot VM
- resilience4j
- zipWith
- feign
- execution engine
- 동작방식
Archives
- Today
- Total
JuBin's personal study blog
[Spring Security] CSRF 대응방법, Protection 적용하기 본문
반응형
[ CSRF(Cross Site Request Forgery) 공격 ]
- 사용자 의지와 무관하게 공격자의 의도대로 서버에 특정 요청을 하도록 함
인증과정
- 서버에서는 View 페이지를 return할때 랜덤으로 생성된 csrfToken값을 사용자 session에 같이 저장한다.
- 사용자는 서버에 request(http method : PATCH, POST, PUT, DELETE(GET은 불포함))를 요청할때 view page 내에 hidden으로 숨어있는 csrfToken을 같이 서버로 전송한다.
- 서버에서는 csrfToken값이 세션에 저장되있는 값과 일치하는지 확인해 위조 여부를 판단한다.
- 일치하면 csrfToken은 바로 폐기하고 새로운 view page를 return할때마다 새로 생성한다.
※ 템플릿엔진으로 thymeleaf2.1 이상 버전을 사용하면 Spring MVC, Spring Security가 조합되고 CsrfRequestDataValueProcessor가 사용되어서 자동으로 form태그 안에 hidden값으로 csrf토큰값이 생성된다.
개발자도구(F12)로 보면 보인다.
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
설정 및 사용방법
1. 먼저 CSRF 기능을 활성화 하기 위해선 Spring Security 의존성을 추가하거나 Boot를 사용할 경우 Starter를 통해 의존성을 추가한다.
dependencies {
compile group: 'org.springframework.security', name: 'spring-security-config', version: '5.1.5.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-web', version: '5.1.5.RELEASE'
-- starter를 이용하는 경우
compile('org.springframework.boot:spring-boot-starter-security')
}
2. CSRF방어 기능은 Spring Security 3.2.0버전 이후부터 지원된다.
@EnableWebSecurity 어노테이션을 이용하여 Spring Security 설정이 되면 기본적으로 CSRF Protection이 활성화 된다. 사실상 http.csrf(); 설정부분은 필요없다.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf();
}
}
3. 예외처리
csrfToken검증에 실패할 경우 http 403을 응답코드로 리턴한다. 이러한 예외시 이동할 페이지나 예외처리를 설정한다.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.accessDeniedPage("/denied.html")
.accessDeniedHandler(new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException, ServletException {
if (exception instanceof MissingCsrfTokenException) {
// exception handling
} else if (exception instanceof InvalidCsrfTokenException) {
// exception handling
}
});
}
4. 특정 요청만 예외처리
Ant Matcher 혹은 Request Matcher를 지정하여 특정 요청은 대상에서 제외할 수 있다. 예를들어 외부에서 오는 요청이나 콜백의 경우 제외해야할 필요가 있는 경우가 있다.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers()
.ignoringRequestMatchers();
}
반응형