Search code examples
javatomcatweb.xmlcsrf-protectioncatalina

Not able to authenticate post request for CSRF token with tomcat


I am working on a tomcat application. I am trying to add CSRF authentication token provided by catlina library(org.apache.catalina.filters.CsrfPrevention). I have added filter to web.xml

<filter>
    <filter-name>CsrfFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CsrfPreventionFilter</filter-class>
    <init-param>
        <param-name>entryPoints</param-name>
        <param-value>/Login</param-value>
    </init-param>
</filter>

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

Also I have updated the login.jsp

<%  String url = '/Login?x=true';
    String encodeUrl = response.encode(url);
%>
    <form action="<%=urlEncode%" action="Post">
        <input type="text" name="username"/>
        <input type="password" name="password"/>
        <button type="submit">Login</button>
    </form>

Now when I am running server login page is rendering. When I am entering username and password browser is sending Post request to Login servlet with CSRF_NONCE http://localhost:9090/Login?x=true&org.apache.catalina.filters.CSRF_NONCE=7DE88A93A526E465566864684FEB01C9. Its having CSRF_NONCE but still response is having status 403. I have read many document but could not found any solution to authenticate post requet.

I also reaad that i need to encode all the urls but could not found how should I need to do. Do I need to write filter for that?


Solution

  • Finally I got the answer. I am posting it here for others.

    For rendering the JSP I was using the RequestDispatcher object

    dispatcher.forward(request, response);
    

    So the filter was not getting applied to the given url. Finally I found the answer. Either I should have used dispatcher in parameter with the filter or response.sendRedirect method in Servlet handler.

    http://www.theserverside.com/news/thread.tss?thread_id=34168