June 21, 2008

Integrating Blaze Data Services and Spring Security

UPDATE: I've noticed that Typepad is mangling some of the XML I'm posting here.  I'm working on a fix for this. :)

One thing to keep in mind with the out-of-the-box security support in Blaze DS is the approach to integration is container-specific: there is support for Tomcat (and therefore JBoss), WebSphere, Weblogic and Oracle through various implementations of the LoginCommand interface. Unfortunately if you have custom security requirements for authentication that means you're dealing with a lot of cumbersome, container-specific security configuration and/or writing and configuring JAAS plugins. The authorization support in Blaze DS is limited to specifying which roles have access to a particular destination which isn't nearly flexible enough.

Fortunately Spring Security provides solutions to many common problems in Java EE space, including features like container portability, a flexible authentication provider model, authorization of service method invocation via AOP and even some very cool ACL support to enforce granular security at the domain object level. Integrating Spring Security with Blaze DS isn't as hard as you think either: I was able to bang out a quick proof of concept over a weekend.

The config for Spring Security 2 is quite straightforward with the new XML namespace support in your Spring config files:

    <security:http>
        <security:form-login>
    </security:http>

This is basically a very stripped-down configuration since things like RememberMeServices (using cookies) don't usually apply in a Flex-based RIA. You can also throw in a very simple AuthenticationProvider like this one from the SS2 docs:

    <security:authentication-provider>
        <security:user-service>
            <security:user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN"/>
            <security:user name="bob" password="bobspassword" authorities="ROLE_USER"/>
        </security:user-service>
    </security:authentication-provider>

There are two items you need to add to your web.xml to bootstrap SS2 in a Servlet container:

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

    <filter>
        <filter-name>securityContextAwareFilter</filter-name>
        <filter-class>org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter</filter-class>
    </filter>

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

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

The first filter is standard part of any Spring Security configuration. The "SecurityContextHolderAwareRequestFilter" adapts SS2 to the Servlet environment so that calls like getPrincipal() and isUserInRole() behave as expected. This really comes in handy when you have other code in your projects that assumes a "standard" Java security setup.

Now we need a little config in the Blaze services-config.xml file:

    <security>
        <login-command class="net.histos.util.spring.SpringSecurityLoginCommand" server="Tomcat"/>

        <security-constraint id="valid-user">
            <auth-method>Custom</auth-method>
            <roles>
                <role>ROLE_USER</role>
            </roles>
        </security-constraint>
    </security>

Blaze DS seems to require that a "server" attribute be specified for any LoginCommand even though this isn't really used in our implementation.  The security-constraint isn't necessary if you are going to use SS2's service method invocation authorization support. However if your security requirements are more straightforward you can do role/destination based restrictions here. Then simply add this element to the appropriate destinations:

    <security>
        <security-constraint ref="valid-user"/>
    </security>

The last part is some Java code. If you extend AppServerCommand you get a default impl for this method:

    protected boolean doAuthorization(Principal principal, List roles, HttpServletRequest request) throws SecurityException

This method makes use of isUserInRole(), so by adding the servlet filter referred to above, this logic can work without any modification required. This leaves only two methods in your LoginCommand impl:

    public Principal doAuthentication(String username, Object credentials) {
        log.debug("doAuthentication");
        // get the ProviderManager from app context
        Map<string, providermanager=""> map = getContext().getBeansOfType(ProviderManager.class);
        if (map.size() != 1)
            throw new RuntimeException("Spring ApplicationContext must contain exactly one ProviderManager bean");
        ProviderManager provider = map.get( map.keySet().iterator().next() );
        // authenticate
        String password = extractPassword(credentials);
        Authentication auth = provider.authenticate( new UsernamePasswordAuthenticationToken(username, password) );
        SecurityContextHolder.getContext().setAuthentication(auth);
        return auth;
    }

    public boolean logout(Principal principal) {
        log.debug("logout");
        SecurityContextHolder.getContext().setAuthentication(null);
        return true;
    }

