a regular expression

Entries categorized as ‘Programming’

Careful With Your Binary Resources!

November 4, 2009 · Leave a Comment

Our production application stack has a fair amount of external service connections that require the use of certs for SSL security. We used to use a static reference (e.g. /config/certs or c:\config\certs for you Windows people) to locate the certificates, but this was always suboptimal as it made the application less portable. I finally got around to moving from the static reference and landing on Java jar introspection to find the file (using something similar to ClassName.getResource("/cert.pks");).

This conversion worked very well and everything seemed fine until the change got to our continuous integration (or CI) box. That machine, a Centos distribution, kept failing with the error Invalid keystore format when we tried to initialize the keystore in code. I spent hours trying to figure out the difference between my local machine (running OS X, which worked fine) and the CI box. I finally diff’d the cert file in src/main/resources and the resulting file in target/classes. I discovered that the two files were radically different.

Maven has a very cool feature that not only copies values from src/main/resources into target/classes and, ultimately, the resulting Jar file but also can substitute tokens in text files as part of the build (referred to as “filtering”). To enable this, all you have to do is add

<resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
</resources>

to your pom.xml file and you’re off to the races. However, Maven will process every file in the src/main/resources directory as part of performing this substitution. This normally wouldn’t be an issue, but certificate files contain some raw text and Maven dutifully filters them just as it would any resource. This caused a serious issue with the character encoding as Maven was writing out a file with a completely different encoding scheme than the file was created with. Basically, Maven filtering was corrupting our certs.

To fix this, I created a subdirectory off of src/main/resources (I called it binary) and added a manual exclusion in the pom.xml file. The resulting XML looks as follows:

<resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <excludes>
                    <exclude>**/binary/*</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources/binary</directory>
            </resource>
</resources>

This worked perfectly. Hopefully, it helps some of you as well!

Categories: Java · Programming

Grails Acegi Plugin and Securing Multiple Resources using Basic Authentication

October 29, 2009 · 1 Comment

Grails is pretty awesome. Not only does it use Groovy as its main language, but it also provides nice DSL access to Spring settings.

Securing a website is something that can often be fairly complex and easy to get wrong. Grails provides a plugin for the state-of-the-art security model Spring Security (also called Acegi) (plugin can be found here).

Everything was all well and good until I tried to use two different security models simultaneously: a form-based login for human beings and an http basic authentication login for machines consuming an API.

This turned out to be pretty hard. The plugin requires setting the following in the resources.groovy file to work with basic authentication at all:

beans = {
  authenticationEntryPoint(org.springframework.security.ui.basicauth.BasicProcessingFilterEntryPoint) {
    realmName = 'Grails Realm'
  }
}

(The plugin is supposed to automatically do this by setting the basicProcessingFilter = true flag in the SecurityConfigure.groovy file, but there is a bug as of version 0.5.2 which is, as of now, the latest production release.) This worked for basic authentication, but would no longer redirect users to the form-based login.

Back to the drawing board.

What I discovered was that I could change between using the form-based login or the http headers authentication but not use them both. (I should clarify this by saying that I could shove the headers into the request and it would work, but a challenge response of 401 was not being sent back to the client which technically breaks the http authentication spec.) I found this thread (with contributions from the author of the Acegi plugin itself) but, while it pointed me in a nice direction, it didn’t answer the question fully. What I really needed was a way to use the URL to decide how to authenticate.

I finally discovered that the ExceptionTranslationFilter was not unique for the URLs I was using. In short, if the URL looked like: http://www.test.com/application/api/user/show/1, I wanted to use basic authentication and if the URL was http://www.test.com/application/user/show/1, I wanted to use the form-based authentication. The redirect is controlled by the ExceptionTranslationFilter and there was only one (so only one model would work at a time).

All I ended up having to do is create my own ExceptionTranslationFilter and wire it to the API URL. The final code in resources.groovy looks as follows:

import org.springframework.security.util.FilterChainProxy
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsAccessDeniedHandlerImpl
import org.springframework.security.ui.ExceptionTranslationFilter

// Place your Spring DSL code here
beans = {
  basicAuthenticationEntryPoint(org.springframework.security.ui.basicauth.BasicProcessingFilterEntryPoint) {
    realmName = 'Grails Realm'
  }

  basicExceptionTranslationFilter(ExceptionTranslationFilter) {
    authenticationEntryPoint = ref('basicAuthenticationEntryPoint')
    accessDeniedHandler = ref('accessDeniedHandler')
    portResolver = ref('portResolver')
  }

  springSecurityFilterChain(FilterChainProxy) {
    filterInvocationDefinitionSource = """
         CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
         PATTERN_TYPE_APACHE_ANT
         /xml*/**=authenticationProcessingFilter,basicProcessingFilter,securityContextHolderAwareRequestFilter,anonymousProcessingFilter,basicExceptionTranslationFilter,filterInvocationInterceptor
         /**=httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,securityContextHolderAwareRequestFilter,rememberMeProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor
         """
  }
}

Now, visiting any URL that prefixed by a /xml/ will be a call to the basic authentication headers and every other prefix will be a standard form-based login.

Since I shaved a serious yak figuring this out, I hope it helps someone!

Categories: Grails · Java · Programming

Book Review: Craig Walls – Modular Java

September 2, 2009 · 2 Comments

A few weeks ago, I had the pleasure of getting a promotional copy of Craig Walls’ (from Spring In Action fame) new book and thought I’d post a review of it here on my blog.

Modular Java: Creating Flexible Applications with OSGi and Spring provides a great introduction to those either curious about OSGi or wanting to get more out of their existing OSGi workflow using the Spring Framework.

The cover to Modular Java

Modular Java by Craig Walls

Craig Walls, author of “Spring in Action, 2nd Edition”, opens the book explaining why OSGi matters and how it can be used to enhance the modularity and maintainability of those application stacks containing multiple and complex moving parts. He not only serves up a great introduction to the technology, but also directs the reader to several tools that make OSGi development significantly easier.

In the second portion of the book, Craig throws Spring into the mix and demonstrates how the power of Spring Dependency Injection, autowiring, and the Spring MVC web framework can not only run seamlessly in an OSGi container, but also remove a large portion of the burden that OSGi’s API can put on application development.

Finally, Craig spends some time describing how an actual deployment might look in a production environment using both Tomcat and Jetty and provides optimization tips that make the process as painless as possible.

The book itself is logically organized and Craig’s writing style is approachable and easy to follow. All the example source code is available online, and Craig demonstrates how to install OSGi packages using both Eclipse Equinox and Apache Felix, leaving the final OSGi container decision up to the preference and requirements of the project. The sample application Craig uses to demonstrate the concepts in the book is surprisingly fun and useful, and the book contains some wonderful appendices that function as a great reference for current and future development projects. The book is a relatively quick read but surprisingly complete.

For someone looking to get the most out of OSGi or wanting to find out what all the “buzz” is about, Craig Walls’ book is an outstanding choice.

Categories: Java · Programming