Sunday, July 14, 2013

Configuring HTTPS causes redirect loop in Spring Security

My application now have authentication module guarding its usage from anonymous user. But sometime I do felt that authentication module doesn’t really showing a great help in securing my web application especially the technology in nowadays is greatly improve, hacking is just as easy as 1, 2, 3. Thus I was thinking to integrate HTTPS protocol into my application to make it more secure. Sound great!! According to the documentation, by adding this code > requires-channel=”true” into the configuration as shown below, will force the application to use HTTPS protocol.
    <http auto-config="true">
        <intercept-url access="ROLE_ADMIN" pattern="/landingpage*"/>
        <intercept-url access="IS_AUTHENTICATED_ANONYMOUSLY" pattern="/login*" requires-channel="https"/>
  
        <form-login authentication-failure-url="/loginfailed" default-target-url="/landingpage" login-page="/login"/>
        
        <session-management invalid-session-url="/sessionTimeout">
            <concurrency-control error-if-maximum-exceeded="true" max-sessions="1"/>
        </session-management>

        <logout invalidate-session="false" logout-success-url="/login"/>
    
Unfortunately the connection were refuse. The connection refuse I mention here is referring to page not found or HTTP 404 being shown on the page. This configuration will not going to work until I discover it few days later of the research. In order to enable HTTPS, the server first must have SSL port enable. Unfortunately Tomcat was disabled by default. To enable SSL port, there are tons of tutorials article on the Internet.

Almost there! The last step is to configure port mapping in the above Spring Security to complete the whole thing. Add following code inside <http>:
    <http auto-config="true">
        ....
        ....
        <port-mappings>
            <port-mapping http="8084" https="8443"/>
        </port-mappings>
    </http>

Missing port mapping in the configuration may cause following error.

The webpage at http://localhost:8084/WebApp3/landingpage has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer. Error code:
ERR_TOO_MANY_REDIRECTS
In conclusion, if the application require to enforce HTTPS rule: 1) Ensure server has SSL port enable. 2) Port mapping has been configure in Spring configuration. 3) Intercept URL to HTTPS channel in Spring configuration.

No comments: