무너지지않는 젠가 2024. 6. 14. 18:04

* 참고 CSRF를 직접 구현한 적없지만 업무 현장에서 경험한 부분이 있어서 당시 파악한 대로 정리했었다. 그 정리한 부분을 참고하고 나머지는 챗 GPT, 검색을 활용해서 어떻게 구현할지 정리를 해보았다.

 

1. pom.xml에 Spring Security 의존성을 추가 설정을 한다.

 

2. spring-security.xml(토큰 유무에 따른 URL 접근 허용 관리)

 

.

.

.


    <!-- Enable CSRF protection -->
    <http>
        <intercept-url pattern="/" access="permitAll"/>
        <intercept-url pattern="/home" access="permitAll"/>
        <intercept-url pattern="/**" access="authenticated"/>
        <form-login login-page="/login" default-target-url="/home"/>
       

 <logout logout-success-url="/login?logout"/>
        <csrf/> <!-- CSRF protection enabled -->
    </http>


</beans:beans>

 

 

3. web.xml

 

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!-- Spring DispatcherServlet 정의 -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- DispatcherServlet 매핑 -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Spring Security filter -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Context Loader Listener 정의 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Context Parameter 설정 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml, /WEB-INF/spring/spring-security.xml</param-value>
    </context-param>

</web-app>

 

 

 

 

4. servlet-context.xml 에 입력

 

<!-- View Resolver -->

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<beans:property name="prefix" value="/WEB-INF/views/"/> <beans:property name="suffix" value=".jsp"/>

</beans:bean>

 

5. jsp에 토큰정보를 추가한다.

 

방법 (1)

<meta id="csrfToken" name=:_csrf" content="${_csrf.token}"/>

 

방법(2) 

<form action="yourAction" method="post">

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

<!-- other form fields -->

</form>