Tuesday, July 20, 2010

Basic Authentication with Spring Security (Part 3)

Basic authentication with Spring Security works great in my application until a web site is trying to access my application by pass in Authorization information through parameter instead of request header.  I have to create a CustomBasicProcessingFilter to handle the special case, which leads to my new application context configuration:
<security:http auto-config="false"
    access-denied-page="/noaccess.jsp"
    session-fixation-protection="none"
    entry-point-ref="authenticationEntryPoint">
    <security:intercept-url pattern="/helper*" filters="none" />
    <security:intercept-url pattern="/index.jsp*"
        access="ROLE_ANONYMOUS" />
    <security:intercept-url pattern="/logout.*"
        access="ROLE_ANONYMOUS" />
    <security:intercept-url pattern="/401.jsp*"
        access="ROLE_ANONYMOUS" />
    <security:intercept-url pattern="/noaccess.jsp*"
        access="ROLE_ANONYMOUS" />
    <security:intercept-url pattern="/*.do*"
        access="ROLE_USER" />
    <security:http-basic/>
    <security:anonymous />
    <security:logout logout-url="/logout.do"
        logout-success-url="/logout.html" />
    <security:concurrent-session-control
        max-sessions="1"
        exception-if-maximum-exceeded="true"/>
</security:http>

<security:authentication-provider
    user-service-ref="authenticationProvider" />

<bean name="authenticationProvider"
    class="com.my.company.web.CustomUserDetailsService"/>

<security:authentication-manager
    alias="authenticationManager"/>

<bean id="authenticationEntryPoint" class="org.springframework.security.ui.basicauth.BasicProcessingFilterEntryPoint">
    <property name="realmName" value="My Realm"/>
</bean>


<bean id="customFilter" class="com.my.company.web.CustomBasicProcessingFilter">
     <security:custom-filter after="BASIC_PROCESSING_FILTER"/>
</bean>
As you can see from above, Spring Security's Basic Authentication is still in use.  However, when this failed, CustomBasicProcessingFilter will be called to retry authentication.

entry-point-ref in security:http is a must for custom filters.  Without it, the application won't work at all.

One more think you'll need to watch out when adding custom filter.  If you have more than one servlet defined in web.xml but not all of them requires authentication, you might need to add them to the configuration for exclusion even if it was working without the configuration before the custom filter.

No comments: