mimiz
mimiz

Reputation: 2288

Different authentication method for different urls

I'm using spring-security (3.0.5.RELEASE) in my application. This application hosts an api and some restricted access for users, i would like to use spring-security to authenticate on both sides of the application.

Api authentication must be done by a sort of api_key

User access authentication is done by a login form

The first question is : Is it possible?
If yes, how could i do it? i've read a lot of things on the Internet, but i can't figure out how to do it (except by upgrading to spring 3.1 ...)

Any help is welcome ...

Regards

Upvotes: 2

Views: 276

Answers (1)

Dave Syer
Dave Syer

Reputation: 58094

Upgrading to Spring Security 3.1 is really the best way to do this cleanly. If you can't do that you can still achieve the desired result but it's not going to be as pretty. If your resources are cleanly separated in the URL space (as they appear to be) you can add a second Spring Security filter covering only the /api resources and make sure it applies before the default one. To separate the configuration in Spring Security 3.0 you need a separate application context for your second filter, and configure the filter to find it in a well-known place - e.g. a DispatcherServlet creates a context and stores it in the servlet context in an attribute related to its name ("api" in the example below):

<filter>
    <filter-name>apiSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>contextAttribute</param-name>
        <param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.api</param-value>
    </init-param>
</filter>

    <filter-mapping>
    <filter-name>apiSecurityFilterChain</filter-name>
    <url-pattern>/api/*</url-pattern>
</filter-mapping>

<servlet>
    <servlet-name>api</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

The dispatcher servlet in this example has an application context at /WEB-INF/api-servlet.xml which contains a Spring Security filter chain with id="apiSecurityFilter".

Upvotes: 3

Related Questions