Those are the basics!  As I said, this a proof of concept that I haven't had time to test extensively yet but it should get you started!  One other note: I noticed while testing the Flex side that calling login() or logout() on a RemoteObject without calling a "regular" service method would result an error; apparently the ChannelSet hadn't been defined yet.  I did a little digging and found that apparently you're supposed to call login() or logout() on the underlying ChannelSet itself.  I wrote a very simple ChannelSet implementation that can be easily instantiated in MXML and bound as the channelSet property for your RemoteObjects:

    package net.histos.flex.util
    {
        import mx.messaging.ChannelSet;
        import mx.messaging.channels.AMFChannel;
       
        public class SimpleChannelSet extends ChannelSet
        {
            public function set url(channelUrl : String) : void {
                addChannel(new AMFChannel("defaultChannel", channelUrl));
            }
        }
    }

    <util:SimpleChannelSet
        id="channelSet"
        url="http://localhost:8080/testapp/messagebroker/amf"
        />

Then simply invoke login() and logout() on the ChannelSet itself and you should have no problems.

June 09, 2008

Railo and JBoss gets crickets at The Server Side

Unfortunately Railo going OSS as part of JBoss has gotten nothing more than crickets over at The Server Side.  The reception to other dynamic languages such as JRuby or Groovy has been lukewarm at TSS so it'll be interesting if CFML is able to make better inroads.

June 08, 2008

Open Source ColdFusion? BlueDragon and Railo

The month of June has been significant with the news of the Railo CFML server joining the JBoss ecosystem and New Atlanta ready to formerly announce the open source BlueDragon CFML server at the CFUnited Conference.  It's interesting to consider what this will mean for the future of CFML and obviously Adobe's official implementation of CF.

We now have two reasonable implementations of ColdFusion that are now free and open source.  It's very likely that this might help spur adoption of CF which has been fairly stagnant for a number of years.  Despite the supposedly strong sales numbers that Adobe routinely trumpets (although rarely articulates with hard numbers), job postings for CF are flat in an industry that continues to grow.  Hopefully the accessibility that an open source CF will offer will make more folks pick it up and see what it's all about.

There's also a good chance that this will drive Adobe to make CF's pricing more competitive.  Given that CF Standard sells for $1299 now it's hard to believe they would start to give that away for free.  Perhaps the price will be pushed down significantly or Adobe will make a free version available while stripping out additional features from pro.  At the end of the day, having access to a cheap version of the "real" CF can't be a bad thing.

The biggest concern has to be one of forking.  BlueDragon has for some time decided to implement their own tags or functions in the language, some of which were followed by Adobe while others were not.  Railo has also started to add their own features which I haven't seen in BD or CF.  If Adobe introduces a third version of the product that will mean at least five different deployment environments.  Is this going to be a problem?  Or will the choices just mean that the reach of CFML will expand?

In some ways this reminds me of the Java universe with its numerous implementations of the Servlet specification and/or the full Java Enterprise Edition stack.  The difference here is that these technologies are based on well-defined standards and specs that anyone is free to implement.  Most of the commercial vendors will add their own extensions to "add value" and justify their hefty license fees but the spec is implemented rather reliably across the board, giving you freedom to switch between vendors if you so desire.

Does this mean that a CF specification might be in the future?  Will Adobe cozy up to Railo to tag-team BlueDragon?  It'll be interesting to see what's in store for the second half of 2008.

May 21, 2008

Mac Users: Stay Away from DoubleCommand

DoubleCommand is "software for Mac OS X (a kernel extension) that lets you remap keys, in other words change the way your keyboard works."  The lesson I learned from DC is that badly-written kernel extensions lead to many kernel panics.  Here's the painful highlights.
  • The machine would rarely shut down or restart properly.  Almost every time my Mac's screen would go dark and be unresponsive to keyboard input I could still hear the fan running.  The only solution was to hold down the power button to force it off, then get that nasty "your Mac did not shut down cleanly" error message on startup.
  • Random kernel panics while plugging or unplugging USB keyboard / mouse from the machine.  Very nasty.
  • The UI is in no way intuitive and that's putting it nicely.  For something as simple as remapping keys, this should not be something you have to fight with.
Stay away from this one.  It ain't worth it. :)

May 14, 2008

FlashPlayer 10 "Astro" now in beta

FlashPlayer 10 (codename: Astro) is now available on Adobe Labs.  3D support and hardware acceleration is the big news here.  Also check out the release notes for two new significant improvements:

  • Vectors - part of ECMAScript 4, these are basically like Arrays except you can specify the type stored inside of it.  Finally a taste of generics from Java!  Better type safety and improved performance.
  • File Reference runtime access - pull local files into the RIA as a ByteArray or String, work with the data and even save changes back to the original file!

It's a great time to be a RIA developer. :)