Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring mvc 3 - HTTPS access

How can I force a page to be accessed via HTTPS only. Need to do this via Spring MVC 3 configuration file.

like image 913
Viren Pushpanayagam Avatar asked Apr 17 '11 08:04

Viren Pushpanayagam


1 Answers

Spring-security has such a configuration. see here for how to do it. In short - you force the channel to use https:

<http>
    <intercept-url pattern="/secure/**" access="ROLE_USER" 
        requires-channel="https"/>
    <intercept-url pattern="/**" access="ROLE_USER" 
        requires-channel="any"/>
</http>

If you don't want to use spring-security, here's an interceptor that I wrote:

@Component
public class SslInterceptor extends HandlerInterceptorAdapter {

    // no need to inject it for now..
    private PathMatcher pathMatcher = new AntPathMatcher();

    @Value("${base.url.secure}")
    private String secureRoot;

    @Resource(name="secureLocations")
    private List<String> secureLocations;

    @Value("${use.ssl}")
    private boolean useSsl;


    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {

        if (useSsl && !request.isSecure() && shouldForceSecure(request.getRequestURI())) {

            String redirectUrl = secureRoot + request.getRequestURI();
            if (request.getQueryString() != null) {
                redirectUrl += "?" + request.getQueryString();
            }
            // force session creation - thus it will be accessible to both the
            // secure and the insecure contexts
            request.getSession(true);
            response.sendRedirect(redirectUrl);
            return false;
        }

        return true;
    }

    private boolean shouldForceSecure(String path) {
        for (String pattern : secureLocations) {
            if (pathMatcher.match(pattern, path)) {
                return true;
            }
        }
        return false;
    }
}
like image 139
Bozho Avatar answered Oct 14 '22 21:10

Bozho