Spring Acegi Security Framework

The Authentication object

The Authentication object is pivotal to the Acegi framework. Since "security" basically means "restricted access for specific roles" the framework has to be able to determine, at any time, the roles given to the authenticated user. The framework stores this info in the "Authentication" object, which contains the username, password and the roles granted to the user.

The Authentication object is created and validated by the by the AuthenticationManager. Access to resources is controlled by the AccessDecisionManager.

Filters ^

Acegi uses a chain of (at least) three filters to enable webapplication security:

1.The AuthenticationProcessingFilter handles the Authentication Request Check ("logging into the application"). It uses the AuthenticationManager to do its work.

2. The HttpSessionContextIntegrationFilter maintains the Authentication object between various requests and passes it around to the AuthenticationManager and the AccessDecisionManager when needed;

3. The ExceptonTranslationFilter performs the Existing Authentication Check, handles security exceptions and takes the appropriate action. This action can be either spawning the authentication dialog (a.k.a. the login form) or returning the appropriate HTTP security error code. ExceptonTranslationFilter depends on the next filter, FilterSecurityInterceptor, to do its work.

4. FilterSecurityInterceptor manages the Restricted Acces Check,and the Authorisation check. It knows which resources are secure and which roles have access to them. FilterSecurityInterceptor uses the AuthenticationManager and AccessDecisionManager to do its work.

In good Spring and Dependency Injection fashion, the classes described above do not do their work alone and serve mainly as proxies who delegate the hard work to other classes. I will describe those classes in more detail while laying out the configuration file later on.

Configuration

Since Acegi depends on the Spring framework, all configuration is done through "wiring". Without going into too much detail, "wiring" means associating JavaBeans with each other via a XML configuration file. The three filters mentioned in the previous paragraph need all their dependent objects "wired" into them. We will get to the XML configuration in a moment, but first it might be a good idea to graphically outline the dependencies between the three filters and the various "utility objects" they use.

The Filter Chain

As you saw in the graph in paragraph 5.2, the three filters form a chain through which every HTTP request passes. Together, the three filters perform the task of securing the application. The three filters are "chained" together by an object called the "filterChainProxy", which in turn creates and starts the three filters. See the diagram below:

In good Spring fashion, the three filters are started by yet another object, the "FilterChainProxy". This proxy is configured in the configuration XML file and any additional filters (we will come to some of them later on) will be added to the "FilterChainProxy" configuration list.

