Using Spring Security, how can I use HTTP methods (e.g. GET, PUT, POST) to distingush security for particular URL patterns?

kamaci picture kamaci · Sep 8, 2011 · Viewed 25.1k times · Source

The Spring Security reference states:

You can use multiple elements to define different access requirements for different sets of URLs, but they will be evaluated in the order listed and the first match will be used. So you must put the most specific matches at the top. You can also add a method attribute to limit the match to a particular HTTP method (GET, POST, PUT etc.). If a request matches multiple patterns, the method-specific match will take precedence regardless of ordering.

How can I configure Spring Security so that access to particular URL patterns are secured differently depending on the HTTP method used to access the URL pattern?

Answer

bluefoot picture bluefoot · Sep 9, 2011

This is only about configuration. It says that the <intercept-url> elements will be evaluated from top to bottom in your <http /> tag of your configuration file:

<http auto-config="true">
    <intercept-url pattern="/**" access="isAuthenticated" />
    <intercept-url pattern="/login.jsp" access="permitAll" />
</http>

In the above example, we're trying to allow only authenticated users access everything, except, of course, the login page (the user must first log in, right?!). But this, according to the documentation, won't work, because the less specific match are on top. So, (one of) the right configuration to accomplish this example's objective is:

<http auto-config="true">
    <intercept-url pattern="/login.jsp" access="permitAll" />
    <intercept-url pattern="/**" access="isAuthenticated" />
</http>

Placing the more specific match on top.

The last thing the quote says is about the HTTP method. You can use it to specify the match, so:

<http auto-config="true">
    <intercept-url pattern="/client/edit" access="isAuthenticated" method="GET" />
    <intercept-url pattern="/client/edit" access="hasRole('EDITOR')" method="POST" />
</http>

In this second example, to access /client/edit via GET the user only needs to be authenticated, but to access /client/edit via POST (lets say, submitting the edit form) the user needs to have the EDITOR role. That url pattern may be not encouraged in some places but it was just an example.