Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable spring form based login for RESTful endpoints?

I have spring-security configured using basic and form based authentication as per auto-config='true'.

I would like the endpoints under /api/** to NOT use form based security. Other endpoints outside of /api/** should use form based login. I would like a 401 response sent to any call for these endpoints who did not provide credentials under /api/**.

UPDATE: Thanks to Luke Taylor's comment below I have come up with the following solution.

NOTE: This technique can only be applied as of spring-security 3.1.

First I single out /api/**. We never create a session though use one if available, this is handled by create-session="never" and the use of <session-management/>.

<http pattern="/api/**" create-session="never" use-expressions="true">
    <http-basic />
    <session-management />
    <intercept-url pattern="/api/**" access="hasRole('API_ACCESS')"/>
</http>

<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/" access="permitAll"/>
    <intercept-url pattern="/**" access="isAuthenticated()"/>
</http>
like image 697
Brett Ryan Avatar asked Aug 14 '12 06:08

Brett Ryan


1 Answers

With Spring Security 3.1, your best option is to split the restful and non-restful parts of your application into separate filter chains by using two separate <http> elements. The restful API chain can then be configured to be stateless and use basic authentication, while the default chain can use a normal form-login configuration.

You would then have something like:

<http pattern="/api/**" create-session="stateless">
    <intercept-url pattern="/api/**" access="ROLE_API_USER" />
    <http-basic />        
</http>

<!-- No pattern attribute, so defaults to matching any request -->
<http>
    <intercept-url pattern="/**" access="ROLE_USER" />
    <form-login />        
</http>

The chain definitions must be ordered from most specific pattern to most general, so the default chain comes last.

like image 156
Shaun the Sheep Avatar answered Oct 26 '22 06:10

Shaun the Sheep