<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
 <property name="filterInvocationDefinitionSource">
    <value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /**=httpSessionContextIntegrationFilter,formAuthenticationProcessingFilter,
    exceptionTranslationFilter,filterSecurityInterceptor
    </value>
 </property>
</bean>

The above configuration states the filter beans which will be started by the proxy. The configuration of those filter beans will be discussed below.

The AuthenticationProcessingFilter

The first filter through which the HTTP request will pass is the formAuthenticationProcessingFilter bean. This filter specializes in handling authentication request, i.e. The validation of username/password combinations. Let's take a look at the configuration XML:

<bean id="formAuthenticationProcessingFilter"
        class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter">
    <property name="filterProcessesUrl">
        <value>/j_acegi_security_check</value>
    </property>
    <property name="authenticationFailureUrl">
        <value>/loginFailed.html</value>
    </property>
    <property name="defaultTargetUrl">
        <value>/</value>
    </property>
    <property name="authenticationManager">
        <ref bean="authenticationManager" />
    </property>
</bean>

The filter bean is of type org.acegisecurity.ui.webapp.AuthenticationProcessingFilter. This filter class is specifically used for Form logins, which is why the form-submit URL ("filterProcessUrl"), the login-failed page ("authenticationFailureUrl") are configured with this bean. In case you are wondering where the login page itself is configured: with the security realm, which we will get to later on. Remember that the AuthenticationProcessingFilter specialised in handling authentication requests. Spawning a login dialog is enables a user to log in, but has nothing to do with actually validating the provided username/password combination and is therefore not configured in this filter.

For clarity, here's a diagram of AuthenticationProcessingFilter and its dependencies:


The HttpSessionContextIntegrationFilter

The work of the HttpSessionContextIntegrationFilter is very specialized and therefor very easy to configure. The only thing this filter does, is propagating the established authentication object through all requests. The filter wraps the authentication object a ThreadLocal and hands that wrapper over to the other filters in the chain. Here is the configuration XML:

<bean id="httpSessionContextIntegrationFilter"
  class="org.acegisecurity.context.HttpSessionContextIntegrationFilter">
</bean>

Below is a (perhaps unnecessary?) diagram of HttpSessionContextIntegrationFilter and its dependencies:


The ExceptionTranslationFilter

The ExceptionTranslationFilter is the one of the two"pivotal" filters in the security system (the other being FilterSecurityInterceptor). In short, ExceptionTranslationFilter catches any authentication or authorization error (in the form of an AcegiSecurityException) and may do one of the following two things.

If the exception was caused by the absence of an Authentication object (i.e. the user has not logged in yet), it spawns the configured AuthenticationEntryPoint to prompt the user for login (more on AuthenticationEntryPoint later).

If the exception was caused by an authorization exception thrown by FilterSecurityInterceptor (i.e. the user is logged in but is not authorized for the resource requested), ExceptionTranslationFilter will send an SC_FORBIDDEN (HTTP 403) error to the browser, which will display it’s built-in version of an ‘unauthorized access’ page.

That sounds like quite the story, does it not? Nonetheless, the XML configuration for ExceptionTranslationFilter is rather simple:

<bean id="exceptionTranslationFilter"
        class="org.acegisecurity.ui.ExceptionTranslationFilter">
    <property name="authenticationEntryPoint">
        <ref bean="formLoginAuthenticationEntryPoint" />
    </property>
</bean>

The filter leaves all the hard work to it's collaborators: FilterSecurityInterceptor (to which it is linked through the filter chain) and authenticationEntryPoint. Before we examine those two in more detail, it will definitely be useful to take a look at the following diagram, which shows the two filters and their dependencies:


FilterSecurityInterceptor

FilterSecurityInterceptor contains the definitions of the secured resources. Let's take a look at the XML configuration first:

<bean id="filterSecurityInterceptor"
        class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
    <property name="authenticationManager">
        <ref bean="authenticationManager" />
    </property>
    <property name="accessDecisionManager">
        <ref bean="accessDecisionManager" />
    </property>
    <property name="objectDefinitionSource">
        <value>
            CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
            PATTERN_TYPE_APACHE_ANT
            /secure/admin/*=ROLE_ADMIN
            /secure/app/*=ROLE_USER
        </value>
    </property>
</bean>

You see two bean references here, "authenticationManager" and "accessDecisionManager". We will get to those in a moment, first let's take a look at the property "objectDefinitionSource". In Acegi security, "secured resources" are called "object definitions" (it is a rather generic sounding name because Acegi can be also used to control access to method invocations and object creations, not just web applications). The thing to remember here is that "objectDefinitionSource" should contain some directives and the URL patterns to be secured, along with the roles who have access to those URL patterns.

There are two directives here:

    * CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON tells the Acegi framework to convert the request URL to lowercase, so that the security mechanism cannot be surpassed by simply entering a slightly different URL in the browser;
    * PATTERN_TYPE_APACHE_ANT makes it easier to define the URL patterns to be secured (there is also a different notation style, which looks more like regular expressions and less like the standard J2EE notation so I will not go into that here, mainly because I do not really understand that notation myself ;-) ).

And there are two URL patterns defined here, which are the two main URLs used in the example webapplication.

AuthenticationManager

Here is the configuration XML for AuthenticationManager and it's dependents:

 <bean id="authenticationManager"
        class="org.acegisecurity.providers.ProviderManager">
    <property name="providers">
        <list>
            <ref bean="daoAuthenticationProvider" />
        </list>
    </property>
</bean>
<bean id="daoAuthenticationProvider"
        class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
    <property name="authenticationDao">
        <ref bean="authenticationDao" />
    </property>
</bean>
<bean id="authenticationDao"
        class="org.acegisecurity.userdetails.memory.InMemoryDaoImpl">
    <property name="userMap">
        <value>
            jklaassen=4moreyears,ROLE_ADMIN
            bouerj=ineedsleep,ROLE_USER
        </value>
    </property>
</bean>

The AuthenticationManager is of type ProviderManager, which means that it forms a proxy to the AuthenticationProvider. In Acegi, an AuthenticationProvider validates the inputted username/password combination and extracts the role(s) appointed to that user. AuthenticationProvider is itself a proxy to an AuthenticationDao, which is basically an registry containing usernames, passwords and roles. There a several types of AuthenticationDao (inmemory, database via JDBC or even LDAP), but for simplicity the standard InMemoryDaoImpl type is used. In the Dao, two users have been defined (jklaassen and bouerj), each with a different role.

AccessDecisionManager

Validating the correctness of the username/password combination and the retrieval of associated roles is one thing, deciding whether to grant access is another. In other words: once a user has been authenticated, he must also be authorized. This decision is the responsibilty of the AccessDecisionManager. The AccessDecisionManager takes the available user information and decides to grant access (or not, of course). The AccessDecisionManager uses a Voter to determine if the user will be authorized. Below is the configuration XML:

<bean id="accessDecisionManager"
        class="org.acegisecurity.vote.UnanimousBased">
    <property name="decisionVoters">
        <list>
            <ref bean="roleVoter" />
        </list>
    </property>
</bean>
<bean id="roleVoter" class="org.acegisecurity.vote.RoleVoter">
    <property name="rolePrefix">
        <value>ROLE_</value>
    </property>
</bean>

The above configuration is usually sufficient for webapplications, so we will leave it at that. Note though, that you will have to specify which rolenames should be handled by a specific voter by specifying the role prefix.

Note also that it is possible to wire multiple voters into one AccessDecisionManager and that multiple ProviderManagers can be wired to an AuthenticationManager. So it is possible to let Acegi consult several different username/password registries available (say a mixture of LDAP, Database and NT Domain registries), with many different rolenames configured and voted on by several Voters. I admit that elaborate scenario to be a bit far fetched and certainly far too complex for one webapplication, but in huge enterprise systems such (legacy) complextity may very well exist.

AuthenticationEntryPoint

Now only one configuration item needs to be specified: the AuthenticationEntryPoint, which is the starting point of the authentication dialog. If the FilterSecurityInterceptor determines that there is no available authentication object present, the SecurityEnforcementFilter will pass control to the AuthenticationEntryPoint. Here is the configuration XML:

<bean id="formLoginAuthenticationEntryPoint"
    class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
    <property name="loginFormUrl">
        <value>/login.jsp</value>
    </property>
    <property name="forceHttps">
        <value>false</value>
    </property>
</bean>

The AuthenticationEntryPoint in this example is of type AuthenticationProcessingFilterEntryPoint, which is specifically suitable for FORM login dialogs. Configuration is fairly straightforward, only the URL of the login form to spawn needs to be specified. An optional parameter "forceHttps", may be set to "true" if you would like the username/password data to be sent as encrypted data.

Using an authentication database through JDBC

The above example uses the InMemoryDaoImpl as the AuthenticationDAO, to store usernames, passwords and roles. That's fine for simple testing purposes, but in the real world a user registry is usually a database. So here's some configuration for using the JdbcDaoImpl class of Acegi:

<bean id="userDetailsService"
        class="org.acegisecurity.userdetails.jdbc.JdbcDaoImpl">
    <property name="dataSource">
        <ref bean="dataSource"/>
    </property>
</bean>

That's all. The dataSource configuration is standard Spring:

<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
        <value>com.mysql.jdbc.Driver</value>
    </property>
    <property name="url">
        <value>jdbc:mysql://localhost:3306/springweb_auth_db</value>
    </property>
    <property name="username">
        <value>j2ee</value>
    </property>
    <property name="password">
        <value>password</value>
    </property>
</bean>

Now all you need is the database specification: the tables. There are two ways to go here. The hard way involves using custom tables and thus specifying custom queries and rowmappers for the AuthenticationDao. This is beyond the scope of this tutorial. The documentation included in the full Acegi framework download contains more information on using a user database.

The easy way is to create a database tailored to Acegi's wishes, which would mean the following schema:

The "ENABLED" column could also be a CHAR or VARCHAR holding the values "true" and "false". Obviously, the AUTHORITY column would hold the role names. Populate the database and you are all set!

Using custom authentication provider

The above example uses the JdbcDaoImpl as the AuthenticationDAO, to store usernames, passwords and roles into a database. But if you don't want Acegi to access directly to the database you can configure a custom authentication as a Java bean. So here's some configuration for using a custom authentication:

First you declare your bean:

<bean id="customAuthenticationDao"
        class="test.mypackage.mydao.security.CustomAuthenticationDAO" />

Here is the new configuration XML for AuthenticationManager and it's dependents:

 <bean id="authenticationManager"
        class="org.acegisecurity.providers.ProviderManager">
    <property name="providers">
        <list>
            <ref bean="daoAuthenticationProvider" />
        </list>
    </property>
</bean>
<bean id="daoAuthenticationProvider"
        class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
    <property name="authenticationDao">
        <ref bean="customAuthenticationDao" />
    </property>
</bean>

And finally your Java code will look like this:

 public class CustomAuthenticationDAO implements UserDetailsService {

    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException, DataAccessException {


    //This method loads the user by username from the DB   
    final User user = AccountFacade.loadUserByUsername(userName);
    if (user == null)
        throw new UsernameNotFoundException("The user name was not found");
    return new UserDetails() {

     private static final long serialVersionUID = -2868501916277412090L;

        public GrantedAuthority[] getAuthorities() {
            return new GrantedAuthority[] { new GrantedAuthority() {

                public String getAuthority() {
                    if (user.isSystemAdmin())
                        return "ROLE_ADMIN";
                    else if (user.isAccountAdmin())
                        return "ROLE_ACCOUNTADMIN";
                    else
                        return "ROLE_USER";
                }
            } };
        }

        public String getPassword() {
            return user.getPassword();
        }

        public String getUsername() {
            return user.getUsername();
        }

        public boolean isAccountNonExpired() {
            return true;
        }

        public boolean isAccountNonLocked() {
            return true;
        }

        public boolean isCredentialsNonExpired() {
            return true;
        }

        public boolean isEnabled() {
            return user.isActivated();
        }
    };
}
}


Logout Filter

Add logout functionallity is really simple. You only have to configure one filter. The filter bean is of type org.acegisecurity.ui.logout.LogoutFilter. In this example it will process the logout.jsp url and it will return to index.jsp.

<bean id="logoutFilter"
        class="org.acegisecurity.ui.logout.LogoutFilter">
 <constructor-arg value="/index.jsp" />
 <constructor-arg>
   <list>
     <bean class="org.acegisecurity.ui.logout.SecurityContextLogoutHandler" />
     </list>
 </constructor-arg>
   <property name="filterProcessesUrl">
     <value>/logout.jsp</value>
     </property>
</bean>

And don't forget to add LogoutFilter to the filter chain:

<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
 <property name="filterInvocationDefinitionSource">
    <value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /**=httpSessionContextIntegrationFilter,formAuthenticationProcessingFilter,
    exceptionTranslationFilter,filterSecurityInterceptor,logoutFilter
    </value>
 </property>
</bean>


RememberMe Filter

Now you can add Remember Me functionallity. This part is not as simple than Logout. The main filter you have to configure is RememberMeProcessingFilter. The XML configuration will look like this:

<bean id="rememberMeProcessingFilter"
    class="org.acegisecurity.ui.rememberme.RememberMeProcessingFilter">
    <property name="rememberMeServices">
        <ref local="rememberMeServices" />
    </property>
    <property name="authenticationManager">
        ref="authenticationManager" />
    </property>
</bean>
<bean id="rememberMeServices"
    class="org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices">
    <property name="userDetailsService">
        <ref local="customAuthenticationDao" />
    </property>
    <property name="key" value="myKey" />
    <property name="parameter" value="rememberMe" />
</bean>
<bean id="rememberMeAuthenticationProvider"
class="org.acegisecurity.providers.rememberme.RememberMeAuthenticationProvider">
    <property name="key">
        <value>myKey</value>
    </property>
</bean>

Also you have to add a reference in your AuthenticationProcessingFilterEntryPoint defined above:

<bean id="formLoginAuthenticationEntryPoint"
    class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
    <property name="loginFormUrl">
        <value>/login.jsp</value>
    </property>

    <property name="rememberMeServices">
        <ref bean="rememberMeServices" />
    </property>
</bean>

And don't forget to add RememberMeProcessingFilter to the filter chain:

<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
 <property name="filterInvocationDefinitionSource">
    <value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /**=httpSessionContextIntegrationFilter,formAuthenticationProcessingFilter,
    exceptionTranslationFilter,filterSecurityInterceptor,logoutFilter,
    rememberMeProcessingFilter
    </value>
 </property>
</bean>


ChannelProcessingFilter (SSL)

Add secure login functionallity is really simple too. You have to configure two beans: ChannelProcessingFilter and ChannelDecisionManager. In the first filter you have to configure which resources will require secure channel. In the second bean you need to specify two references (SecureChannelProcessor and InsecureChannelProcessor). Here is the XML configuration:

<bean id="channelProcessingFilter"
    class="org.acegisecurity.securechannel.ChannelProcessingFilter" >
    <property name="channelDecisionManager" ref="channelDecisionManager"/>
    <property name="filterInvocationDefinitionSource">
        <value>
        PATTERN_TYPE_APACHE_ANT
        /login.jsp=REQUIRES_SECURE_CHANNEL
        /**=REQUIRES_INSECURE_CHANNEL
      </value>
  </property>
<bean id="channelDecisionManager"
    class="org.acegisecurity.securechannel.ChannelDecisionManagerImpl">
    <property name="channelProcessors">
        <list>
        <bean class="org.acegisecurity.securechannel.SecureChannelProcessor"/>
        <bean class="org.acegisecurity.securechannel.InsecureChannelProcessor"/>
      </list>
  </property>
</bean>

AGAIN: Don't forget to add ChannelProcessingFilter to the filter chain:

<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
 <property name="filterInvocationDefinitionSource">
    <value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /**=httpSessionContextIntegrationFilter,formAuthenticationProcessingFilter,
    exceptionTranslationFilter,filterSecurityInterceptor,logoutFilter,
    rememberMeProcessingFilter,channelProcessingFilter
    </value>
 </property>
</bean>

And also you have to change to TRUE the forceHttps property defined above:

<bean id="formLoginAuthenticationEntryPoint"
    class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
    <property name="loginFormUrl">
        <value>/login.jsp</value>
    </property>
    <property name="forceHttps">
        <value>true</value>
    </property>
</bean>

And finally you will need to install your certificates and configure your application server. If you are using Apache Tomcat you can read about it at:

http://tomcat.apache.org/tomcat-5.5-doc/ssl-howto.html

No comments:

Post a Comment