<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gridshore &#187; security</title>
	<atom:link href="http://www.gridshore.nl/tag/security/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gridshore.nl</link>
	<description>A weblog about software engineering, Architecture, Technology an other things we like.</description>
	<lastBuildDate>Tue, 13 Dec 2011 15:36:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Integrate flex security in Mate using the spring BlazeDS integration project</title>
		<link>http://www.gridshore.nl/2009/05/24/integrate-flex-security-in-mate-using-the-spring-blazeds-integration-project/</link>
		<comments>http://www.gridshore.nl/2009/05/24/integrate-flex-security-in-mate-using-the-spring-blazeds-integration-project/#comments</comments>
		<pubDate>Sun, 24 May 2009 09:04:20 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[Mate]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=789</guid>
		<description><![CDATA[<p>More than a year a go I started writing about flex. My first post was about the integration of BlazeDS with the springframework at the back-end using intellij. I moved on with a Datagrid component that had filtering included in my second post. Than I did two posts about integrating spring security. The first [...]]]></description>
			<content:encoded><![CDATA[<p>More than a year a go I started writing about flex. <a href="http://www.gridshore.nl/2008/03/04/integrating-flex3-and-springframework-using-blazeds-and-intellij/">My first post</a> was about the integration of BlazeDS with the springframework at the back-end using intellij. I moved on with a Datagrid component that had filtering included in <a href="http://www.gridshore.nl/2008/03/25/creating-a-flex-3-datagrid-component-with-backend-filtering/">my second post</a>. Than I did two posts about integrating spring security. <a href="http://www.gridshore.nl/2008/05/11/integrating-flex-3-with-spring-security-formerly-known-as-acegi/">The first article</a> was a nice start to understand the concepts. <a href="http://www.gridshore.nl/2008/07/14/integration-spring-security-acegi-and-flex-3-the-sequel/">The second post</a> improved the code a lot with more understanding of the flex principles.</p>
<p>With the next posts I moved on to use maven, which in the beginning was not easy, but thanks to the <a href="http://code.google.com/p/flex-mojos/">excellent flex-mojos plugin</a> from velo. In the beginning of this year I started blogging about the springsource coming into the flex domain for real. Two projects, one for the spring style of programming in the ActionScript language. The other one for integrating BlazeDS and the spring framework. I wrote multiple posts about the new spring project. This post will probably not be the last. But if you are using Mate as well as the spring BlazeDS Integration project. This is a must read post. Maybe only to laugh at what I have done, but I hope to be amazed how simple a full flexed application can be when you combine all these technologies.</p>
<p>Kind of a long introduction, but what is this post really about? I have been using a sample application called books-overview that I have been using for flex based applications. I have been adding stuff to it once in while, but now I have completely refactored it. I am using a framework called <a href="http://mate.asfusion.com/">Mate</a>, have made it modular using the flex-mojos plugin and I have adopted the Spring BlazeDS integration project. Time to explain the way I handle security now, how I am using maven and show the extension to Mate for security.</p>
<p>Read on to find out how I did it and like always leave a comment if you like it or if you have improvements.</p>
<p><span id="more-789"></span><br />
<h2>The books-overview sample</h2>
<p>The books overview sample is a very easy application. You need to login to get access to the application. You can get two different roles. A normal user can look at the books, and admin user can also add books. The domain model is very easy. There are two entities; book and author. A book can have multiple authors and an author can write multiple books. I think the architecture is pretty straightforward. The basic business layer, dao layer, domain component and a web project containing the BlazeDS and flex components. We use spring-security to implement authentication as well as authorization. All data is stored in an in memory database and everything is build using maven. You can find the code in google code, checkout the trunk with the following command:</p>
<p><strong>svn checkout http://gridshore.googlecode.com/svn/trunk/books-overview gridshore-books-overview</strong></p>
<p>To tests if it works, you can use the following commands:</p>
<ul>
<li>step into the directory where you just checked out the sample</li>
<li>mvn clean install (you might have to install some artifacts yourself that are not available in a repository)</li>
<li>cd books-web</li>
<li>mvn clean jetty:run-war</li>
<li>open your browser with the url: <a href="http://localhost:8080/books-web">http://localhost:8080/books-web</a></li>
</ul>
<p>You should see the login screen, enter user admin with password admin and you should see the following screen:</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/bo-screen-initial.png" alt="bo_screen_initial.png" border="0" width="786" height="519"/></p>
<p>It looks like a pretty easy screen, but a lot has happened before this screen is presented to you. Most important to know for now is that the <strong>New Book</strong> button is only available when logged in as admin. The name can be seen in the logout button on the right. This time with the label <strong>logout admin</strong>. You can now experiment with the application a bit. That way you will better understand what is happening in the code.</p>
<h2>Setting up the maven build</h2>
<p>For my development I use a combination of building with maven and writing code within intellij. Maybe I should invest more time to build with intellij as well, but I keep having problems with it. The workflow of building with maven in a command line is now so easy that I settle with that. Though I do miss the debugging, maybe I&#8217;ll step into it once more. A very cool feature of intellij is that it can group projects into modules. You can make intellij create these modules automatically based on maven structures. <strong>Pom</strong> projects become modules. That way grouping your flex projects to give them common dependencies becomes very easy. That is what I have done for the sample.</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/bo-dir-struct.png" alt="bo_dir_struct.png" border="0" width="236" height="258"/></p>
<p>Lets have a look at the dependencies and some build specifics. The parent pom contains the following dependencies: flex.sdk.version=3.2.0.3958, spring-actionscript=0.7.1, mate.version=0.8.7.1, flex-mojos.version=3.2.0 </p>
<pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;com.adobe.flex.framework&lt;/groupId&gt;
    &lt;artifactId&gt;flex-framework&lt;/artifactId&gt;
    &lt;version&gt;${flex.sdk.version}&lt;/version&gt;
    &lt;type&gt;pom&lt;/type&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-actionscript&lt;/artifactId&gt;
    &lt;version&gt;${spring-actionscript.version}&lt;/version&gt;
    &lt;type&gt;swc&lt;/type&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;com.asfusion&lt;/groupId&gt;
    &lt;artifactId&gt;mate&lt;/artifactId&gt;
    &lt;version&gt;${mate.version}&lt;/version&gt;
    &lt;type&gt;swc&lt;/type&gt;
&lt;/dependency&gt;
&lt;!-- testing --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.sonatype.flexmojos&lt;/groupId&gt;
    &lt;artifactId&gt;flexmojos-unittest-support&lt;/artifactId&gt;
    &lt;version&gt;${flex-mojos.version}&lt;/version&gt;
    &lt;type&gt;swc&lt;/type&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
<p>The build section for both of the flex modules is the same. The only difference is the packaging. For the security model it is <em>swc</em> and for the mate module it is <em>swf</em>. The mate modules is actually not a very good name, it contains the application, maybe I should call it main or so. The build section of the pom looks like this:</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;build&gt;
        &lt;sourceDirectory&gt;src/main/flex&lt;/sourceDirectory&gt;
        &lt;testSourceDirectory&gt;src/test/flex&lt;/testSourceDirectory&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.sonatype.flexmojos&lt;/groupId&gt;
                &lt;artifactId&gt;flexmojos-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;${flex-mojos.version}&lt;/version&gt;
                &lt;extensions&gt;true&lt;/extensions&gt;
                &lt;configuration&gt;
                    &lt;contextRoot&gt;/books-web&lt;/contextRoot&gt;
                    &lt;mergeResourceBundle&gt;true&lt;/mergeResourceBundle&gt;
                    &lt;resourceBundlePath&gt;${basedir}/src/main/locale/{locale}&lt;/resourceBundlePath&gt;
                    &lt;locales&gt;
                        &lt;locale&gt;en_US&lt;/locale&gt;
                        &lt;!--&lt;locale&gt;nl_NL&lt;/locale&gt;--&gt;
                    &lt;/locales&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
        &lt;defaultGoal&gt;install&lt;/defaultGoal&gt;
        &lt;resources&gt;
            &lt;resource&gt;
                &lt;directory&gt;${basedir}/src/main/resources&lt;/directory&gt;
            &lt;/resource&gt;
        &lt;/resources&gt;
    &lt;/build&gt;
</pre>
<p>The other big maven thing to configure is the server side. This you can find in the books-web project. There are dependencies for BlazeDS and the spring-flex project containing the BlazeDS spring integration. Please check the code if you want to see more of it. The last thing I want to show about maven are the repositories I use to find most of the artifacts. You do need to install some manually, but most of them come from an existing repository:</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;repositories&gt;
        &lt;repository&gt;
            &lt;id&gt;flex-mojos-repository&lt;/id&gt;
            &lt;url&gt;http://repository.sonatype.org/content/groups/public&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;true&lt;/enabled&gt;
            &lt;/releases&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/repository&gt;
        &lt;repository&gt;
            &lt;id&gt;fnh&lt;/id&gt;
            &lt;url&gt;http://fna.googlecode.com/svn/trunk/fna/fna_m2_repository/&lt;/url&gt;
        &lt;/repository&gt;
        &lt;repository&gt;
            &lt;id&gt;Servebox&lt;/id&gt;
            &lt;url&gt;http://maven.servebox.org/repository&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;true&lt;/enabled&gt;
            &lt;/releases&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/repository&gt;

        &lt;repository&gt;
            &lt;id&gt;spring-milestone&lt;/id&gt;
            &lt;name&gt;Spring Portfolio Milestone Repository&lt;/name&gt;
            &lt;url&gt;http://maven.springframework.org/milestone&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;true&lt;/enabled&gt;
            &lt;/releases&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/repository&gt;
    &lt;/repositories&gt;
    &lt;pluginRepositories&gt;
        &lt;pluginRepository&gt;
            &lt;id&gt;flex-mojos-repository&lt;/id&gt;
            &lt;url&gt;http://repository.sonatype.org/content/groups/public&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;true&lt;/enabled&gt;
            &lt;/releases&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/pluginRepository&gt;
    &lt;/pluginRepositories&gt;
</pre>
<p>Enough about maven, lets move on to the flex side.</p>
<h2>Introducing Mate, a flex framework</h2>
<p><img src="http://www.gridshore.nl/wp-content/uploads/mate-logo.png" alt="mate_logo.png" border="0" width="107" height="108" align="right" />Mate is a tag-based, event-driven Flex framework. At least that is what <a href="http://mate.asfusion.com/">the website</a> states. Event driven is very important. If you follow the recommended way to create your application you get a clean separation of front end components that show data, forms and interaction components. Each action should lead to an event, which is handled by Mate. Most of the logic is put into manager components.</p>
<p>Lets have a look at what happens when you click on the All Books button. The MainNavigation.mxml contains a button that calls the following code when the button is clicked.</p>
<pre class="brush: jscript; title: ; notranslate">
private function doObtainAllBooks():void {
    var event:BooksEvent = new BooksEvent(BooksEvent.OBTAIN_ALL_BOOKS);
    dispatchEvent(event);
}
</pre>
<p>As you can see, this only dispatches and event. Mate uses an mxml component with a lot of special tags to handle events. This handling can result in calling remote services, manager classes, dispatching new events and injecting data into view components. The following code block shows the capturing of this event, calling a remote service to obtain the books, giving the books to a manager, injecting the results into the AllBooks.mxml view component. Finally a new navigation event is dispatched to open the view component. The names of the tags give a clear description of what is going on.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;EventMap xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; xmlns=&quot;http://mate.asfusion.com/&quot;&gt;
    ...
    &lt;mx:RemoteObject id=&quot;booksService&quot;
                     endpoint=&quot;http://{props.host}:{props.port}/{props.webcontext}/messagebroker/amf&quot;
                     destination=&quot;remoteBookManager&quot;/&gt;

    &lt;EventHandlers type=&quot;{BooksEvent.OBTAIN_ALL_BOOKS}&quot; debug=&quot;true&quot;&gt;
        &lt;RemoteObjectInvoker instance=&quot;{booksService}&quot; method=&quot;obtainAllBooks&quot;&gt;
            &lt;resultHandlers&gt;
                &lt;MethodInvoker generator=&quot;{BooksManager}&quot; method=&quot;storeBooks&quot; arguments=&quot;{resultObject}&quot;/&gt;
                &lt;EventAnnouncer generator=&quot;{MainNavigationEvent}&quot; type=&quot;{MainNavigationEvent.NAVIGATION}&quot;&gt;
                    &lt;Properties navigationId=&quot;{MainNavigationEvent.ALL_BOOKS}&quot;/&gt;
                &lt;/EventAnnouncer&gt;
            &lt;/resultHandlers&gt;
        &lt;/RemoteObjectInvoker&gt;
    &lt;/EventHandlers&gt;
    &lt;Injectors target=&quot;{AllBooks}&quot;&gt;
        &lt;PropertyInjector source=&quot;{BooksManager}&quot; sourceKey=&quot;books&quot; targetKey=&quot;books&quot;/&gt;
    &lt;/Injectors&gt;
    ...
&lt;/EventMap&gt;
</pre>
<p>Now have a look at the code of the <em>BooksManager</em> component. Calling the actual remote object and transforming java objects into flex objects is done using BlazeDS. More on this later on. The objects that you get back are Books.</p>
<pre class="brush: jscript; title: ; notranslate">
public class BooksManager {
    [Bindable]public var books:ArrayCollection = new ArrayCollection();

    public function storeBooks(obj:Object):void {
        books = ArrayCollection(obj);
    }
}

[Bindable]
[RemoteClass(alias=&quot;nl.gridshore.samples.books.domain.Book&quot;)]
public class Book {
    public var id:Number;
    public var title:String;
    public var isbn:String;
    public var authors:ArrayCollection = new ArrayCollection();

    public function Book() {
    }

    public function addAuthor(author:Author):void {
        authors.addItem(author);
    }
}
</pre>
<p>That was your crash coarse in Mate. If you want to know more about the basics, be sure to check out their website. A lot of links to other good resources are available. Time to move on. For the security part I need to extend Mate. That is what the next section is about</p>
<h2>Implementing authentication in the flex client</h2>
<p>With respect to the authentication there are three different events that take place:</p>
<ul>
<li>Check if needs authentication &#8211; If the current client is not authenticated the login form must be presented</li>
<li>Try authentication &#8211; check the provided credentials, show an error message if authentication fails or go to the initial screen.</li>
<li>Logout &#8211; logout from the client</li>
</ul>
<p>The handling of these three events can be found in the SecurityEventMap.mxml component. This part of the solution has changed the most with respect to previous versions of the sample. In the current release I make use of the standard capabilities of the flex class <a href="http://livedocs.adobe.com/flex/3/langref/mx/messaging/ChannelSet.html">mx.messaging.ChannelSet</a>. I have created an extension to interact with this channelset using tags, the <strong>ChannelSetInvoker</strong>. Creating this class was not easy to me, there is <a href="http://mate.asfusion.com/page/how-to/extend-mate">a document that can help</a> and the source code from existing tags is very helpful. I run by some things I learned while creating the extension.</p>
<p>A very important part is to make a difference to properties that you need to configure the component and arguments to the methods being called. The ChannelSet will not change and can be provided as a property. The username and password for the login method are arguments to the method and need to be provided as arguments. Within the source code you can see the difference as well, the ChannelSet is a property of the component, while username and password are not really visible in the code. The ChannelSetInvoker component uses the ResultEvent and the FaultEvent to communicate with handlers. You can register handlers in the Mate event mapping component. Of course we need to registers these handlers within the component. This is done in the complete function</p>
<pre class="brush: jscript; title: ; notranslate">
    override protected function complete(scope:IScope):void {
        if (this.resultHandlers &amp;&amp; resultHandlers.length &gt; 0) {
            this.createInnerHandlers(scope, ResultEvent.RESULT, resultHandlers);
        }
        if (this.faultHandlers &amp;&amp; faultHandlers.length &gt; 0) {
            this.createInnerHandlers(scope, FaultEvent.FAULT, faultHandlers);
        }
    }
</pre>
<p>Time to move on to the fun part, the actual interaction with the ChannelSet. The components supports three methods (think about the three events we needed): login, logout and authenticated. The magic takes place in the run function.</p>
<pre class="brush: jscript; title: ; notranslate">
    override protected function run(scope:IScope):void {
        var argumentList:Array = (new SmartArguments()).getRealArguments(scope, this.arguments);
        innerHandlersDispatcher = channelSet;

        if (method == &quot;login&quot;) {
            if (!channelSet.authenticated) {
                var loginToken:AsyncToken = channelSet.login(argumentList[0], argumentList[1]);
                loginToken.addResponder(new AsyncResponder(
                        function(event:ResultEvent, token:Object = null):void {
                            scope.lastReturn = event.result;
                            innerHandlersDispatcher.dispatchEvent(event);
                        },
                        function(event:FaultEvent, token:Object = null):void {
                            scope.lastReturn = event.fault;
                            innerHandlersDispatcher.dispatchEvent(event);
                        }));
            }
        } else if (method == &quot;logout&quot;) {
            var logoutToken:AsyncToken = channelSet.logout();
            logoutToken.addResponder(new AsyncResponder(
                    function(event:ResultEvent, token:Object = null):void {
                        innerHandlersDispatcher.dispatchEvent(event);
                    },
                    function(event:FaultEvent, token:Object = null):void {
                        innerHandlersDispatcher.dispatchEvent(event);
                    }));
        } else if (method == &quot;authenticated&quot;) {
            var isAuthenticated:Boolean = channelSet.authenticated;
            scope.lastReturn = isAuthenticated;
            var event:ResultEvent = new ResultEvent(&quot;user is authenticated?&quot;, false, true, isAuthenticated);
            innerHandlersDispatcher.dispatchEvent(event);
        }
    }
</pre>
<p>Check how we use the provided arguments in the login method handling. AsyncToken objects are used to handle the asynchronous results of the login and logout methods. Finally the innerHandlerDispatcher is used to notify the registered handlers of new results. For the final piece of the puzzle, have a look at the implementation of the event handling. Due to the names of the tags the code is self explanatory.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;EventMap xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; xmlns=&quot;http://mate.asfusion.com/&quot;
          xmlns:extensions=&quot;extensions.*&quot;&gt;
    &lt;mx:ChannelSet id=&quot;authenticationChannelSet&quot;&gt;
        &lt;mx:AMFChannel id=&quot;myAmf&quot; uri=&quot;http://{props.host}:{props.port}/{props.webcontext}/messagebroker/amf&quot;/&gt;
    &lt;/mx:ChannelSet&gt;

    &lt;!-- Event handlers --&gt;
    &lt;EventHandlers type=&quot;{AuthenticationEvent.TRY}&quot; debug=&quot;true&quot;&gt;
        &lt;extensions:ChannelSetInvoker method=&quot;login&quot;
                                      channelSet=&quot;{authenticationChannelSet}&quot;
                                      arguments=&quot;{[event.username,event.password]}&quot;&gt;
            &lt;extensions:resultHandlers&gt;
                &lt;MethodInvoker generator=&quot;{AuthenticationManager}&quot; method=&quot;logInSuccess&quot;
                               arguments=&quot;{currentEvent.result}&quot;/&gt;
            &lt;/extensions:resultHandlers&gt;
            &lt;extensions:faultHandlers&gt;
                &lt;MethodInvoker generator=&quot;{AuthenticationManager}&quot; method=&quot;storeAuthenticationProblem&quot;
                               arguments=&quot;{currentEvent.fault}&quot;/&gt;
            &lt;/extensions:faultHandlers&gt;
        &lt;/extensions:ChannelSetInvoker&gt;
    &lt;/EventHandlers&gt;

    &lt;EventHandlers type=&quot;{AuthenticationEvent.CHECK_NEEDS}&quot; debug=&quot;true&quot;&gt;
        &lt;extensions:ChannelSetInvoker method=&quot;authenticated&quot; channelSet=&quot;{authenticationChannelSet}&quot;&gt;
            &lt;extensions:resultHandlers&gt;
                &lt;MethodInvoker generator=&quot;{AuthenticationManager}&quot; method=&quot;isAuthenticated&quot;
                               arguments=&quot;{currentEvent.result}&quot;/&gt;
            &lt;/extensions:resultHandlers&gt;
        &lt;/extensions:ChannelSetInvoker&gt;
    &lt;/EventHandlers&gt;

    &lt;EventHandlers type=&quot;{AuthenticationEvent.LOGOUT}&quot; debug=&quot;true&quot;&gt;
        &lt;extensions:ChannelSetInvoker method=&quot;logout&quot; channelSet=&quot;{authenticationChannelSet}&quot;&gt;
            &lt;extensions:resultHandlers&gt;
                &lt;MethodInvoker generator=&quot;{AuthenticationManager}&quot; method=&quot;logout&quot;/&gt;
            &lt;/extensions:resultHandlers&gt;
        &lt;/extensions:ChannelSetInvoker&gt;
    &lt;/EventHandlers&gt;
&lt;/EventMap&gt;
</pre>
<p>To be able to actually authenticate, we need a server component as well. With the RC2 release of the spring-flex project this has become incredibly easy. The next section talks about that part of the application.</p>
<h2>Spring-flex, how easy can it be.</h2>
<p>I do want to stress that the documentation coming with spring-flex is a good read. I recommend to read it to see all options that you have. For now I discuss only the basic steps.</p>
<p><a href="http://static.springframework.org/spring-flex/docs/1.0.x/reference/html/ch04s02.html">http://static.springframework.org/spring-flex/docs/1.0.x/reference/html/ch04s02.html</a></p>
<ul>
<li>Configure the web.xml, add the dispatcher servlet and the springSecurityFilterChain for the initialization of spring security.</li>
<li>I added one servlet mapping for *.properties. This is for loading the config.properties file through a spring bean. Check my post <a href="http://www.gridshore.nl/2009/01/23/flex-remoting-without-configuring-the-client/">flex remoting without configuring the client</a> to find out more on this topic.</li>
<li>Configure BlazeDS using the services-config.xml file in the default location WEB-INF/flex. Remember that we do not need this file in the flex client anymore like we did in the past. It is also this file where you configure BlazeDS logging.</li>
<li>Configure the security, be sure to look good before it is over.</li>
</ul>
<pre class="brush: xml; title: ; notranslate">
    &lt;!-- Bootstraps and exposes the BlazeDS MessageBroker --&gt;
    &lt;flex:message-broker&gt;
        &lt;flex:secured /&gt;
    &lt;/flex:message-broker&gt;

    &lt;!-- remote proxies --&gt;
    &lt;flex:remoting-destination destination-id=&quot;remoteBookManager&quot; ref=&quot;bookManager&quot; exclude-methods=&quot;internalUseStoreBook&quot;/&gt;

    &lt;security:http entry-point-ref=&quot;preAuthenticatedEntryPoint&quot;/&gt;

    &lt;bean id=&quot;preAuthenticatedEntryPoint&quot;
        class=&quot;org.springframework.security.ui.preauth.PreAuthenticatedProcessingFilterEntryPoint&quot; /&gt;

    &lt;security:global-method-security&gt;
        &lt;security:protect-pointcut
            expression=&quot;execution(* nl.gridshore.samples.books.business.*Manager.store*(..))&quot;
            access=&quot;ROLE_ADMIN&quot;/&gt;
        &lt;security:protect-pointcut
            expression=&quot;execution(* nl.gridshore.samples.books.business.*Manager.obtain*(..))&quot;
            access=&quot;ROLE_USER&quot;/&gt;
    &lt;/security:global-method-security&gt;

    &lt;security:authentication-provider&gt;
        &lt;security:user-service&gt;
            &lt;security:user name=&quot;admin&quot; password=&quot;admin&quot; authorities=&quot;ROLE_USER, ROLE_ADMIN&quot;/&gt;
            &lt;security:user name=&quot;user&quot; password=&quot;user&quot; authorities=&quot;ROLE_USER&quot;/&gt;
        &lt;/security:user-service&gt;
    &lt;/security:authentication-provider&gt;
</pre>
<p>As you can see, most of the configuration deals with method-security and the authentication provider. It takes around 5 lines of code to configure spring security to receive all incoming authentication requests and connect to BlazeDS security. I think this is pretty amazing. During the refactoring I could remove a lot of configuration and a java class. Also the client code has become a lot easier and adheres to standards of flex remoting.</p>
<h2>Concluding</h2>
<p>That is it, now we have a much cleaner sample. Be sure to check out the code and of course the referring frameworks. I also want to mention the extendability of the Mate framework. At first I had to understand some basic concepts, but than it become easy to write an extension. I hope you like the blog. Questions and commands are welcome.</p>
<p>See you again next time.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F05%2F24%2Fintegrate-flex-security-in-mate-using-the-spring-blazeds-integration-project%2F&amp;title=Integrate%20flex%20security%20in%20Mate%20using%20the%20spring%20BlazeDS%20integration%20project&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2009/05/24/integrate-flex-security-in-mate-using-the-spring-blazeds-integration-project/feed/</wfw:commentRss>
		<slash:comments>49</slash:comments>
		</item>
		<item>
		<title>Integration spring security (Acegi) and flex 3 the sequel</title>
		<link>http://www.gridshore.nl/2008/07/14/integration-spring-security-acegi-and-flex-3-the-sequel/</link>
		<comments>http://www.gridshore.nl/2008/07/14/integration-spring-security-acegi-and-flex-3-the-sequel/#comments</comments>
		<pubDate>Mon, 14 Jul 2008 14:00:12 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=155</guid>
		<description><![CDATA[<p></p> <p>In my previous blog post : integrating flex 3 with spring security I made a good effort to create a nice flex 3 application and integrate authentication and authorization with spring security. A few days a go I received a trackback from sven. Curious as I am I started reading the material he [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/flexlogo1.png" alt="flexlogo.png" border="0" width="100" height="100" align="left"/></p>
<p>In my previous blog post : <a href="http://www.gridshore.nl/2008/05/11/integrating-flex-3-with-spring-security-formerly-known-as-acegi/">integrating flex 3 with spring security</a> I made a good effort to create a nice flex 3 application and integrate authentication and authorization with spring security. A few days a go I received a <a href="http://www.mindtheflex.com/?p=67">trackback from sven</a>. Curious as I am I started reading the material he provided and especially the other links he mentioned. That made me think about my own solution. To be honest I think I did not really do a good job. It works, but still not optimal for most of the flex situations.</p>
<p>In my previous post I already mentioned the problem of sessions that are closed and exception handling with respect to security. In this article I am looking at the available mechanisms for security in flex. In this post I explain why I am not really using the flex or better BlazeDS security mechanisms and what you probably should use them for.</p>
<p>If this made you curious enough, read on. If you have questions, remarks or improvements, do not hesitate to use the comments feature of this blog item.</p>
<p><span id="more-155"></span></p>
<h2>The security problem</h2>
<p>The basic problem: we want to know who you are and we then what you are allowed to do. In other words, we want to use authentication to determine if you are who you say you are and authorization to determine what you are allowed to do. For web applications, authentication is a territory that is well known. There are lot&#8217;s of different ways to determine if you are who you say you are. Think about password, iris scan, finger print, tokens, etc. </p>
<p>When clients are becoming richer or fat, this does not have to change, but if you are creating applications that should function offline as well, you have some limitations. For my sample I am using a username/password combination. I am not using https, not using encryption. It is a basic sample. </p>
<p>I am going to show you a possible solution that uses some basic components to authenticate against a server side web application. Using BlazeDS we are talking direct to spring beans that are secured using spring security.</p>
<h2>Flex and BlazeDS security mechanism for remoting</h2>
<p>BlazeDS has a few things that can help you to secure the remote calls from the web client. You can configure security for remote destinations. This way BlazeDS makes sure you have been authenticated and have the required role. The following piece of code gives an example of a destination that is secured. The destination references a security-constraint that is also presented in the code.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;destination id=&quot;bookManager&quot;&gt;
    &lt;properties&gt;
        &lt;factory&gt;spring&lt;/factory&gt;
        &lt;source&gt;bookManager&lt;/source&gt;
    &lt;/properties&gt;
    &lt;security&gt;
        &lt;security-constraint ref=&quot;trusted&quot;/&gt;
    &lt;/security&gt;
    &lt;security-constraint id=&quot;trusted&quot;&gt;
        &lt;auth-method&gt;Custom&lt;/auth-method&gt;
        &lt;roles&gt;
            &lt;role&gt;ROLE_USER&lt;/role&gt;
        &lt;/roles&gt;
    &lt;/security&gt;
&lt;/destination&gt;
</pre>
<p>This way the user is asked for a username/password using for instance using Basic authentication. This mechanism makes use of the application server. Since not all application servers use the same mechanism for authentication there are special implementations available for a number of application servers. If you want to use an application level authentication you need to create a custom LoginCommand.</p>
<p>At first I thought this was the way to go, to be honest I never really understood it. So maybe I am missing something. For now I think my solutions is more flexible and easier to understand for an average java programmer. Therefore the flex/BlazeDS model was not the way to go for me. Let&#8217;s go over to a general view of my solution.</p>
<h2>Overview of my solution</h2>
<p>I am a java programmer coming to the flex world. Therefore my solution might be a bit to java-ish. Since I am integrating with java and spring security specifically, I do not really mind. The following things were important to me when creating the solution:</p>
<ul>
<li>No double configuration of roles for authorization, but the flex application must have the availability of obtained authorizations.</li>
<li>Easy recovery in case of exception due to bad credentials, unauthorized access of remote methods, session time out, etc.</li>
<li>No necessity for offline working (no authentication details available in the client)</li>
<li>Possibility of re-authentication in case of a session time out without asking for credentials again.</li>
</ul>
<p>This all can be done using some hierarchy in classes, use of singletons for user data and custom events. The following image gives a schematic overview of the solution. You are missing the actual pages: Home and AuthenticationForm. You are also missing the actual service implementations on the server side. Both topics will be talked about later on.</p>
<h3>Remote services, error handling and events.</h3>
<p><img src="http://www.gridshore.nl/wp-content/uploads/flexdiagrams.jpg" alt="FlexDiagrams.jpg" border="0" width="458" height="430" />
</p>
<p>The image shows the main components for authentication and authorization from the flex side. The yellow classes are provided by the framework, the green ones are services that interact with remote services and the data obtained from the server. The blue ones are the events used by the security mechanism to expose the results of authentication and authorization requests.
</p>
<p>Let&#8217;s start with the services. The super class <strong>RemoteService</strong> contains some generic methods for catching and translating them into events. The constructor excepts an id and the name of the destination for the <strong>RemoteObject</strong> to create. Beware that this name should be the same as configured in the destination of the <strong>remoting-config.xml</strong>. The next block of code shows you the implementation of this RemoteService</p>
<pre class="brush: java; title: ; notranslate">
/**
 * Super class for all remote services that contains some generic methods.
 */
public class RemoteService {
    private static var BAD_CREDENTIALS:String =
            &quot;org.springframework.security.BadCredentialsException : Bad credentials&quot;;
    protected var remoteObject:RemoteObject;

    /**
     * Constructor accepting an id and destination for the actual RemoteObject to create. An event listener
     * is added for exceptions.
     * @param id String representing the id of the new RemoteObject to create
     * @param destination String representing the destination of the RemoteObject to create
     */
    public function RemoteService(id:String, destination:String) {
        this.remoteObject = new RemoteObject(id);
        this.remoteObject.destination = destination;
        this.remoteObject.addEventListener(FaultEvent.FAULT,onRemoteException);
    }

    /**
     * generic fault event handler for all remote object actions. based on the received message an action
     * is taken, mostly throwing a new event.
     * @param event FaultEvent received for handling
     */
    public function onRemoteException(event:FaultEvent):void {
        trace('code : ' + event.fault.faultCode +
              ', message : ' + event.fault.faultString +
              ',detail : ' + event.fault.faultDetail);

        if (event.fault.faultString == BAD_CREDENTIALS) {
            Application.application.dispatchEvent(
                    new AuthenticationFailureEvent(AuthenticationFailureEvent.AUTHENTICATION_FAILURE,
                            &quot;problem while authenticating&quot;))
        } else {
            Application.application.dispatchEvent(
                    new RemoteExceptionEvent(RemoteExceptionEvent.REMOTE_EXCEPTION,
                            &quot;unknown problem occurred during a remote call : &quot; + event.fault.message));
        }
    }
}
</pre>
<p>The onRemoteException is not finished yet, at the moment we only handle BAD_CREDENTIALS differently than other exceptions. I can imagine that we will have more exceptions here. But for now the structure is clear. Most important to notice is the use of events. Using the special Application object, we dispatch the AuthenticationFailureEvent as well as the RemoteExceptionEvent. The next thing is to create a sub-class of this service that actually uses the connection. So let&#8217;s have a look at the <strong>SecurityService</strong></p>
<p>The SecurityService is used to authenticate a user making use of the provided username and password. The following block of code contains the implementation if this method:</p>
<pre class="brush: java; title: ; notranslate">
public function authenticatePrincipal(username:String,password:String):void {
    var userData:UserData = UserData.getInstance();
    userData.username = username;
    userData.password = password;
    remoteObject.authenticatePrincipal.addEventListener(ResultEvent.RESULT,handleAuthenticatePrincipal);
    remoteObject.authenticatePrincipal(username,password);
}
</pre>
<p>Important in this piece of code is obtaining the singleton UserData instance. This instance contains the credentials and has some utility methods to see if the logged in user has administrative rights or is a plain user. The way to get the results back looks a bit strange to the average java programmer, but we are doing a-synchronous calls (like JMS guys). The next piece of code gets called if the response is received and handles this response.</p>
<pre class="brush: java; title: ; notranslate">
protected function handleAuthenticatePrincipal(event:ResultEvent):void {
    var userData:UserData = UserData.getInstance();
    userData.authenticated = true;

    var obj:Object = event.result;
    var obtainedRoles:Array = obj.roles as Array;
    for(var i:int=0; i &lt; obtainedRoles.length; i++) {
        userData.addGrantedRole(obtainedRoles[i])
    }

    Application.application.dispatchEvent(
            new AuthenticationEvent(AuthenticationEvent.AUTHENTICATION,&quot;user is authenticated&quot;));
};
</pre>
<p>As you can see in the code we tell the userData object that he is authenticated now and we add the roles he is authorized for. To make sure that those that are interested get notified of the authentication we throw an event.</p>
<p>The next step is to actually start the authentication process. This is done on the visual components. The first one that gets loaded is the <strong>Home.mxml</strong> page.</p>
<h3>Visible components interacting with services</h3>
<p>To demonstrate the complete authentication process we need only two visual components: <strong>Home.mxml</strong> and <strong>AuthenticationForm.mxml</strong>. I am not going to show them completely, you can browse the sources only. (see references at the bottom). In Home.mxml we add listeners for the <strong>AuthenticationEvent</strong> as well as the <strong>RemoteExceptionEvent</strong>, then we create the form and add it to the main content panel. The following piece of code shows just that:</p>
<pre class="brush: java; title: ; notranslate">
private function initializeApplication():void {
    Application.application.addEventListener(AuthenticationEvent.AUTHENTICATION, handleAuthenticationEvent);
    Application.application.addEventListener(RemoteExceptionEvent.REMOTE_EXCEPTION, handleRemoteExceptionEvent);
    authenticateUser();
}

private function authenticateUser():void {
    myMainContentPanel.removeAllChildren();
    var authenticationForm:AuthenticationForm = new AuthenticationForm();
    authenticationForm.securityService = authenticationHelper;
    myMainContentPanel.addChild(authenticationForm);
}
</pre>
<p>As you can see in the code we call the method <strong> handleAuthenticationEvent </strong> when a user gets authenticated. This method is not interesting for our cause, it could just show <em>Yes, I am authenticated</em> in an alert box. Let&#8217;s have a look at the AuthenticationForm now. This is also a pretty simple class with a call to the security service and a method that handles the a-synchronous callback.</p>
<pre class="brush: java; title: ; notranslate">
private function submitLogin():void {
    submitButton.enabled = false;
    Application.application.addEventListener(
            AuthenticationFailureEvent.AUTHENTICATION_FAILURE,loginServiceFaultHandler);
    securityService.authenticatePrincipal(userName.text,password.text);
}

private function loginServiceFaultHandler(event:AuthenticationFailureEvent):void {
    authenticationMessage.text = &quot;Problem while authentication ...&quot;;
    authenticationMessage.visible = true;
    submitButton.enabled = true;
}
</pre>
<p>As you can see, the AuthenticationFailureEvent is handled by this form page. We show just a text that there was something wrong. In any other cases we let the Home page catch the AuthenticationEvent, we do nothing here.</p>
<p>Final part to cover is the server side implementation. That is what we&#8217;ll do next.</p>
<h3>Server side implementations of remote services</h3>
<p>Within the <strong>remoting-config.xml</strong> I have configured the following destination:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;destination id=&quot;authenticationHelper&quot;&gt;
    &lt;properties&gt;
               &lt;source&gt;nl.gridshore.samples.books.web.security.security.AuthenticationHelper&lt;/source&gt;
    &lt;/properties&gt;
&lt;/destination&gt;
</pre>
<p>Within the class <strong>Authenticationhelper</strong> you can find the following method that obtains the spring application context, executes the authentication and handles the obtained principal. Take notice of the name of the bean we obtain. This is the default name when using the namespace configuration of spring-security. The other important part is the creation of the UsernamePasswordAuthenticationToken and doing the actual authentication. Problems with authentication result in a runtime exception that is propagated into flex and handled by the RemoteService object.</p>
<pre class="brush: java; title: ; notranslate">
public AuthorizationData authenticatePrincipal(String username, String password) {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(
            flex.messaging.FlexContext.getServletConfig().getServletContext());
    AuthenticationManager manager = (AuthenticationManager)appContext.getBean(&quot;_authenticationManager&quot;);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
            new UsernamePasswordAuthenticationToken(username,password);

    Authentication authentication = manager.authenticate(usernamePasswordAuthenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);

    GrantedAuthority[] authorities =
            SecurityContextHolder.getContext().getAuthentication().getAuthorities();
    int numAuthorities = authorities.length;
    String[] grantedRoles = new String[numAuthorities];
    for (int counter = 0; counter &lt; numAuthorities ; counter++) {
        grantedRoles[counter] = authorities[counter].getAuthority();
    }
    String name = SecurityContextHolder.getContext().getAuthentication().getName();
    return new AuthorizationData(grantedRoles,name);
}
</pre>
<p>That is about it, if you feel this is the way to go, check the sources in my google code repo. If you have strong opinion that this is just wrong, please share your thoughts.</p>
<h2>References</h2>
<ul>
<li><a href="http://code.google.com/p/gridshore/source/browse">Google code project (browse to books-overview)</a></li>
<li><a href="http://www.mindtheflex.com/?p=67">Mind the flex by sven</a></li>
<li><a href="http://www.gridshore.nl/2008/05/11/integrating-flex-3-with-spring-security-formerly-known-as-acegi/">Integrating flex 3 with spring security (formerly known as Acegi)</a></li>
</ul>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F07%2F14%2Fintegration-spring-security-acegi-and-flex-3-the-sequel%2F&amp;title=Integration%20spring%20security%20%28Acegi%29%20and%20flex%203%20the%20sequel&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/07/14/integration-spring-security-acegi-and-flex-3-the-sequel/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Feeling secure with Web Services &#8211; Part 3 &#8211; Digital Signature</title>
		<link>http://www.gridshore.nl/2008/06/01/feeling-secure-with-web-services-part-3-digital-signature/</link>
		<comments>http://www.gridshore.nl/2008/06/01/feeling-secure-with-web-services-part-3-digital-signature/#comments</comments>
		<pubDate>Sun, 01 Jun 2008 15:10:55 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[signing]]></category>
		<category><![CDATA[web service]]></category>
		<category><![CDATA[webservices]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2008/06/01/feeling-secure-with-web-services-part-3-digital-signature/</guid>
		<description><![CDATA[<p>There seems to be a lot of misunderstanding about Web Service security. Using password authentication doesn&#8217;t prevent unauthorized users to access your data, while SSL / HTTPS doesn&#8217;t give you any information about who is trying to access your services. And did you ever think of signing you messages with a digital signature?</p> <p>In [...]]]></description>
			<content:encoded><![CDATA[<p>There seems to be a lot of misunderstanding about Web Service security. Using password authentication doesn&#8217;t prevent unauthorized users to access your data, while SSL / HTTPS doesn&#8217;t give you any information about who is trying to access your services. And did you ever think of signing you messages with a digital signature?</p>
<p>In my introductory post I&#8217;ve elaborated on what type of security we&#8217;d typically want on Web Services.</p>
<p>In <a href="http://www.gridshore.nl/2008/05/20/feeling-secure-with-web-services-part-1-the-usernametoken/">part 1</a> , I&#8217;ve dealt with Username Token authentication, an easy to use way to provide an authentication mechanism for your web service.</p>
<p>In <a href="http://www.gridshore.nl/2008/05/26/feeling-secure-with-web-services-part-2/">part 2</a> , I have described Transport Layer Security (TLS) -formerly known as Secure Socket Layer- and message encryption.</p>
<p>In this part, the last one in this series, I will explain how the the digital signature can provide some form of security in web services.</p>
<p><span id="more-135"></span></p>
<p>Lets recap the security requirements I have discussed in my <a href="http://www.gridshore.nl/2008/05/17/feeling-secure-with-web-services-introduction/">introduction</a> .</p>
<ol>
<li>The client must be sure it sends it messages to the correct provider;</li>
<li>The provider wants to be sure that the client is authorized to;</li>
<li>The provider wants to be sure that the client is who it says it is;</li>
<li>Both the consumer and provider want to be sure that the messages can only be interpreted by each other;</li>
<li>Both parties want to be sure that the message sent is received unchanged.</li>
</ol>
<p>So far, we have dealt with the first four requirements by implementing Encryption or TLS/SSL or by requiring a UsernameToken from the client. But until now, we are still not the guaranteed that the messages are unmodified since we&#8217;ve sent them.</p>
<p>Encryption will prevent modification during the transport between the sender and the final recipient, the one with the private key to decrypt the message. However, once decrypted, the message is free to be modified.</p>
<p>Digital invoices are an example of documents that should be digitally signed. In some countries (in The Netherlands in any case) the Belastingdienst (Tax authority) requires that all digital invoices are digitally signed by the company sending the invoice. This way, the Belastingdienst is able to verify who sent the invoice -the one who signed it- and be sure that it hasn&#8217;t been tampered with in the meantime. Of course, the company receiving this invoice wouldn&#8217;t really mind to have these guarantees too, I suppose.</p>
<p>Now that we have a real valid use case and are really convinces of the need of the digital signature, let&#8217;s have a look at how it works.</p>
<p>Actually, it is almost identical to encryption, but then in the opposite way. With encryption, the message is encrypted using the public key. Only the one with access to the private key can decrypt it. When signing, the private key is used to sign the message, and the public key is used to check the signature. Since access to the private key is limited to authorized people/machines, only they can sign the message. Anyone can access the public part of the key -hence &#8220;public&#8221;-, meaning that anyone can check the signature.</p>
<p>When a message is signed, the actual message itself is not encrypted. That wouldn&#8217;t be very meaningful, because that would mean that anyone would have to decrypt the message, even though they might not really care about the signature. Instead, a hash is creating from all the parts that have to be signed. That hash is then encrypted using the private key. The encrypted has is then inserted in (the header of) the message. Typically, one would also include the public key, to allow anyone to check your signature. That&#8217;s it.</p>
<p>To check a signature, the hash is recreated the same way as it was done originally and the encrypted hash from the signer is decrypted. If the message has not been tampered with, the newly generated hash and the decrypted original hash are identical. If they are different, you know the message has been tampered with.</p>
<p>The signature on the message will ensure the reader that the message has not been modified since it has signed sent and that the contents were created by, or created with the consent of, the user who signed it. If you want to see it in action, you can download the example code from the <a href="http://code.google.com/p/gridshore/source/checkout">Gridshore google code repository</a>. The demo uses all three forms of security described in this series.</p>
<p>This concludes this three-part article about web service security. The type of security you would choose for your web service clearly depends on the needs of your specific service. UsernameToken provides for an easy to use authentication mechanism, while TLS or message encryption prevents a third party from reading the messages. Finally, the digital signature will ensure that a message is not modified after it is signed.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F06%2F01%2Ffeeling-secure-with-web-services-part-3-digital-signature%2F&amp;title=Feeling%20secure%20with%20Web%20Services%20-%20Part%203%20-%20Digital%20Signature&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/06/01/feeling-secure-with-web-services-part-3-digital-signature/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Feeling secure with Web Services &#8211; Part 2</title>
		<link>http://www.gridshore.nl/2008/05/26/feeling-secure-with-web-services-part-2/</link>
		<comments>http://www.gridshore.nl/2008/05/26/feeling-secure-with-web-services-part-2/#comments</comments>
		<pubDate>Mon, 26 May 2008 19:23:04 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[authorization]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[web service]]></category>
		<category><![CDATA[webservices]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2008/05/26/feeling-secure-with-web-services-part-2/</guid>
		<description><![CDATA[<p>There seems to be a lot of misunderstanding about Web Service security. Using password authentication doesn&#8217;t prevent unauthorized users to access your data, while SSL / HTTPS doesn&#8217;t give you any information about who is trying to access your services. And did you ever think of signing you messages with a digital signature?</p> <p>In [...]]]></description>
			<content:encoded><![CDATA[<p>There seems to be a lot of misunderstanding about Web Service security. Using password authentication doesn&#8217;t prevent unauthorized users to access your data, while SSL / HTTPS doesn&#8217;t give you any information about who is trying to access your services. And did you ever think of signing you messages with a digital signature?</p>
<p>In my <a href="http://www.gridshore.nl/2008/05/17/feeling-secure-with-web-services-introduction/">introductory post</a> I&#8217;ve elaborated on what type of security we&#8217;d typically want on Web Services.</p>
<p>In <a href="http://www.gridshore.nl/2008/05/20/feeling-secure-with-web-services-part-1-the-usernametoken/">part 1</a> , I&#8217;ve dealt with Username Token authentication.</p>
<p>In this article, I will describe Transport Level Security (TLS), formerly known as Secure Socket Layer and message encryption.</p>
<p><span id="more-134"></span></p>
<p>Lets recap the security requirements I have discussed in my introduction.</p>
<ol>
<li>
<div>The client must be sure it sends it messages to the correct provider;</div>
</li>
<li>
<div>The provider wants to be sure that the client is authorized to;</div>
</li>
<li>
<div>The provider wants to be sure that the client is who it says it is;</div>
</li>
<li>
<div>Both the consumer and provider want to be sure that the messages can only be interpreted by each other;</div>
</li>
<li>
<div>Both parties want to be sure that the message sent is received unchanged.</div>
</li>
</ol>
<p><em><span style="text-decoration: underline;">Transport Level Security</span></em></p>
<p>Using &#8220;Transport Level Security&#8221; (TLS), formerly known as Secure Socket Layer (SSL), and also referred to as HTTPS, will take care of requirements 1 and 4.</p>
<p>TLS is a technically very complex algorithm, with a lot of varieties. Fortunately, the general concept is not as hard to grasp. It works as follows:</p>
<ol>
<li>
<div>The client will send a &#8220;Hello&#8221; to the server.</div>
</li>
<li>
<div>The server will response with a &#8220;Hello&#8221;, and send a certificate to the client</div>
</li>
<li>
<div>The client will decide whether it trusts the server&#8217;s certificate</div>
</li>
<li>
<div>The client will use the servers certificate to encrypt its own certificate and send it back to the server</div>
</li>
<li>
<div>Depending on the exact algorithm chosen, the client and server will exchange some more encryption information to make the communication &#8220;water tight&#8221;.</div>
</li>
</ol>
<p>If you really want to know the technical details of TLS, have a look at this page: <a href="http://an.wikipedia.org/wiki/Secure_Sockets_Layer">http://an.wikipedia.org/wiki/Secure_Sockets_Layer</a>. For the typical Web Service developer, these details are not really important. However, knowledge of how the first three steps work can help you prevent a lot of problems.</p>
<p>Especially step 3 is of great importance. The client has received a certificate from the server, and has to decide whether it is safe. This decision is based on a few factors.</p>
<p>First of all, the certificate has to have been issued for the domain that has been requested. So if you access a service on http://somecompany.com/service and get a certificate issued for someothercompany.org, the client will reject the certificate. Some clients, such as web browsers allow the users to override this decision and accept the certificate anyway. A web service client doesn&#8217;t typically have a user, so there is no room for second chances.</p>
<p>Secondly, the certificates timestamp has to be valid, meaning that it hasn&#8217;t reached it&#8217;s expiry date yet. Depending of the type of certificate, it is valid from 1 to tens of years.</p>
<p>The third requirement can sometimes give some problems: the client has to <em>trust</em> the certificate. This can best be explained using a real life example. Imagine yourself at the border control on a foreign airport. If you show them a paper with your name and a signature on it, chances are small that they let you through? Why? Because they can&#8217;t trust a self-signed certificate, or one that is signed by a relative. However, if that same name is written on a legal passport, given and signed by your country&#8217;s authority, border control will trust it, because they trust them. In TLS, it is exactly the same.</p>
<p>If you order a certificate from a certificate authority (CA), nobody will actually know that you have that certificate. And you don&#8217;t trust what you don&#8217;t know. However, you have paid the CA to sign your certificate. And maybe the CA certificate has been signed with yet another certificate. Now, if you trust the CA, you will automatically trust all certificates that have been signed with that CA. Back to our border control. If you trust the US government to issue correct passports to people, you will automatically trust all passports of US citizens, even if you don&#8217;t know that person.</p>
<p>To mark a certificate as trusted, the certificate has to be stored in a so-called &#8220;trust store&#8221;. Your browser has a truststore that includes the large CA certificates by default. Just look around in the configuration of your browser. You&#8217;ll be able to install other certificates if you like. For example, one that you have created and signed yourself.</p>
<p>You can also configure a truststore for your web service client. By default, your JVM will probably include the large CA certificates, such as Verisign and Thawte. If you&#8217;re running on an application server, chances are big there is a trust store configured in them, too. Of course, you can override the truststore by defining your own.</p>
<p>Ok, now that we&#8217;ve seen a lot of misery on the client side, let&#8217;s have a look at what has to happen on the server side. Well, luckily, not all that much. All you have to do is configure your web server to use SSL. Somewhere along the line it will require you configure a certificate to use. And since you probably want to be trusted, make sure to have your certificate signed by a large CA.</p>
<p>The good part is that all communication between client and server is encrypted in such a way, that only these parties are able to read the messages. And, as a bonus, the client is ensured that it is really talking to the server it was expecting to communicate with.</p>
<p><em><span style="text-decoration: underline;">Message encryption</span></em></p>
<p>TLS is nice, but if you have a message that will pass a few endpoints, or has to be logged in the mean time, it doesn&#8217;t really help you. If you have to keep your data secure after is has arrived at your first endpoint, message encryption could be your solution.</p>
<p>Let&#8217;s start off with an example. Let&#8217;s image we have a service where consumers can place orders. Just for the sake of the example, the request will first be processed by an endpoint that checks the stocks. If the stocks are sufficient, the payment is processed. If TLS were used between the consumer and the first endpoint, the message would be sent unencrypted. Of course it is possible to encrypt that communication too, but that would probably be a performance hit.</p>
<p>The idea behind encryption is not really complex. The entire message, or part of it is encrypted using the public key part of the certificate. Since the private key is required to decrypt it, only the recipient (or at least only systems with access to the private key) will be able to so. Even if a message is stored for future reference, the contents will be unreadable to any third party.</p>
<p>Typically, only parts of messages are encrypted. You could think of elements containing payment information or other private contents, such as social security numbers. The <a href="http://code.google.com/p/gridshore/source/checkout" target="_blank">example project in go ogle code </a>shows an example of a message where an ID is encrypted. Not a really powerful use case, but it shows how the technology works.</p>
<p>As with TLS, message encryption will deal with items 1 and 4. However, it will only do so for the parts of the message that have been encrypted.</p>
<p><em><span style="text-decoration: underline;">Conclusion</span></em></p>
<p>Both TLS and message encryption give the communication between consumer and provider some form or privacy and protection against eavesdropping. If configured correctly, they can work transparently to the implementation of both the client and the consumer, but will claim some of your performance.</p>
<p>My next and last article in this series will discuss message signing, which will deal with the security item that hasn&#8217;t been covered yet: &#8220;Both parties want to be sure that the message is received unchanged&#8221;.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F05%2F26%2Ffeeling-secure-with-web-services-part-2%2F&amp;title=Feeling%20secure%20with%20Web%20Services%20-%20Part%202&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/05/26/feeling-secure-with-web-services-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Feeling secure with Web Services &#8211; Part 1 &#8211; The UsernameToken</title>
		<link>http://www.gridshore.nl/2008/05/20/feeling-secure-with-web-services-part-1-the-usernametoken/</link>
		<comments>http://www.gridshore.nl/2008/05/20/feeling-secure-with-web-services-part-1-the-usernametoken/#comments</comments>
		<pubDate>Tue, 20 May 2008 19:25:59 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[authorization]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[web service]]></category>
		<category><![CDATA[webservices]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2008/05/20/feeling-secure-with-web-services-part-1-the-usernametoken/</guid>
		<description><![CDATA[<p>Recently, I&#8217;ve been helping a customer with some Web Service issues. One of the problems was their limited knowledge of security in that area. He asked me to explain, in Jip and Janneke language [1] how SSL works and what it actually secures.</p> <p>There seems to be a lot of misunderstanding about Web Service [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I&#8217;ve been helping a customer with some Web Service issues. One of the problems was their limited knowledge of security in that area. He asked me to explain, in Jip and Janneke language [1] how SSL works and what it actually secures.</p>
<p>There seems to be a lot of misunderstanding about Web Service security. Using password authentication doesn&#8217;t prevent unauthorized users to access your services, while SSL / HTTPS doesn&#8217;t give you any information about who is trying to access your services. And did you ever think of signing you messages with a digital signature?</p>
<p>In my <a href="http://www.gridshore.nl/2008/05/17/feeling-secure-with-web-services-introduction/">introductory post</a> I&#8217;ve elaborated on what type of security we&#8217;d typically want on Web Services.</p>
<p>This article will go more in-depth in the Username Token authentication.</p>
<p><span id="more-133"></span></p>
<p>First, I&#8217;ll list the 5 security requirements we usually have to feel really secured. These have been treated in the introductory post in this series.</p>
<ol>
<li>
<div>The client must be sure it sends it messages to the correct provider;</div>
</li>
<li>
<div>The provider wants to be sure that the client is authorized to;</div>
</li>
<li>
<div>The provider wants to be sure that the client is who it says it is;</div>
</li>
<li>
<div>Both the consumer and provider want to be sure that the messages can only be interpreted by eachother;</div>
</li>
<li>
<div>Both parties want to be sure that the message sent is received unchanged.</div>
</li>
</ol>
<p>The username token will take care of items 2 and 3. The username token is typically a security header in the soap message from the client towards the server. This header contains a username and a password, in one form or another.</p>
<p>In the simplest form, a UsernameToken authentication header contains an element with a username and one with a password. This is the &#8220;PasswordText&#8221; option of the UsernameToken. When you send this message unencrypted, anyone would be able to read your username and password, an log in on your behalf. Encrypting the communication will solve this risk. However, if the message has to pass several endpoints and one of the connections in unencrypted, your password is open again, despite effort to secure it.</p>
<p>To prevent giving away the username and password combination for free, it is possible to use the &#8220;PasswordDigest&#8221; version of the UsernameToken. This will actually pass a hash of your password, instead of the password itself. This prevents malicious ears from plucking you password off the wire.</p>
<p>However, although the password is encrypted and unknown to any third party, that third party could log log in by copying the entire security header. After all, if one client can get in using that header, any client could. To prevent this, a Nonce and/or a Timestamp are made part of the hash too. The Nonce is a random value, chosen by the client. The Timestamp is the date and time the password was hashed.</p>
<p>So how does this prevent another user from replicating your authentication header? Well, if a Timestamp is used, the server could require that that timestamp may not be older than for example 5 minutes. This still gives the third party a 5 minute window to abuse your password. That&#8217;s where the Nonce comes in. The server can (and should) require that the Nonce may be used at most one time. If the same header -and thus the same nonce- is sent again, the UsernameToken is refused based on a duplicate nonce.</p>
<p>In the end, the security header could look like this:</p>
<p>&lt;wsse:Security xmlns:wsse=&#8221;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd&#8221; SOAP-ENV:mustUnderstand=&#8221;1&#8243;&gt; &lt;wsse:UsernameToken xmlns:wsu=&#8221;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd&#8221; wsu:Id=&#8221;UsernameToken-33083972&#8243; xmlns:wsse=&#8221;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd&#8221;&gt; &lt;wsse:Username xmlns:wsse=&#8221;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd&#8221;&gt;username&lt;/wsse:username&gt; &lt;wsse:Password Type=&#8221;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest&#8221; xmlns:wsse=&#8221;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd&#8221;&gt;Zb5nkZdaXM3hH/bVPQRdMdYSbdo=&lt;/wsse:password&gt; &lt;wsse:Nonce xmlns:wsse=&#8221;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd&#8221;&gt;hHDHOSh3akTwwZFs+6o13A==&lt;/wsse:nonce&gt; &lt;wsu:Created xmlns:wsu=&#8221;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd&#8221;&gt;2008-05-20T19:00:06.937Z&lt;/wsu:created&gt; &lt;/wsse:UsernameToken&gt; &lt;/wsse:Security&gt;</p>
<p>So, does this make us absolutely secured from any attacks? Well, the likelyhood of anyone abusing your security header is very slim, but nowhere near to zero. Hackers keep lists of commonly used passwords and can use these lists to guess your password. They will see which passwords will create the given hash using the Nonce and Timestamp you have provided. It is therefore very important to generate a password instead of choosing one which is easy to remember. Why would you anyway, a client is usually a piece of software that doesn&#8217;t really have difficulties remembering any password. It is of course still not water tight, but it is more likely that the service won&#8217;t exist anymore by the time the password has been guessed.</p>
<p>Another way to minimize the chance of abuse of your credentials is by encrypting the messages, or parts of it. This shall be treated in my next post in this series.</p>
<p>The configuration of UsernameToken security in your WebService is fairly simple. Both in client and server only little configuration is needed. There are libraries that can assist you in setting up security, such as <a href="http://ws.apache.org/wss4j/" target="_blank">Apache&#8217;s WSS4J</a> and <a href="https://xwss.dev.java.net/" target="_blank">Sun&#8217;s XWSS</a>. If you want to see these libraries at work, make sure you download the code samples for this series on the Gridshore code repository: <a href="http://code.google.com/p/gridshore/source/checkout">http://code.google.com/p/gridshore/source/checkout</a> [1].</p>
<p>If you want to go into a little (or a lot) more technical depth of the UsernameToken specification, make sure you read the OASIS WSS specification from <a href="http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=wss#technical">http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=wss#technical</a>.</p>
<p>This concludes this post about the UsernameToken. In my <a href="http://www.gridshore.nl/2008/05/26/feeling-secure-with-web-services-part-2/">next post </a>in this series, I will shed some light on Transport Level Security and Message Encryption.</p>
<hr />[1] Make sure you checkout the code in the /trunk/feeling-secure-with-webservices/ folder. If you check out the entire trunk, you&#8217;ll have to deal with lots of samples.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F05%2F20%2Ffeeling-secure-with-web-services-part-1-the-usernametoken%2F&amp;title=Feeling%20secure%20with%20Web%20Services%20-%20Part%201%20-%20The%20UsernameToken&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/05/20/feeling-secure-with-web-services-part-1-the-usernametoken/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Feeling secure with Web Services &#8211; Introduction</title>
		<link>http://www.gridshore.nl/2008/05/17/feeling-secure-with-web-services-introduction/</link>
		<comments>http://www.gridshore.nl/2008/05/17/feeling-secure-with-web-services-introduction/#comments</comments>
		<pubDate>Sat, 17 May 2008 13:45:27 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[authorization]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[web service]]></category>
		<category><![CDATA[webservices]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2008/05/17/feeling-secure-with-web-services-introduction/</guid>
		<description><![CDATA[<p>Recently, I&#8217;ve been helping a customer with some Web Service issues. One of the problems was their limited knowledge of security in that area. He asked me to explain, in Jip and Janneke language [1] how SSL works and what it actually secures.</p> <p>There seems to be a lot of misunderstanding about Web Service [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I&#8217;ve been helping a customer with some Web Service issues. One of the problems was their limited knowledge of security in that area. He asked me to explain, in Jip and Janneke language [1] how SSL works and what it actually secures.</p>
<p>There seems to be a lot of misunderstanding about Web Service security. Using password authentication doesn&#8217;t prevent unauthorized users to access your data, while SSL / HTTPS doesn&#8217;t give you any information about who is trying to access your services. And did you ever think of signing you messages with a digital signature?</p>
<p>In this article, I&#8217;ll explain the different methods of securing your Web Services, how each of the methods work and what you actually secure by applying each method.</p>
<p><span id="more-132"></span></p>
<p>First, let&#8217;s start with a definition of security. Wikipedia describes it as: &#8220;Security is the condition of being protected against danger or loss&#8221; [2]. This just means that you don&#8217;t want anyone stealing your data (expecially during transportation) or doing something unwanted with it. To feel secure in the Web Services area, we want to be assured of the following:</p>
<ol>
<li>
<div>The client must be sure it sends it messages to the correct provider;</div>
</li>
<li>
<div>The provider wants to be sure that the client is authorized to;</div>
</li>
<li>
<div>The provider wants to be sure that the client is who it says it is;</div>
</li>
<li>
<div>Both the consumer and provider want to be sure that the messages can only be interpreted by eachother;</div>
</li>
<li>
<div>Both parties want to be sure that the message sent is received unchanged.</div>
</li>
</ol>
<p>I will briefly explain each of these items.</p>
<p>Let&#8217;s start with the first item. The client is the one initiating the connection. Typically by accessing a URL. For example, http://services.somecompany.com/someService. However, messages towards this endpoint are routed through many routers, switches and proxy servers around the internet. How can you be sure that your messages don&#8217;t end up in the servers of &#8220;some competiting company&#8221;?</p>
<p>On the other side of the connection we want a similar kind of ensurance. How can you be sure that the message comes from a client that has been authorized to access that service? And how do you know the message really comes from that client and not from someone pretending to be an authorized client? Quite often, the use of services is paid for, and you&#8217;d want to be sure that nobody is using your services without paying for it.</p>
<p>Regarding the fourth item, just imagine sending a request to a web service provider with an order. That order will probably contain some order items, an address and payment information. If anyone can read that information, it is only a matter of minutes before the credit card number has been abused. We want to be absolutely sure that only the client and the server are aware of the contents of the messages.</p>
<p>And finally, if a message has been tampered with, we want both the client and the server to be able to reject that message. After all, when sending the order again, we wouldn&#8217;t want our competitor to intercept the message, change the delivery address to their own (although that would be really easy to trace for law enforcement) and forward the message to the service provider. In some countries, at least in The Netherlands, the tax authority requires that digital invoices are signed by the sender using a trusted digital certificate.</p>
<p>There are several tools, methods and libraries available to achieve one or more of these goals. In my next articles, I will elaborate more on the following topics:</p>
<ol>
<li>
<div><a href="http://www.gridshore.nl/2008/05/20/feeling-secure-with-web-services-part-1-the-usernametoken/">Username Token authentication</a>,</div>
</li>
<li>
<div><a href="http://www.gridshore.nl/2008/05/26/feeling-secure-with-web-services-part-2/">Transport Level Security and Message encryption</a>,</div>
</li>
<li>
<div><a href="http://www.gridshore.nl/2008/06/01/feeling-secure-with-web-services-part-3-digital-signature/">Digital signing</a></div>
</li>
</ol>
<hr />[1] Jip and Janneke are two very popular cartoon characters for small children. You might just recognize them: <a href="http://images.google.nl/images?q=jip+and+janneke&amp;hl=nl&amp;um=1&amp;ie=UTF-8&amp;sa=X&amp;oi=images&amp;ct=title">http://images.google.nl/images?q=jip+and+janneke&amp;hl=nl&amp;um=1&amp;ie=UTF-8&amp;sa=X&amp;oi=images&amp;ct=title</a></p>
<p>[2]http://en.wikipedia.org/wiki/Security</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F05%2F17%2Ffeeling-secure-with-web-services-introduction%2F&amp;title=Feeling%20secure%20with%20Web%20Services%20-%20Introduction&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/05/17/feeling-secure-with-web-services-introduction/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Integrating flex 3 with spring security (formerly known as Acegi)</title>
		<link>http://www.gridshore.nl/2008/05/11/integrating-flex-3-with-spring-security-formerly-known-as-acegi/</link>
		<comments>http://www.gridshore.nl/2008/05/11/integrating-flex-3-with-spring-security-formerly-known-as-acegi/#comments</comments>
		<pubDate>Sun, 11 May 2008 08:49:15 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[acegi]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[authorization]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=126</guid>
		<description><![CDATA[<p>This blog item show a way of doing security, after some additional experience I consider this method as being non optimal. The server side does not change a lot (spring security configuration), but the client does. I explain my current solution is this blog post:Integration spring security and flex 3 the sequel/ </p> <p>This [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/flexlogo1.png" alt="flexlogo.png" border="0" width="100" height="100" align="left"/>This blog item show a way of doing security, after some additional experience I consider this method as being non optimal. The server side does not change a lot (spring security configuration), but the client does. I explain my current solution is this blog post:<a href="http://www.gridshore.nl/2008/07/14/integration-spring-security-acegi-and-flex-3-the-sequel/">Integration spring security and flex 3 the sequel/</a>
</p>
<p>This article is actually about two things. It explains the basic steps to use the new spring security version 2 library in a java (web) application. I am going to show the basic configuration as well as web resource authorization and bean methods authorization. The other part is the integration of flex with spring security. I am going to show how to use authentication from within flex 3 using the spring security back end. After that I&#8217;ll show a service used from within flex through blazeds to ask for the roles a logged in user has. Using these roles I am going to hide buttons to actions non admin users must not use. Like the create new book.<img src="http://www.gridshore.nl/wp-content/uploads/springlogo.png" alt="springlogo.png" border="0" width="100" height="45" align="right" />In short this article shows the complete picture of an application using flex 3, blazeds, spring security to authenticate users and authorize actions.</p>
<p>Read on if you want to learn about the integration of these frameworks.</p>
<p><span id="more-126"></span></p>
<h2>Introduction</h2>
<p>
For a lot of my applications up till now I have used Acegi or spring security to take care of authentication and authorization. So the whole idea of securing certain url&#8217;s, presenting a login form, going to a database or ldap or whatever, checking password and obtain the roles a certain user has. This has become common through out all my jsp based web applications. Now I am moving into the flex domain. I have created an application that you can use to store all your books and browse through them. Now I want to make sure that not everybody can see the application, and only special users can insert and update books. Just because I know how to handle springframework at the server side, it seems logical to keep it that way. I have already written about the integration of flex and spring, now I want to reuse my security knowledge to secure my flex application.
</p>
<p>
One warning before you think this solutions solves all your problems. Please check the future directions, there are some differences between a normal web application and flex application in relation to session management and probably some other things as well.
</p>
<p>
So what do we need to do, let&#8217;s have a birds eye view over the complete solution:</p>
<ul>
<li>change the pom</li>
<li>add a filter to your web.xml</li>
<li>Configure the filter chain using the excellent new spring security namespace support.</li>
<li>Configure the resources to secure (at first all)</li>
<li>Fine tune the resources to secure, only *.html so everybody can download the flex swf file</li>
<li>create the login form in flex, including the remote call and the event handling of the result.</li>
<li>Implement method level security</li>
<li>Create a remote call that returns the roles for an authenticated user</li>
<li>Use the obtained roles to prevent showing the button to open the new book form.</li>
</ul>
<p>Enough has been said, let&#8217;s start configuring the basic security. If you want to have a look at the source code, go to my google code project @ http://code.google.com/p/gridshore. Check the books-overview project.
</p>
<h2>Configuring Spring security (authentication and resource authorization)</h2>
<p>First the changes in the pom file, we exclude the spring-support jar, this is important since we use spring 2.5.x and that version does not contain the spring-support module anymore. This results in some jars from spring 2.0.x due to the dependency from spring-security.
</p>
<pre>
    &lt;dependency>
        &lt;groupId>org.springframework.security&lt;/groupId>
        &lt;artifactId>spring-security-core-tiger&lt;/artifactId>
        &lt;version>2.0.0&lt;/version>
        &lt;exclusions>
            &lt;exclusion>
                &lt;groupId>org.springframework&lt;/groupId>
                &lt;artifactId>spring-support&lt;/artifactId>
            &lt;/exclusion>
        &lt;/exclusions>
    &lt;/dependency>
</pre>
<p>
That takes care of the needed jars on the classpath, now can actually start by adding a filter including mapping to the <strong>web.xml</strong>. If you look at the filter-mapping, you can see we pass everything to the spring security filter. This gives flexibility to the actually secured resources, but you can optimize it a bit.
</p>
<pre>
    &lt;filter>
        &lt;filter-name>springSecurityFilterChain&lt;/filter-name>
        &lt;filter-class>org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class>
    &lt;/filter>
    &lt;filter-mapping>
        &lt;filter-name>springSecurityFilterChain&lt;/filter-name>
        &lt;url-pattern>/*&lt;/url-pattern>
    &lt;/filter-mapping>
</pre>
<p>
Next step is to implement security, the following lines of code secures all web resources and creates an in memory user store with two users. As you can see in the code, there is almost nothing to configure. Spring security makes use of a lot of sensible defaults. You do not even have to configure your own login screen. There is even a default version for that as you can see in the image after the code.
</p>
<pre>
&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd">
    &lt;security:http auto-config="true">
        &lt;security:intercept-url pattern="*" access="ROLE_USER"/>
    &lt;/security:http>
    &lt;security:authentication-provider>
        &lt;security:user-service>
            &lt;security:user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN"/>
            &lt;security:user name="user" password="user" authorities="ROLE_USER"/>
        &lt;/security:user-service>
    &lt;/security:authentication-provider>
&lt;/beans>
</pre>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/defaultloginformspringsecurity.png" alt="defaultloginformspringsecurity.png" border="0" width="312" height="183" /></div>
<p>
Now we can prevent people from downloading he swf file, could be a nice security thing, but not really what I want. I do not really care if they can download the swf, I care more about consistent look and feel and having some good authentication. Next step is to create the login form in the flex app.
</p>
<h2>Configure flex to use spring&#8217;s authentication</h2>
<p>
First we have to change the resources that are secured.
</p>
<pre>
    &lt;security:http auto-config="true">
        &lt;security:intercept-url pattern="index.html" filters="none"/>
        &lt;security:intercept-url pattern="*.swf" filters="none"/>
        &lt;security:intercept-url pattern="*.html" access="ROLE_USER"/>
    &lt;/security:http>
</pre>
<p>
Now that we have that out of our way, let&#8217;s have a look at the flex code. The Home.mxml is the application that gets started. First a public parameter called <strong>authorization</strong>, this parameter is of our on type <strong>AuthorizationControl</strong> and contains the username as well as the granted roles. Making this parameter public enables all other flex modules to ask for the value. Another function that is public and important for the same reason is the function <strong>isAuthorized</strong>. This returns false if the current user has not been authorized yet. After the screen has been created and is ready to be displayed we create the login form using the <strong>creationComplete</strong> event. The following function is called to create the login form and add it to the page. As you can see, we remove all the children of the main content panel before we add the login form.
</p>
<pre>
    public function authenticateUser():void {
        myMainContentPanel.removeAllChildren();
        myMainContentPanel.addChild(new AuthenticationForm());
    }
</pre>
<p>Now we have a look at the implementation of the form. First the elements to present the form and the element that defines the remote http GET. In the code you&#8217;ll find the username TextInput, the password TextInput a Text element for showing a message in case of an authentication error and as said the element <strong>HttpService</strong> that defines the remote call. Take a good look at the HttpService element. We specify the special spring security url that we post the form to : <strong>j_spring_security_check</strong>. We define the method to call if everything goes well (<em>result</em>) as well as in case of an error (<em>fault</em>).
</p>
<pre>
    &lt;mx:HTTPService
            id="loginService"
            url="j_spring_security_check"
            showBusyCursor="true"
            method="POST"
            result="loginServiceResultHandler(event)"
            fault="loginServiceFaultHandler(event)">
        &lt;mx:request>
            &lt;j_username>{userName.text}&lt;/j_username>
            &lt;j_password>{password.text}&lt;/j_password>
        &lt;/mx:request>
    &lt;/mx:HTTPService>
    &lt;mx:Text id="authenticationMessage" visible="false" styleName="warning"/>
    &lt;mx:Form defaultButton="{submitButton}">
        &lt;mx:FormItem label="Username">
            &lt;mx:TextInput id="userName"/>
        &lt;/mx:FormItem>
        &lt;mx:FormItem label="Password">
            &lt;mx:TextInput id="password" displayAsPassword="true"/>
        &lt;/mx:FormItem>
        &lt;mx:FormItem>
            &lt;mx:Button id="submitButton" label="submit" click="submitBook()"/>
        &lt;/mx:FormItem>
    &lt;/mx:Form>
</pre>
<p>
In the code we saw three functions that are called when we push the login button, when a result comes back from the remote service and when an error comes back using the remote service. The function <strong>submitLogin</strong> just uses the remote service. The most interesting function is the <strong>loginServiceResultHandler</strong>. Here we call the <strong>initComponent</strong> function of the Application object. Remember we talked about this when discussing the Home.mxml. The result of this action is that we now have been authenticated on the server and we have security related information stored on the session.</p>
<pre>
        private function submitLogin():void {
            submitButton.enabled = false;
            loginService.send();
            submitButton.enabled = true;
        }
        private function loginServiceResultHandler(event:ResultEvent):void {
            Application.application.initComponent();
        }
        private function loginServiceFaultHandler(event:FaultEvent):void {
            authenticationMessage.text = "Problem while authentication ...";
            authenticationMessage.visible = true;
        }
</pre>
<p>
We go back to the <strong>Home.mxml</strong> component. We now call the remote service <em>booksSecurityServices</em> and call the method <em>obtainGrantedRoles</em> which is actually a call to the spring bean. This bean uses some specific spring security classes to obtain the current authenticated user and requests the granted roles from this user. The object that is returned <strong>AuthorizationData</strong> has the same fields as the flex object <strong>AuthorizationControl</strong>. Using BlazeDS we obtain the data we want. If you want to know more about the configuration of blazeDS than check <a href="http://www.gridshore.nl/2008/03/04/integrating-flex3-and-springframework-using-blazeds-and-intellij/">my previous post</a>. Most important file is the <em>remoting-config.xml</em>.
</p>
<pre>
public class BooksSecurityServicesImpl implements BooksSecurityServices {
    public AuthorizationData obtainGrantedRoles() {
        GrantedAuthority[] authorities =
                SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        int numAuthorities = authorities.length;
        String[] grantedRoles = new String[numAuthorities];
        for (int counter = 0; counter < numAuthorities ; counter++) {
            grantedRoles[counter] = authorities[counter].getAuthority();
        }
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return new AuthorizationData(grantedRoles,username);
    }
}
</pre>
<p>
What do we do when we have received the AuthorizationControl instance? We assign it to our globally available authorization parameter. Then if the user is authorized we initialize the navigation object and clean out the main content panel. The next block of code shows the mxml component representing the remote object as well as the function that handles a successful call. The function <strong>isAuthorized</strong> is used to check if the authorization we have is not of type <strong>anonymous</strong>. This role is assigned to any user asking a resource going through the spring security filters</p>
</pre>
<pre>
    &lt;mx:RemoteObject id="securityService" destination="booksSecurityServices"
                     fault="authorizationFaultHandler(event)">
        &lt;mx:method name="obtainGrantedRoles" result="handleReceivedGrantedRoles(event.result)"/>
    &lt;/mx:RemoteObject>

private function handleReceivedGrantedRoles(eventResult:Object):void {
    this.authorization = AuthorizationControl(eventResult);
    if (isAuthorized()) {
        var mainNavigation:MainNavigationComponent = new MainNavigationComponent();
        menuDock.addChild(mainNavigation);
        mainNavigation.visible = true;
        mainNavigation.addEventListener(components.MainNavigationEvent.SELECT_ITEM, eventAction);
        myMainContentPanel.removeAllChildren();
    }
}
public function isAuthorized():Boolean {
    return authorization != null &#038;&#038; authorization.username != 'roleAnonymous';
}
</pre>
<p>
Depending on the user that is logged on, we now have one or two buttons at the top of the screen. Users with the <em>ROLE_ADMIN</em> will see two buttons. One line of code I want to put under your attention is the one with an addEventListener. We will need this line when we start talking about he navigation menu component. Most important to know here is that we add a listener for our own event, just like we would for a click event to a button for instance. Let&#8217;s have a look at the important components.
</p>
<h2>Use user&#8217;s roles to hide some ui components</h2>
<p>
For the navigation we make use of a custom event when a button is clicked. This is used to determine the component to show in the main content panel when one of the buttons is clicked. If you look at the function <strong>initMyComponent</strong> you can see how we can determine whether we need to show the button for a new book. We make use of the globally available object Application.application which contains our object authorization. The function userIsAdmin just checks if the user has the role ADMIN. In the function clickEventHandler we create a new <strong>MainNavigationEvent</strong> which is catched by our Home.mxml component like I described.
</p>
<pre>
    public class MainNavigationComponent extends HBox {
        public function MainNavigationComponent() {
            super();
            initMyComponent();
        }
        function initMyComponent():void {
            addChild(createNewButton('allbooks', 'All Books'));
            if (Application.application.isAuthorized() &#038;&#038; Application.application.authorization.userIsAdmin()) {
                addChild(createNewButton('newbook', 'New Book'));
            }
        }
        private function clickEventHandler(event:Event):void {
            dispatchEvent(new MainNavigationEvent(MainNavigationEvent.SELECT_ITEM, event.currentTarget.id));
        }
        private function createNewButton(id:String, label:String):Button {
            var aButton:Button = new Button();
            aButton.id = id;
            aButton.label = label;
            aButton.addEventListener(MouseEvent.CLICK,clickEventHandler);
            return aButton;
        }
    }
</pre>
<p>
For completeness I&#8217;ll also show the event stuff here. The next function is from the Home.mxml. It is called when the special event is catched. The event contains a method to create a new component that is displayed in the main content panel.
</p>
<pre>
    private function eventAction(event:components.MainNavigationEvent):void {
        myMainContentPanel.removeAllChildren();
        myMainContentPanel.addChild(event.createRightUIComponent());
    }
</pre>
<p>
The next block of code show our custom flex event component. The buttons pass the item that was clicked to the event and based on this value we created the appropriate component like FilteredBooks or BookForm.
</p>
<pre>
    public class MainNavigationEvent extends Event {
        public static var SELECT_ITEM:String = 'selectitem';
        public var clickedItem:String;
        public function createRightUIComponent():UIComponent {
            var createdComponent:UIComponent;
            switch (clickedItem) {
                case 'allbooks' :
                    createdComponent = new FilteredBooks();
                    break;
                case 'newbook' :
                    createdComponent = new BookForm();
                    break;
                default:
                    var label:Label = new Label();
                    label.text = clickedItem;
                    createdComponent = label;
            }
            return createdComponent;
        }
        public function MainNavigationEvent(eventType:String,clickedItem:String) {
            super(eventType, false, false);
            this.clickedItem = clickedItem;
        }
    }
</pre>
<p>
We are almost there. Now you cannot click on the new book button anymore. But it is possible we forget to secure something on the front-end. For the example I have forgotten to secure the update book screen. Now anybody can click on a book and go to the update screen. We need more security, therefore we implement method level security on the server side.
</p>
<h2>Configure the method level authorization in spring security</h2>
<p>
Implementing method level security using spring security is very easy, especially when you have done the steps we have done so far. We use aspectJ style pointcuts to select the object and methods that need a certain security role. In our case we select all objects with a name ending with <em>Manager</em> in the specified package. The methods starting with <em>store</em> need the role <strong>ROLE_ADMIN</strong>. The methods starting with <em>obtain</em> need to role <strong>ROLE_USER</strong>. To show that it works we open the list of books with the normal user, click on a book, make a change and get the message as shown in the following image. To my opinion this message is not nice, you should prevent the user from being able to do this as all. So do not present the update form but present the data in non updatable form instead.
</p>
<pre>
    &lt;security:global-method-security>
        &lt;security:protect-pointcut
            expression="execution(* nl.gridshore.samples.books.business.*Manager.store*(..))"
            access="ROLE_ADMIN"/>
        &lt;security:protect-pointcut
            expression="execution(* nl.gridshore.samples.books.business.*Manager.obtain*(..))"
            access="ROLE_USER"/>
    &lt;/security:global-method-security>
</pre>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/authorizationerrorspringsecurity.png" alt="authorizationerrorspringsecurity.png" border="0" width="348" height="153" /></div>
<h2>Future enhancements</h2>
<p>
I am having mostly problems with the session handling. You need to think hard about what to do when the flex app outlives the server session. I also had some problems with new sessions that got started when I did not expect it. This had to do with a remote call before trying to authenticate. What I would like to do is something like a re-authentication when the sessions has died automatically. You also need to think about the length of the session. What should happen if you remove a role from a certain user.
</p>
<h2>Conclusions</h2>
<p>
It turned out to become a long article. I hope you had the patience to read it all. I do not think it is very hard to integrate spring-security with flex. All the things I have done for normal web application I could do as well for the flex application. The spring security version 2 is a good enhancement, much easier configuration, but still the possibility to make it pretty complex. Convention over configuration is well used. As for flex, just a few remote calls like in our previous posts.
</p>
<p>
I hope you like the article, drop a comment if you have questions or if you have found this useful.
</p>
<h2>References</h2>
<ul>
<li><a href="http://www.mail-archive.com/flexcoders@yahoogroups.com/msg35921.html">http://www.mail-archive.com/flexcoders@yahoogroups.com/msg35921.html</a></li>
<li><a href="http://static.springframework.org/spring-security/site/reference/html/namespace-config.html">http://static.springframework.org/spring-security/site/reference/html/namespace-config.html</a></li>
<li><a href="http://code.google.com/p/gridshore">Code sample (check the books-overview)</a></li>
</ul>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F05%2F11%2Fintegrating-flex-3-with-spring-security-formerly-known-as-acegi%2F&amp;title=Integrating%20flex%203%20with%20spring%20security%20%28formerly%20known%20as%20Acegi%29&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/05/11/integrating-flex-3-with-spring-security-formerly-known-as-acegi/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
	</channel>
</rss>

