Tag Archives: spring

A Quick Spring Security Lock-Down

IMPORTANT!
This blog has moved to http://blog.brasskazoo.com!

My new shiny web application is fantastically useful, but only to a certain group of people (i.e. my team), and should only be accessible by them.

So, before being able to put it into real production, I needed a security framework around it.

A legacy JAAS component of ours exists, but given my application was making use of the Spring framework, I compared Spring’s offering to the JAAS infrastructure.

Popular opinion seems to be that JAAS was build for J2SE, not J2EE, and is designed for things at a much ‘lower level’ than web applications, such as client-side applets rather than server-side applications.

Maven

First things first: Maven dependencies.

I’m using spring-webmvc 2.5.6, so I’d like to get security working with the application as it stands now – the latest pre-3.0 release of spring-security is 2.0.6-RELEASE:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aspects</artifactId>
  <version>2.5.6</version>
</dependency>
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-core</artifactId>
  <version>2.0.6.RELEASE</version>
</dependency>

web.xml

The web context requires two things:

1. Context location

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.xml
  </param-value>
</context-param>

(we’ll create the security context in the next step)

2. Filter definition

<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

The url-pattern will mean all requests pass through the filter (which will have more explicit criteria).

Security Context

Now we get to the real meat of the security layer!

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                         http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                        http://www.springframework.org/schema/security
                         http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">

    <http auto-config="true">
        <intercept-url pattern="/**" access="ROLE_USER" />
        <http-basic />
    </http>

    <authentication-provider>
        <password-encoder hash="md5"/>
        <user-service>
            <user name="user" password="aabbccddeeff001122334455667788ff" authorities="ROLE_USER" />
	    </user-service>
	</authentication-provider>
</beans:beans>

Here we can see the configuration for http requests. The ‘auto-config’ sets the defaults (refer to the doco in the references), which are overridden by the contents of the tag. We’ll let in one user for now with the role ‘ROLE_USER’, defined in the authentication-provider section.

Including http-basic just puts the preference on using the basic HTTP prompt, but removing that line would use Spring’s default login page (with user/pass and ‘remember me’ checkbox).

And its done! Deploying the application and loading the page demands a login before progressing.

Next

Future improvements might involve setting up a styled login page, hooking up an LDAP connection (but with restrictions).
Oh, and Selenium tests..

References

Spring Source, Spring Security Reference Documentation <http://static.springsource.org/spring-security/site/docs/2.0.x/reference/ns-config.html>
Peter Mularien, 5 Minute Guide to Spring Security <http://www.mularien.com/blog/2008/07/07/5-minute-guide-to-spring-security/>

Advertisements

Monitoring OSCache statistics with JMX

Given an existing web application that uses OSCache, we can pretty easily add support for JMX monitoring.

A couple of things first:

  • We are using Sun’s Glassfish application server
  • The application is not yet spring-enabled
  • The project uses maven for dependancy management

Since we are using Glassfish, we already have an MBean server and connector, so we don’t have to worry about configuring those parts of the stack. (An MBean is a Managed JavaBean)

As for Spring support, we are restricting its introduction to a small aspect of the application (for now!), so we are minimizing the impact on the rest of the application.

What we need to do:

  • Modify oscache.properties and add an event listener
  • Add a dependancy on spring-web
  • Add a spring context for the JMX exporter
  • Modify web.xml to load the spring context

OSCache event listener

Firstly, we need to set a listener for OSCache that will publish the statistics we are interested in.

In oscache.properties, there is a section for event listeners. We want to implement a statistical listener:

cache.event.listeners=com.opensymphony.oscache.extra.StatisticListenerImpl

Spring dependancies

If you’re using maven, add a dependency on spring-web. This has dependancies on spring-core, spring-context and spring-beans (At the time of writing, 3.0.2.RELEASE was the latest version in the maven repositories).

Otherwise download these manually and chuck them in your WEB-INF/lib.

Spring Context

I made a separate spring context file (cacheContext.xml) for the cache MBean exporter:

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

        <!-- OSCache stats listener bean -->
        <bean id="statisticListener" class="com.opensymphony.oscache.extra.StatisticListenerImpl"/>

        <!-- Export the OSCache stats beans -->
        <bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
            <property name="beans">
                <map>
                    <entry key="oscache-bean:name=Statistics" value="statisticListener"/>
                </map>
            </property>
        </bean>
    </beans>

The map in the exporter links the statistics bean to a key that will be visible in JConsole.

Note: The OpenSymphony link in the references below gives you code to expose an arbitrary JMX connector and port. This is unnecessary since we’re accessing via the application server.

Adding the Spring context loader

The web.xml then needs to be updated to be told to load the new cacheContext.xml.

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/cacheContext.xml</param-value>
    </context-param>

	...

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

JMX Clients

JDK 1.5 includes two JMX clients that you can use.

jconsole is the legacy monitoring application, which has been superseded by the fancy UI of jvisualvm.

Either application will allow you to monitor the statistics bean, however in jvisualvm you will need to install the plugin VisualVM-MBeans under Tools > Plugins. Meanwhile jconsole has an MBeans tab by default.

When your application is running, use one of these utilities to connect to the application server (either directly or via localhost:8686 for glassfish). Under the oscache-bean > Statistics, you should be able to see counts generated by cache attributes. Double-clicking the numbers will pop up a graph, and right-clicking will allow you to export the recorded values.

Graph of OSCache statistics

References

  1. http://www.opensymphony.com/oscache/wiki/JMX%20Monitoring.html
  2. http://java.sun.com/docs/books/tutorial/jmx/mbeans/standard.html
  3. http://java.sun.com/developer/technicalArticles/J2SE/jmx.html

How to load properties files into Spring and expose to the Java classes

IMPORTANT!
This blog has moved to http://blog.brasskazoo.com!

Loading properties files in the spring configuration

The issue:

Our webapp is using a spring and hibernate backend, and both spring configuration and Java classes need to access database connection properties.

Currently there is an application.properties file and a spring applicationContext.xml, both which contain the same information for the database connection.

Ideally, there should be only one configuration file to define the properties, which is used by both spring and Java.

Spring has the ability to load properties files as part of the application configuration, for use internally. The properties can be referenced within spring configuration files using ant-style placeholders, e.g. ${app.var}.

To solve our issue though we’ll also need to provide a populated bean that can be used by our production classes.

Here’s the properties file (application.properties):

appl.name=My Web Application
appl.home=/Users/webapp/application/

# Database properties
db.driver=org.hsqldb.jdbcDriver
db.name=v8max.db
db.url=jdbc:hsqldb:file://${appl.home}/database/${db.name}
db.user=SA
db.pass=

Spring loads the properties file using a bean of the type org.springframework.beans.factory.config.PropertyPlaceholderConfigurer, and then we can reference the properties directly in the spring configuration file.

Note that we can also use placeholders within the properties file, as in the db.url above – the PropertyPlaceholderConfigurer will resolve them too!

    <!-- Load in application properties reference -->
    <bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:application.properties"/>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.user}"/>
        <property name="password" value="${db.pass}"/>
    </bean>

So now we’ve removed the need to have literals in the spring config!

Exposing the spring properties bean in java

To allow our Java classes to access the properties from the same object as spring, we’ll need to extend the PropertyPlaceholderConfigurer so that we can provide a more convenient method for retrieving the properties (there is no direct method of retrieving properties!).

We can extend the spring provided class to allow us to reuse spring’s property resolver in our Java classes:

public class PropertiesUtil extends PropertyPlaceholderConfigurer {
   private static Map propertiesMap;

   @Override
   protected void processProperties(ConfigurableListableBeanFactory beanFactory,
             Properties props) throws BeansException {
        super.processProperties(beanFactory, props);

        propertiesMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            propertiesMap.put(keyStr, parseStringValue(props.getProperty(keyStr),
                props, new HashSet()));
        }
    }

    public static String getProperty(String name) {
        return propertiesMap.get(name);
    }
}

If we now update the applicationProperties bean to use the PropertiesUtil class, we can use the static getProperty method to access the resolved properties via the same object as the spring configuration bean.

Of course, we could run into problems if a class tries to use PropertiesUtil before the spring context has been initialised. For example if you’re registering ServletContextListeners in your web.xml before configuring spring, you’ll get a NullPointerException if one of those classes tries to use PropertiesUtil. For that reason I’ve had to declare the spring context before any context listeners.

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Other listeners -->

References

  1. http://www.jdocs.com/spring/1.2.8/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html
  2. http://j2eecookbook.blogspot.com/2007/07/accessing-properties-loaded-via-spring.html