<?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/"
	xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
xmlns:rawvoice="http://www.rawvoice.com/rawvoiceRssModule/"
>

<channel>
	<title>Solution Hacker &#187; AOP</title>
	<atom:link href="http://www.solutionhacker.com/tag/aop/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.solutionhacker.com</link>
	<description>This blog provides solutions for enterpreneurs!</description>
	<lastBuildDate>Sun, 05 Feb 2012 00:45:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=426</generator>
<!-- podcast_generator="Blubrry PowerPress/2.0.4" -->
	<itunes:summary>This blog provides solutions for enterpreneurs!</itunes:summary>
	<itunes:author>Solution Hacker</itunes:author>
	<itunes:explicit>no</itunes:explicit>
	<itunes:image href="http://www.solutionhacker.com/wp-content/plugins/powerpress/itunes_default.jpg" />
	<itunes:subtitle>This blog provides solutions for enterpreneurs!</itunes:subtitle>
	<image>
		<title>Solution Hacker &#187; AOP</title>
		<url>http://www.solutionhacker.com/wp-content/plugins/powerpress/rss_default.jpg</url>
		<link>http://www.solutionhacker.com</link>
	</image>
		<item>
		<title>Powerful combination: JMX + Annotation + AOP</title>
		<link>http://www.solutionhacker.com/implement-your-idea/scale-your-website/powerful-combination-jmx-spring-aop/</link>
		<comments>http://www.solutionhacker.com/implement-your-idea/scale-your-website/powerful-combination-jmx-spring-aop/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 06:30:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Scale]]></category>
		<category><![CDATA[annotation]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[aspectj]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[cross-cutting concern]]></category>
		<category><![CDATA[interceptor]]></category>
		<category><![CDATA[JMX]]></category>
		<category><![CDATA[management]]></category>
		<category><![CDATA[monitoring]]></category>
		<category><![CDATA[proxy-based]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.solutionhacker.com/?p=215</guid>
		<description><![CDATA[<h2>What is AOP?</h2>
<p>AOP is a way to <strong>modularize</strong> cross-cutting concerns. Ok, what does "modularize" really mean? Modularization is the encapsulation of a unit of functionality. It is exactly what "Class" is doing in OO world. How about "cross-cutting concerns"? Basically it means any functionalities that span multiple modules/ classes. They include <strong>Transaction</strong> <strong>Management</strong>, <strong>Security</strong>, <strong>Caching</strong>, <strong>Performance Monitoring </strong>and etc. To understand how AOP works, we first look at the common terms in this area:</p>
<ol>
    <li><strong>Join point</strong> - An identifiable point in the execution of a program like method invocation, exception thrown.</li>
    <li><strong>Pointcut</strong> - Program construct that selects join points and collects context at those points. AspectJ has a rich pointcut expression language!</li>
    <li><strong>Advice</strong> - Code to be executed at a join point that has been selected by a pointcut.</li>
</ol>
<p>To me, I found it easier to understand these terms if I consider<strong> join point</strong> as event generated point in code, <strong>pointcut </strong>as a way to define what events to be captured and <strong>advice </strong>as event handler.</p>
<p>AOP is indeed a powerful way to factor out system or infrasturcture-related code from the business oriented code. Typically, we use it to take care of transaction, security and profiling aspects. But it doesn't stop you putting creativity in this domain. With a bit more creativity, you can also do the following::</p>
<ol>
    <li><strong>Exception translation</strong> - checked to runtime</li>
    <li><strong>Catch ConcurrencyFailureExceptions</strong> and transparently retry if an idempotent operation fails with, for example, a deadlock loser exception.</li>
</ol>
<p><!--more--></p>
<h2>How I use Spring AOP in my project?</h2>
<p>I have been told to report the elapsed time for all calls to the database. If I don't know how to use AOP, I may end up putting code to measure time for every JDBC calls. It ends up <strong>tangling</strong> performance monitoring code with my main line business logic and the same logic will be <strong>scattered everywhere</strong> in my data access code. Bad!! That is why we need to know how to factor out the performance monitoring code into an <strong>aspect </strong>like below:</p>
<p style="text-align: center;"><img alt="" style="width: 541px; height: 163px;" src="http://www.solutionhacker.com/wp-content/uploads/image/aspectCode1.JPG" /></p>
<p>Here we use <strong>AspectJ annotation approach</strong> to implement the aspect. "Around" is to intercept start and end of any repository method. Here is what states in Spring 2.5 reference:</p>
<blockquote>
<p>Spring 2.0 introduces a simpler and more powerful way of writing       custom aspects using either a <a title="6.3.&#160;Schema-based AOP support" href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-schema">schema-based       approach</a> or the <a title="6.2.&#160;@AspectJ support" href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-ataspectj">@AspectJ annotation       style</a>. Both of these styles offer fully typed advice and use of       the AspectJ pointcut language, while still using Spring AOP for       weaving.</p>
</blockquote>
<p>If you use <strong>AspectJ annotation</strong>, you need to put <strong>&#60;aop:aspectj-autoproxy/&#62;</strong> in your application-context.xml. The limitation of Spring proxy-based AOP is that it is limited to method invocation interception. To get around that, you can use AspectJ syntax in your pointcut expression. You don't need to build the application with ajc (the AspectJ compiler) even you are using AspectJ syntax. Spring AOP can also understand @AspectJ aspects. I strong suggest you use Annotation driven AOP because it is cleaner and simplier. Working with AOP, I have faced 2 questions.</p>
<ol>
    <li>How to select the methods that I want to intercept without hardcoding the method or package name in my pointcut expression. So, my aspect or pointcut doesn't contain application specific information - Look into annotation and AOP section.</li>
    <li>How to turn on and off AOP without restarting the web application? I would use <strong>JMX</strong>. Look into "What is JMX" section.&#160;</li>
</ol>
<h2>Annotation and AOP</h2>
<p><strong>Annotation </strong>provides a better way other than code signature for selecting join point that leads to creating loosely coupled aspect. In fact, you can see annotation as another signature of a method in other dimension. And a method can have multiple annotations and each concern just bother its own annotation. It is called <strong>multidimensional signature space</strong>. For example,</p>
<blockquote>
<p>@Authentication("bankOperation")<br />
@Transactional(REQUIRED)<br />
public void credit(){...}</p>
</blockquote>
<p><strong>Pointcut </strong>uses annotation to capture join points. For example:</p>
<blockquote>
<p>execution(@Transactional * *.*(..)) Execution of a method annotated as Transactional<br />
execution((@Trasactional *) *.*(..)) Execution of a method that returns object annotated as Transactional<br />
execution(* (@Transactional *).*(..)) Execution of a method defined for type annotated as Transactional</p>
</blockquote>
<p>Selection can use <strong>Annotation types</strong> and <strong>Annotation values</strong>.&#160; What is more, annotation values can be used in Advice implementation.</p>
<p>Here is a great <a href="http://www.parleys.com/display/PARLEYS/Home#talk=2097291;slide=1;title=Leveraging%20Annotations%20with%20AOP">video</a> from Parleys that talked about "Leveraging Annotation with AOP". I have included some key points Ramnivas made here:</p>
<ul>
    <li>Write you pointcut in a smart way to avoid annotation mess. Try to use naming and package convention to help you. For example, if you want to write app log for all public facing service method, you can use "public" with package name containing "service" wildcard to help you.</li>
    <li>If you really need to use annotation like <strong>@Transaction</strong> that designer has no way to define the pointcut beforehand, use annotation to describe <strong>what the join point is</strong> but not how to handle it. So, your transaction aspect only need to worry annotation @Transaction and decouple from the application.</li>
    <li>You can piggyback annotation. For example, you can make all entities auditable via <strong><span style="color: rgb(51, 153, 102);">declare @type: @Entity *: @Auditable;&#160;</span></strong></li>
</ul>
<h2><strong>How does Spring AOP work internally?</strong></h2>
<p>The magic behind AOP is the concept of Proxy/ Decorator/ Interceptor/ Filter pattern. To me, all those patterns are conceptually the same. They all try to present itself as target object (thru implementing the same interface), intercept method call and execute injected logics. And you can have more than one interceptors invoked in series. In Spring AOP, there is one thing we need to pay attention:</p>
<p>However, once the call has finally reached the target object, ...any method calls that it may make on itself, such as 	<tt class="methodname">this.bar()</tt> or <tt class="methodname">this.foo()</tt>, are going to be 	invoked against the <span class="emphasis"><em><tt class="literal">this</tt></em></span> reference, and <span class="emphasis"><em>not</em></span> 	the proxy. This has important implications. It means that self-invocation is <span class="emphasis"><em>not</em></span> 	going to result in the advice associated with a method invocation getting a chance to execute. To handle this, either you refactor your code such that the self-invocation does not happen (best approach) or you make self invocation call thru proxy like&#160;<strong>((Pojo) AopContext.currentProxy()).bar()</strong> (invasive approach b/c it totally couples your code to Spring AOP, <span class="emphasis"><em>and</em></span> it makes the class     itself aware of the fact that it is being used in an AOP context, which flies in the face of AOP. Avoid using it).</p>
<p><em>However, it must be noted that AspectJ does not have this self-invocation issue because it is 	not a proxy-based AOP framework.</em></p>
<h2>What is JMX?</h2>
<p>In short, it is a way to enable management and monitoring of Java applications over a generic API. JMX has a simple architecture that contains <strong>instrumentation </strong>level, <strong>agent </strong>level and <strong>distribution service </strong>level. In instrumentation layer, we register MBean to the MBeanServer. In simple term, In simple term, <strong>MBean </strong>is a&#160; JavaBean with defined management interface that exposes attributes and operations to the world. <strong>MBeanServer </strong>acts as a <strong>broker </strong>to decouple communication among application MBeans and/or remote clients.</p>
<p><img alt="" style="width: 473px; height: 327px;" src="http://www.solutionhacker.com/wp-content/uploads/image/jmxaArchitecture2.JPG" /></p>
<h2>Combine AOP and JMX</h2>
<p>AOP is statically defined and intercept at the runtime. It is hard to take this out or add another aspect in after you start your machine. However, with JMX, you can enable and disable it via skipping the aspect code. <img src="../../../../../wp-includes/images/smilies/icon_cool.gif" alt=":cool:" onclick="grin(':cool:');" /> On the other hand, you can also use JMX to configure and report SLA metrics like configure thresholds and send notifications of violations. That sounds very interesting to me. There are other interesting usages mentioned in the Parley's video as well:</p>
<ol>
    <li><strong>Service blocking</strong> - throw an exception if particular service you don't want to user to use it for a period of time esp during maintenance time.</li>
    <li><strong>Caching management</strong> - I am currently using interceptor pattern and IoC to intercept dao method calls for cache lookup.&#160;</li>
</ol>
<h2>Reference</h2>
<ol>
    <li><a href="http://developers.sun.com/learning/javaoneonline/2007/pdf/TS-1106.pdf">JavaOne 07 - JMX, AOP and Spring (Nice Presentation)</a></li>
    <li><a href="http://www.parleys.com/display/PARLEYS/Home#talk=2097315;slide=3;title=Spring%20AOP%20and%20JMX">Parley's AOP and JMX (Video)</a></li>
    <li><a href="http://www.infoq.com/articles/Simplifying-Enterprise-Apps">Simplifying Enterprise Applications with Spring 2.0 and AspectJ</a></li>
    <li><a href="http://www.infoq.com/articles/Orchestration-Oleg-Zhurakousky">Workflow Orchestration Using AOP</a></li>
    <li><a href="http://www.ibm.com/developerworks/java/library/j-aopwork10/index.html">Performance Monitoring with AOP and JMX</a></li>
</ol>
<p>&#160;</p>]]></description>
			<content:encoded><![CDATA[<h2>What is AOP?</h2>
<p>AOP is a way to <strong>modularize</strong> cross-cutting concerns. Ok, what does &#8220;modularize&#8221; really mean? Modularization is the encapsulation of a unit of functionality. It is exactly what &#8220;Class&#8221; is doing in OO world. How about &#8220;cross-cutting concerns&#8221;? Basically it means any functionalities that span multiple modules/ classes. They include <strong>Transaction</strong> <strong>Management</strong>, <strong>Security</strong>, <strong>Caching</strong>, <strong>Performance Monitoring </strong>and etc. To understand how AOP works, we first look at the common terms in this area:</p>
<ol>
<li><strong>Join point</strong> &#8211; An identifiable point in the execution of a program like method invocation, exception thrown.</li>
<li><strong>Pointcut</strong> &#8211; Program construct that selects join points and collects context at those points. AspectJ has a rich pointcut expression language!</li>
<li><strong>Advice</strong> &#8211; Code to be executed at a join point that has been selected by a pointcut.</li>
</ol>
<p>To me, I found it easier to understand these terms if I consider<strong> join point</strong> as event generated point in code, <strong>pointcut </strong>as a way to define what events to be captured and <strong>advice </strong>as event handler.</p>
<p>AOP is indeed a powerful way to factor out system or infrasturcture-related code from the business oriented code. Typically, we use it to take care of transaction, security and profiling aspects. But it doesn&#8217;t stop you putting creativity in this domain. With a bit more creativity, you can also do the following::</p>
<ol>
<li><strong>Exception translation</strong> &#8211; checked to runtime</li>
<li><strong>Catch ConcurrencyFailureExceptions</strong> and transparently retry if an idempotent operation fails with, for example, a deadlock loser exception.</li>
</ol>
<p><span id="more-215"></span></p>
<h2>How I use Spring AOP in my project?</h2>
<p>I have been told to report the elapsed time for all calls to the database. If I don&#8217;t know how to use AOP, I may end up putting code to measure time for every JDBC calls. It ends up <strong>tangling</strong> performance monitoring code with my main line business logic and the same logic will be <strong>scattered everywhere</strong> in my data access code. Bad!! That is why we need to know how to factor out the performance monitoring code into an <strong>aspect </strong>like below:</p>
<p style="text-align: center;"><img alt="" style="width: 541px; height: 163px;" src="http://www.solutionhacker.com/wp-content/uploads/image/aspectCode1.JPG" /></p>
<p>Here we use <strong>AspectJ annotation approach</strong> to implement the aspect. &#8220;Around&#8221; is to intercept start and end of any repository method. Here is what states in Spring 2.5 reference:</p>
<blockquote>
<p>Spring 2.0 introduces a simpler and more powerful way of writing       custom aspects using either a <a title="6.3.&#160;Schema-based AOP support" href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-schema">schema-based       approach</a> or the <a title="6.2.&#160;@AspectJ support" href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-ataspectj">@AspectJ annotation       style</a>. Both of these styles offer fully typed advice and use of       the AspectJ pointcut language, while still using Spring AOP for       weaving.</p>
</blockquote>
<p>If you use <strong>AspectJ annotation</strong>, you need to put <strong>&lt;aop:aspectj-autoproxy/&gt;</strong> in your application-context.xml. The limitation of Spring proxy-based AOP is that it is limited to method invocation interception. To get around that, you can use AspectJ syntax in your pointcut expression. You don&#8217;t need to build the application with ajc (the AspectJ compiler) even you are using AspectJ syntax. Spring AOP can also understand @AspectJ aspects. I strong suggest you use Annotation driven AOP because it is cleaner and simplier. Working with AOP, I have faced 2 questions.</p>
<ol>
<li>How to select the methods that I want to intercept without hardcoding the method or package name in my pointcut expression. So, my aspect or pointcut doesn&#8217;t contain application specific information &#8211; Look into annotation and AOP section.</li>
<li>How to turn on and off AOP without restarting the web application? I would use <strong>JMX</strong>. Look into &#8220;What is JMX&#8221; section.&#160;</li>
</ol>
<h2>Annotation and AOP</h2>
<p><strong>Annotation </strong>provides a better way other than code signature for selecting join point that leads to creating loosely coupled aspect. In fact, you can see annotation as another signature of a method in other dimension. And a method can have multiple annotations and each concern just bother its own annotation. It is called <strong>multidimensional signature space</strong>. For example,</p>
<blockquote>
<p>@Authentication(&#8220;bankOperation&#8221;)<br />
@Transactional(REQUIRED)<br />
public void credit(){&#8230;}</p>
</blockquote>
<p><strong>Pointcut </strong>uses annotation to capture join points. For example:</p>
<blockquote>
<p>execution(@Transactional * *.*(..)) Execution of a method annotated as Transactional<br />
execution((@Trasactional *) *.*(..)) Execution of a method that returns object annotated as Transactional<br />
execution(* (@Transactional *).*(..)) Execution of a method defined for type annotated as Transactional</p>
</blockquote>
<p>Selection can use <strong>Annotation types</strong> and <strong>Annotation values</strong>.&#160; What is more, annotation values can be used in Advice implementation.</p>
<p>Here is a great <a href="http://www.parleys.com/display/PARLEYS/Home#talk=2097291;slide=1;title=Leveraging%20Annotations%20with%20AOP">video</a> from Parleys that talked about &#8220;Leveraging Annotation with AOP&#8221;. I have included some key points Ramnivas made here:</p>
<ul>
<li>Write you pointcut in a smart way to avoid annotation mess. Try to use naming and package convention to help you. For example, if you want to write app log for all public facing service method, you can use &#8220;public&#8221; with package name containing &#8220;service&#8221; wildcard to help you.</li>
<li>If you really need to use annotation like <strong>@Transaction</strong> that designer has no way to define the pointcut beforehand, use annotation to describe <strong>what the join point is</strong> but not how to handle it. So, your transaction aspect only need to worry annotation @Transaction and decouple from the application.</li>
<li>You can piggyback annotation. For example, you can make all entities auditable via <strong><span style="color: rgb(51, 153, 102);">declare @type: @Entity *: @Auditable;&#160;</span></strong></li>
</ul>
<h2><strong>How does Spring AOP work internally?</strong></h2>
<p>The magic behind AOP is the concept of Proxy/ Decorator/ Interceptor/ Filter pattern. To me, all those patterns are conceptually the same. They all try to present itself as target object (thru implementing the same interface), intercept method call and execute injected logics. And you can have more than one interceptors invoked in series. In Spring AOP, there is one thing we need to pay attention:</p>
<p>However, once the call has finally reached the target object, &#8230;any method calls that it may make on itself, such as 	<tt class="methodname">this.bar()</tt> or <tt class="methodname">this.foo()</tt>, are going to be 	invoked against the <span class="emphasis"><em><tt class="literal">this</tt></em></span> reference, and <span class="emphasis"><em>not</em></span> 	the proxy. This has important implications. It means that self-invocation is <span class="emphasis"><em>not</em></span> 	going to result in the advice associated with a method invocation getting a chance to execute. To handle this, either you refactor your code such that the self-invocation does not happen (best approach) or you make self invocation call thru proxy like&#160;<strong>((Pojo) AopContext.currentProxy()).bar()</strong> (invasive approach b/c it totally couples your code to Spring AOP, <span class="emphasis"><em>and</em></span> it makes the class     itself aware of the fact that it is being used in an AOP context, which flies in the face of AOP. Avoid using it).</p>
<p><em>However, it must be noted that AspectJ does not have this self-invocation issue because it is 	not a proxy-based AOP framework.</em></p>
<h2>What is JMX?</h2>
<p>In short, it is a way to enable management and monitoring of Java applications over a generic API. JMX has a simple architecture that contains <strong>instrumentation </strong>level, <strong>agent </strong>level and <strong>distribution service </strong>level. In instrumentation layer, we register MBean to the MBeanServer. In simple term, In simple term, <strong>MBean </strong>is a&#160; JavaBean with defined management interface that exposes attributes and operations to the world. <strong>MBeanServer </strong>acts as a <strong>broker </strong>to decouple communication among application MBeans and/or remote clients.</p>
<p><img alt="" style="width: 473px; height: 327px;" src="http://www.solutionhacker.com/wp-content/uploads/image/jmxaArchitecture2.JPG" /></p>
<h2>Combine AOP and JMX</h2>
<p>AOP is statically defined and intercept at the runtime. It is hard to take this out or add another aspect in after you start your machine. However, with JMX, you can enable and disable it via skipping the aspect code. <img src="../../../../../wp-includes/images/smilies/icon_cool.gif" alt=":cool:" onclick="grin(':cool:');" /> On the other hand, you can also use JMX to configure and report SLA metrics like configure thresholds and send notifications of violations. That sounds very interesting to me. There are other interesting usages mentioned in the Parley&#8217;s video as well:</p>
<ol>
<li><strong>Service blocking</strong> &#8211; throw an exception if particular service you don&#8217;t want to user to use it for a period of time esp during maintenance time.</li>
<li><strong>Caching management</strong> &#8211; I am currently using interceptor pattern and IoC to intercept dao method calls for cache lookup.&#160;</li>
</ol>
<h2>Reference</h2>
<ol>
<li><a href="http://developers.sun.com/learning/javaoneonline/2007/pdf/TS-1106.pdf">JavaOne 07 &#8211; JMX, AOP and Spring (Nice Presentation)</a></li>
<li><a href="http://www.parleys.com/display/PARLEYS/Home#talk=2097315;slide=3;title=Spring%20AOP%20and%20JMX">Parley&#8217;s AOP and JMX (Video)</a></li>
<li><a href="http://www.infoq.com/articles/Simplifying-Enterprise-Apps">Simplifying Enterprise Applications with Spring 2.0 and AspectJ</a></li>
<li><a href="http://www.infoq.com/articles/Orchestration-Oleg-Zhurakousky">Workflow Orchestration Using AOP</a></li>
<li><a href="http://www.ibm.com/developerworks/java/library/j-aopwork10/index.html">Performance Monitoring with AOP and JMX</a></li>
</ol>
<p>&#160;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.solutionhacker.com/implement-your-idea/scale-your-website/powerful-combination-jmx-spring-aop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Part 1 &#8211; Spring Security Architectural Review</title>
		<link>http://www.solutionhacker.com/uncategorized/part-1-spring-security-architectural-review/</link>
		<comments>http://www.solutionhacker.com/uncategorized/part-1-spring-security-architectural-review/#comments</comments>
		<pubDate>Tue, 27 May 2008 21:15:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[6. Uncategorized]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Site Building]]></category>
		<category><![CDATA[acegi]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[aspect]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[authorization]]></category>
		<category><![CDATA[JXplorer]]></category>
		<category><![CDATA[LDAP]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.solutionhacker.com/?p=146</guid>
		<description><![CDATA[<p><img width="216" height="120" align="left" alt="" src="http://www.solutionhacker.com/wp-content/uploads/securityLogo.gif" style="margin-right: 10px;" /></p>
<p>My Web application needs both authentication and role-based authorization features. And our user profile is currently stored in an OpenLDAP server. I am looking for a security framework that can help me to integrate LDAP and provide these security features with the least amount of effort. On top of that, I want to achieve this without polluting my business logic with security code (ie. via AOP). At my first glance, Spring security (aka. acegi security) looks promising to me. After evaluating it a bit more, I believe it does provide what I need for my project. So, I started creating a prototype and gave it a trial. In this article, I will go over the steps I took to build my prototype and I will provide you the necessary explanation to move forward alongside. Hopefully, you will get over the initial learning curve as quick as possible with this guide. <!--more--></p>
<p><!--more--></p>
<h2>Spring Security Overview</h2>
<p><strong><u>Step 1. Specify the location of the configuration files for Spring and Log4J in web.xml<br />
</u></strong></p>
<p>The configuration below tells Spring and Log4J the location of the configuration files. These files will be parsed by the <strong>ContextLoaderListener </strong>(for Spring) and <strong>Log4JConfigListener </strong>(for log4j) during the initial loading process.</p>
<pre class="xml" name="code">
&#60;context-param&#62;
	&#60;param-name&#62;contextConfigLocation&#60;/param-name&#62;
	&#60;param-value&#62;/WEB-INF/applicationContext.xml&#60;/param-value&#62;
&#60;/context-param&#62;

&#60;context-param&#62;
	&#60;param-name&#62;log4jConfigLocation&#60;/param-name&#62;
	&#60;param-value&#62;/WEB-INF/classes/log4j.properties&#60;/param-value&#62;
&#60;/context-param&#62;
</pre>
<p><strong><u>Step 2. Define the Acegi Filter Chain Proxy Filter in web.xml<br />
</u></strong></p>
<p>Spring Security's support for web security is heavily based on <strong>servlet filters</strong>. These filters intercept an incoming request and apply some security processing before the request is handled by your application. Spring security comes with a handful of filters that intercept servlet requests and pass them on to the authentication and access decision manager to enforce security. However if you ever used servlet filters, you know that for them to take effect, you must configure them in the web application's web.xml file, using the &#60;filter&#62; and &#60;filter-mapping&#62; elements. While this works, it doesn't lend itself to configuration using dependency injection. You have no control of the life-cycle of the filter (like instantiation), but you may be able to override the constructor and use <strong>WebApplicationContextUtil </strong>to load the bean your filter needs to act on. This is not ideal as you need to hardcode a reference to the name of the bean. That is why Filter Chain Proxy is created. The <strong>FilterToBeanProxy</strong> is a special servlet filter that, by itself, doesn't do much. Instead, it delegate its work to a bean implements the Filter interface just like other servlet filter. In the configuration below, the target class is the filter class that I talk about. Using this approach, Spring security is able to <strong>plug in</strong> its security functionality in a modular way. NOTE: The mechanism is <strong>not </strong>Spring Security specific. You can use this approach if you have no control of the life-cycle of the class you are interested in.</p>
<pre class="xml" name="code">
   &#60;filter&#62;
        &#60;filter-name&#62;Acegi Filter Chain Proxy&#60;/filter-name&#62;
        &#60;filter-class&#62;net.sf.acegisecurity.util.FilterToBeanProxy&#60;/filter-class&#62;
        &#60;init-param&#62;
            &#60;param-name&#62;targetClass&#60;/param-name&#62;
            &#60;param-value&#62;net.sf.acegisecurity.util.FilterChainProxy&#60;/param-value&#62;
        &#60;/init-param&#62;
   &#60;/filter&#62;</pre>
<p><strong><u>Step 3. Define the Filter chain in ApplicationContext.xml<br />
</u></strong></p>
<p>Now you have the proxy to redirect the request to your Spring bean. What is next? Spring Security requires at least 4 filters to be functioned. Does this mean that you have to configure a FilterToBeanProxy for each of the filters. No! To make life easier, Spring Security offers &#34;FilterChainProxy&#34; that can be configured to chain together several filters at once. The filters we need as part of the request processing are:</p>
<ol>
    <li><u>HttpSessionContextIntegrationFilter</u>
    <ul>
        <li>Check to see if the user's Authentication information is in <strong>Session</strong>. If so, it makes the authentication info available to the current request. At the end of the request, it will deposit the authentication info back into the session so that it will be available for the next request.</li>
        <li>It prevents user from logging in again.</li>
    </ul>
    </li>
    <li><u>AuthenticationProcessingFilter          </u>
    <ul>
        <li>Delegate to <strong>AuthenticationManager </strong>to do the actual authentication. <strong>AuthenticationManager</strong> determines who you are. Once you are identified, a list of <strong>roles </strong>that belongs to you will be populated. As with the rest of Spring Security, the authentication manager is a <strong>pluggable interface-based</strong> component. This makes it possible to use Spring Security with virtually any authentication mechanism.</li>
        <li>Process authentication based on username and password given to it in <strong>j_username</strong> and <strong>j_password.</strong></li>
        <li>&#34;<strong>filterProcessesUrl</strong>&#34; property tells which URL it should intercept. Default to<strong> /j_acegi_security_check.</strong></li>
        <li>&#34;<strong>authenticationFailureUrl</strong>&#34; property indicates where the user will be sent should authentication fail.</li>
        <li>When authentication is successful, <strong>Authentication </strong>object will be placed to the Session.</li>
    </ul>
    </li>
    <li><u>ExceptionTranslationFilter</u>
    <ul>
        <li>Handle <strong>AuthenticationException </strong>via sending the user to the authentication entry point. It is configured in the &#34;authenticationEntryPoint&#34; property. There are different type of entry points: Basic, Form, Digest and X.509 cert.</li>
        <li>Handle <strong>AccessDeniedException </strong>- Default to HTTP 403 error to the browser. You can configure AccessDeniedHandlerImpl to forward the user to nice-looking error page.</li>
        <li>Without anything to handle Spring Security exceptions above, they would flow up to the servlet container and be displayed in the browser as stack trace.</li>
    </ul>
    </li>
    <li><u>FilterSecurityInterceptor</u>
    <ul>
        <li>Enforce web security. If user has not been authenticated, throw an <strong>AuthenticationException </strong>which will be handled by exception translation filter. If user has no right to access the resource, it will throw an <strong>AccessDeniedException </strong>that will be handled by exception translation filter as well.</li>
        <li>It is wired with authenticationManager and accessDecisionManager</li>
        <li><strong>Access Decision Manager</strong> determines whether you are <strong>authorized</strong> to access the secured resource. It performs authorization, deciding whether to let you in by considering your authentication information and the security attributes that have been associated with the secured resource. Access Decision Manager is also pluggable.</li>
        <li>&#34;<strong>objectDefinitionSource</strong>&#34; property specifies which resources (ie. urls) are secured and what privileges are required to access them via url pattern with roles.</li>
    </ul>
    </li>
    <li><u>ChannelProcessingFilter</u> (optional)
    <ul>
        <li>Even you have done all the secure protection as stated above, the information you are authorized to obtain still needs to transfer to you via the Internet unprotected. You may want to encrypt it to prevent people from stealing it. Use <strong>HTTPS</strong>!</li>
        <li>ChannelProcessingFilter offers a foolproof way to ensure that certain pages be transferred using HTTPS via intercept the request, check to see if it needs to be secure and, if so, call https by <strong>redirecting the request </strong>to an HTTPS form of the original request URL.</li>
    </ul>
    </li>
</ol>
<p><strong>NOTE</strong>: &#34;securityEnforcementFilter&#34; can combine ExceptionTranslationFilter and FilterSecurityInterceptor together.</p>
<p>To chain them up, here is the xml piece for FilterChainProxy.</p>
<pre name="code" class="xml">
&#60;bean id=&#34;filterChainProxy&#34; class=&#34;net.sf.acegisecurity.util.FilterChainProxy&#34;&#62;
      &#60;property name=&#34;filterInvocationDefinitionSource&#34;&#62;
         &#60;value&#62;
	    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
	    PATTERN_TYPE_APACHE_ANT
	    /**=httpSessionContextIntegrationFilter, authenticationProcessingFilter, exceptionTranslationFilter, filterSecurityInterceptor
         &#60;/value&#62;
      &#60;/property&#62;
    &#60;/bean&#62;</pre>
<p>You can put more than 1 pattern if you want. The order of the filters are important because it governs the order of the filters in the chain.</p>
<p><strong><u>Step 4. Customize the authentication mechanism<br />
</u></strong></p>
<p>Now you have all the filters wired. You may want to provide a custom authentication against your own database or ldap server. To do that, you need to implement UserDetail class and wire it up with authentication manager. Below is the method you need to override.</p>
<pre class="java" name="code">
public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException, DataAccessException {
        User user = null;
        GrantedAuthority[] grantedAuthorities = null;
        try {
            user = getUserDAO().lookupUser(userId);
            
            if(user==null) {
                throw new UsernameNotFoundException(&#34;Invalid User&#34;);            
            }
            
            Set roles = user.getRoles();
            int i = 0;
            grantedAuthorities = new GrantedAuthority[roles.size()];
            for (Iterator iter = roles.iterator(); iter.hasNext(); i++) {
                Role role = (Role) iter.next();
                
                GrantedAuthority authority = new GrantedAuthorityImpl(role.getRole());
                grantedAuthorities[i] = authority;
            }
        } catch (DataStoreException e) {
            throw new DataRetrievalFailureException(&#34;Cannot loadUserByUsername userId:&#34;+userId+ &#34; Exception:&#34; + e.getMessage(), e);
        }

        UserDetails userDetails = new org.acegisecurity.userdetails.User(
                user.getUserId(), 
                user.getPassword(),
                user.isEnabled(), //enabled
                user.isEnabled(), //accountNonExpired
                user.isEnabled(), //credentialsNonExpired
                user.isEnabled(), //accountNonLocked
                grantedAuthorities
                );
        return userDetails;
    }

</pre>
<p>Now you need to wire it up to your Authentication Manager</p>
<pre name="code" class="xml">
&#60;bean id=&#34;authenticationManager&#34; class=&#34;org.acegisecurity.providers.ProviderManager&#34;&#62;
  &#60;property name=&#34;providers&#34;&#62;
	 &#60;list&#62;
		&#60;ref local=&#34;daoAuthenticationProvider&#34;/&#62;
	 &#60;/list&#62;
  &#60;/property&#62;
&#60;/bean&#62;

&#60;!-- Acegi will use our UserService bean to do authentication --&#62;
&#60;bean id=&#34;daoAuthenticationProvider&#34; class=&#34;org.acegisecurity.providers.dao.DaoAuthenticationProvider&#34;&#62;
  &#60;property name=&#34;userDetailsService&#34;&#62;&#60;ref bean=&#34;UserService&#34;/&#62;&#60;/property&#62;
  &#60;property name=&#34;passwordEncoder&#34;&#62;&#60;ref local=&#34;passwordEncoder&#34;/&#62;&#60;/property&#62;
&#60;/bean&#62;

&#60;bean id=&#34;UserService&#34; 
      class=&#34;org.springframework.transaction.interceptor.TransactionProxyFactoryBean&#34;&#62;
  &#60;property name=&#34;transactionManager&#34;&#62;
    &#60;ref bean=&#34;myTransactionManager&#34;/&#62;
  &#60;/property&#62;
  &#60;property name=&#34;target&#34;&#62;
    &#60;bean class=&#34;com.solutionhacker.user.UserServiceImpl&#34; &#62;
      &#60;property name=&#34;userDAO&#34;&#62;
        &#60;ref local=&#34;UserDAO&#34; /&#62;
      &#60;/property&#62;
    &#60;/bean&#62;
  &#60;/property&#62;
  &#60;property name=&#34;transactionAttributes&#34;&#62;
    &#60;props&#62;
      &#60;prop key=&#34;*&#34;&#62;PROPAGATION_REQUIRED,-Exception&#60;/prop&#62;
    &#60;/props&#62;
  &#60;/property&#62;
&#60;/bean&#62;</pre>
<h2>View-layer security</h2>
<p>&#160;As you may notice, filters only provide a coarse-grained security, limiting access at the request level like either you can access the resource or not. In some cases, you may want more fine-grained control over what the user is allowed to see. Maybe all users of an application will be allowed to see a certain page, but only users who are granted special authority may see certain elements on that page. To handle this, Spring Security uses JSP tag library. This tag library provides only 3 tags: <strong>&#60;authz:acl&#62;, &#60;authz:authentication&#62; </strong>and <strong>&#60;authz:authorize&#62;</strong>. You can use this tag to wrap around the UI element and conditionally allows it to display or not based on the role. I will not go through the detail of this here. Since I advocate to use Flex as View, so I will write another article to talk about how we can achieve it in Flex.</p>
<h2>Secure method invocation</h2>
<p>&#160;Similar</p>
<h2>Conclusion</h2>
<p>As you can tell, you don't write much java code to protect your resource. Everything is almost driven by configuration there. It is nice. However, on the other hand, the tedious work is shifted to configuration. To me, reading the configuration is harder than reading code. You can tell most of the configuration there are not coupled with application. Only the section that is application specific is the security policies you put in under &#34;<strong>objectDefinitionSource</strong>&#34;.&#160; Again, to associate all the stuff I want to protect with the role names are tedious and hardcoded.</p>
<p><em><strong>UPDATE</strong>: Acegi is moved to Spring Security 2.0 that has new namespace for security. The main thing they fix is to make the configuration much cleaner. I will talk about that in my next article. </em></p>
<p><strong><em>UPDATE</em></strong><em>: Riable has walked us through how to upgrade from Acegi to Spring Security <a href="http://raibledesigns.com/rd/entry/upgrading_to_spring_security_2" target="_blank">here</a>. So, I don't need to write one!</em></p>
<h2>Reference</h2>
<p><a target="_blank" href="http://springtips.blogspot.com/search/label/security">http://springtips.blogspot.com/search/label/security</a></p>
<p><a target="_blank" href="http://i-proving.ca/space/Technologies/Acegi+Security+System+for+Spring">http://i-proving.ca/space/Technologies/Acegi+Security+System+for+Spring</a></p>
<p><a target="_blank" href="http://static.springframework.org/spring-security/site/reference/pdf/springsecurity.pdf">http://static.springframework.org/spring-security/site/reference/pdf/springsecurity.pdf</a></p>
<p>&#160;</p>]]></description>
			<content:encoded><![CDATA[<p><img width="216" height="120" align="left" alt="" src="http://www.solutionhacker.com/wp-content/uploads/securityLogo.gif" style="margin-right: 10px;" /></p>
<p>My Web application needs both authentication and role-based authorization features. And our user profile is currently stored in an OpenLDAP server. I am looking for a security framework that can help me to integrate LDAP and provide these security features with the least amount of effort. On top of that, I want to achieve this without polluting my business logic with security code (ie. via AOP). At my first glance, Spring security (aka. acegi security) looks promising to me. After evaluating it a bit more, I believe it does provide what I need for my project. So, I started creating a prototype and gave it a trial. In this article, I will go over the steps I took to build my prototype and I will provide you the necessary explanation to move forward alongside. Hopefully, you will get over the initial learning curve as quick as possible with this guide. <span id="more-146"></span></p>
<p><!--more--></p>
<h2>Spring Security Overview</h2>
<p><strong><u>Step 1. Specify the location of the configuration files for Spring and Log4J in web.xml<br />
</u></strong></p>
<p>The configuration below tells Spring and Log4J the location of the configuration files. These files will be parsed by the <strong>ContextLoaderListener </strong>(for Spring) and <strong>Log4JConfigListener </strong>(for log4j) during the initial loading process.</p>
<p><pre><pre class="xml" name="code">
&amp;lt;context-param&amp;gt;
&nbsp;&nbsp;&amp;lt;param-name&amp;gt;contextConfigLocation&amp;lt;/param-name&amp;gt;
&nbsp;&nbsp;&amp;lt;param-value&amp;gt;/WEB-INF/applicationContext.xml&amp;lt;/param-value&amp;gt;
&amp;lt;/context-param&amp;gt;

&amp;lt;context-param&amp;gt;
&nbsp;&nbsp;&amp;lt;param-name&amp;gt;log4jConfigLocation&amp;lt;/param-name&amp;gt;
&nbsp;&nbsp;&amp;lt;param-value&amp;gt;/WEB-INF/classes/log4j.properties&amp;lt;/param-value&amp;gt;
&amp;lt;/context-param&amp;gt;
</pre></pre></p>
<p><strong><u>Step 2. Define the Acegi Filter Chain Proxy Filter in web.xml<br />
</u></strong></p>
<p>Spring Security&#8217;s support for web security is heavily based on <strong>servlet filters</strong>. These filters intercept an incoming request and apply some security processing before the request is handled by your application. Spring security comes with a handful of filters that intercept servlet requests and pass them on to the authentication and access decision manager to enforce security. However if you ever used servlet filters, you know that for them to take effect, you must configure them in the web application&#8217;s web.xml file, using the &lt;filter&gt; and &lt;filter-mapping&gt; elements. While this works, it doesn&#8217;t lend itself to configuration using dependency injection. You have no control of the life-cycle of the filter (like instantiation), but you may be able to override the constructor and use <strong>WebApplicationContextUtil </strong>to load the bean your filter needs to act on. This is not ideal as you need to hardcode a reference to the name of the bean. That is why Filter Chain Proxy is created. The <strong>FilterToBeanProxy</strong> is a special servlet filter that, by itself, doesn&#8217;t do much. Instead, it delegate its work to a bean implements the Filter interface just like other servlet filter. In the configuration below, the target class is the filter class that I talk about. Using this approach, Spring security is able to <strong>plug in</strong> its security functionality in a modular way. NOTE: The mechanism is <strong>not </strong>Spring Security specific. You can use this approach if you have no control of the life-cycle of the class you are interested in.</p>
<p><pre><pre class="xml" name="code">
&nbsp;&nbsp; &amp;lt;filter&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;filter-name&amp;gt;Acegi Filter Chain Proxy&amp;lt;/filter-name&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;filter-class&amp;gt;net.sf.acegisecurity.util.FilterToBeanProxy&amp;lt;/filter-class&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;init-param&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;param-name&amp;gt;targetClass&amp;lt;/param-name&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;param-value&amp;gt;net.sf.acegisecurity.util.FilterChainProxy&amp;lt;/param-value&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;/init-param&amp;gt;
&nbsp;&nbsp; &amp;lt;/filter&amp;gt;</pre></pre></p>
<p><strong><u>Step 3. Define the Filter chain in ApplicationContext.xml<br />
</u></strong></p>
<p>Now you have the proxy to redirect the request to your Spring bean. What is next? Spring Security requires at least 4 filters to be functioned. Does this mean that you have to configure a FilterToBeanProxy for each of the filters. No! To make life easier, Spring Security offers &quot;FilterChainProxy&quot; that can be configured to chain together several filters at once. The filters we need as part of the request processing are:</p>
<ol>
<li><u>HttpSessionContextIntegrationFilter</u>
<ul>
<li>Check to see if the user&#8217;s Authentication information is in <strong>Session</strong>. If so, it makes the authentication info available to the current request. At the end of the request, it will deposit the authentication info back into the session so that it will be available for the next request.</li>
<li>It prevents user from logging in again.</li>
</ul>
</li>
<li><u>AuthenticationProcessingFilter          </u>
<ul>
<li>Delegate to <strong>AuthenticationManager </strong>to do the actual authentication. <strong>AuthenticationManager</strong> determines who you are. Once you are identified, a list of <strong>roles </strong>that belongs to you will be populated. As with the rest of Spring Security, the authentication manager is a <strong>pluggable interface-based</strong> component. This makes it possible to use Spring Security with virtually any authentication mechanism.</li>
<li>Process authentication based on username and password given to it in <strong>j_username</strong> and <strong>j_password.</strong></li>
<li>&quot;<strong>filterProcessesUrl</strong>&quot; property tells which URL it should intercept. Default to<strong> /j_acegi_security_check.</strong></li>
<li>&quot;<strong>authenticationFailureUrl</strong>&quot; property indicates where the user will be sent should authentication fail.</li>
<li>When authentication is successful, <strong>Authentication </strong>object will be placed to the Session.</li>
</ul>
</li>
<li><u>ExceptionTranslationFilter</u>
<ul>
<li>Handle <strong>AuthenticationException </strong>via sending the user to the authentication entry point. It is configured in the &quot;authenticationEntryPoint&quot; property. There are different type of entry points: Basic, Form, Digest and X.509 cert.</li>
<li>Handle <strong>AccessDeniedException </strong>- Default to HTTP 403 error to the browser. You can configure AccessDeniedHandlerImpl to forward the user to nice-looking error page.</li>
<li>Without anything to handle Spring Security exceptions above, they would flow up to the servlet container and be displayed in the browser as stack trace.</li>
</ul>
</li>
<li><u>FilterSecurityInterceptor</u>
<ul>
<li>Enforce web security. If user has not been authenticated, throw an <strong>AuthenticationException </strong>which will be handled by exception translation filter. If user has no right to access the resource, it will throw an <strong>AccessDeniedException </strong>that will be handled by exception translation filter as well.</li>
<li>It is wired with authenticationManager and accessDecisionManager</li>
<li><strong>Access Decision Manager</strong> determines whether you are <strong>authorized</strong> to access the secured resource. It performs authorization, deciding whether to let you in by considering your authentication information and the security attributes that have been associated with the secured resource. Access Decision Manager is also pluggable.</li>
<li>&quot;<strong>objectDefinitionSource</strong>&quot; property specifies which resources (ie. urls) are secured and what privileges are required to access them via url pattern with roles.</li>
</ul>
</li>
<li><u>ChannelProcessingFilter</u> (optional)
<ul>
<li>Even you have done all the secure protection as stated above, the information you are authorized to obtain still needs to transfer to you via the Internet unprotected. You may want to encrypt it to prevent people from stealing it. Use <strong>HTTPS</strong>!</li>
<li>ChannelProcessingFilter offers a foolproof way to ensure that certain pages be transferred using HTTPS via intercept the request, check to see if it needs to be secure and, if so, call https by <strong>redirecting the request </strong>to an HTTPS form of the original request URL.</li>
</ul>
</li>
</ol>
<p><strong>NOTE</strong>: &quot;securityEnforcementFilter&quot; can combine ExceptionTranslationFilter and FilterSecurityInterceptor together.</p>
<p>To chain them up, here is the xml piece for FilterChainProxy.</p>
<p><pre><pre name="code" class="xml">
&amp;lt;bean id=&amp;quot;filterChainProxy&amp;quot; class=&amp;quot;net.sf.acegisecurity.util.FilterChainProxy&amp;quot;&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;property name=&amp;quot;filterInvocationDefinitionSource&amp;quot;&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &amp;lt;value&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PATTERN_TYPE_APACHE_ANT
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/**=httpSessionContextIntegrationFilter, authenticationProcessingFilter, exceptionTranslationFilter, filterSecurityInterceptor
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &amp;lt;/value&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;/property&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;/bean&amp;gt;</pre></pre></p>
<p>You can put more than 1 pattern if you want. The order of the filters are important because it governs the order of the filters in the chain.</p>
<p><strong><u>Step 4. Customize the authentication mechanism<br />
</u></strong></p>
<p>Now you have all the filters wired. You may want to provide a custom authentication against your own database or ldap server. To do that, you need to implement UserDetail class and wire it up with authentication manager. Below is the method you need to override.</p>
<p><pre><pre class="java" name="code">
public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException, DataAccessException {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;User user = null;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;GrantedAuthority[] grantedAuthorities = null;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user = getUserDAO().lookupUser(userId);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(user==null) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw new UsernameNotFoundException(&amp;quot;Invalid User&amp;quot;);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Set roles = user.getRoles();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int i = 0;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;grantedAuthorities = new GrantedAuthority[roles.size()];
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for (Iterator iter = roles.iterator(); iter.hasNext(); i++) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Role role = (Role) iter.next();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;GrantedAuthority authority = new GrantedAuthorityImpl(role.getRole());
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;grantedAuthorities[i] = authority;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (DataStoreException e) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw new DataRetrievalFailureException(&amp;quot;Cannot loadUserByUsername userId:&amp;quot;+userId+ &amp;quot; Exception:&amp;quot; + e.getMessage(), e);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UserDetails userDetails = new org.acegisecurity.userdetails.User(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.getUserId(), 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.getPassword(),
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.isEnabled(), //enabled
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.isEnabled(), //accountNonExpired
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.isEnabled(), //credentialsNonExpired
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.isEnabled(), //accountNonLocked
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;grantedAuthorities
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return userDetails;
&nbsp;&nbsp;&nbsp;&nbsp;}

</pre></pre></p>
<p>Now you need to wire it up to your Authentication Manager</p>
<p><pre><pre name="code" class="xml">
&amp;lt;bean id=&amp;quot;authenticationManager&amp;quot; class=&amp;quot;org.acegisecurity.providers.ProviderManager&amp;quot;&amp;gt;
&nbsp;&nbsp;&amp;lt;property name=&amp;quot;providers&amp;quot;&amp;gt;
&nbsp;&nbsp; &amp;lt;list&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;ref local=&amp;quot;daoAuthenticationProvider&amp;quot;/&amp;gt;
&nbsp;&nbsp; &amp;lt;/list&amp;gt;
&nbsp;&nbsp;&amp;lt;/property&amp;gt;
&amp;lt;/bean&amp;gt;

&amp;lt;!-- Acegi will use our UserService bean to do authentication --&amp;gt;
&amp;lt;bean id=&amp;quot;daoAuthenticationProvider&amp;quot; class=&amp;quot;org.acegisecurity.providers.dao.DaoAuthenticationProvider&amp;quot;&amp;gt;
&nbsp;&nbsp;&amp;lt;property name=&amp;quot;userDetailsService&amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot;UserService&amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;
&nbsp;&nbsp;&amp;lt;property name=&amp;quot;passwordEncoder&amp;quot;&amp;gt;&amp;lt;ref local=&amp;quot;passwordEncoder&amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;
&amp;lt;/bean&amp;gt;

&amp;lt;bean id=&amp;quot;UserService&amp;quot; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;class=&amp;quot;org.springframework.transaction.interceptor.TransactionProxyFactoryBean&amp;quot;&amp;gt;
&nbsp;&nbsp;&amp;lt;property name=&amp;quot;transactionManager&amp;quot;&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;ref bean=&amp;quot;myTransactionManager&amp;quot;/&amp;gt;
&nbsp;&nbsp;&amp;lt;/property&amp;gt;
&nbsp;&nbsp;&amp;lt;property name=&amp;quot;target&amp;quot;&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;bean class=&amp;quot;com.solutionhacker.user.UserServiceImpl&amp;quot; &amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;property name=&amp;quot;userDAO&amp;quot;&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;ref local=&amp;quot;UserDAO&amp;quot; /&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;/property&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;/bean&amp;gt;
&nbsp;&nbsp;&amp;lt;/property&amp;gt;
&nbsp;&nbsp;&amp;lt;property name=&amp;quot;transactionAttributes&amp;quot;&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;props&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;prop key=&amp;quot;*&amp;quot;&amp;gt;PROPAGATION_REQUIRED,-Exception&amp;lt;/prop&amp;gt;
&nbsp;&nbsp;&nbsp;&nbsp;&amp;lt;/props&amp;gt;
&nbsp;&nbsp;&amp;lt;/property&amp;gt;
&amp;lt;/bean&amp;gt;</pre></pre></p>
<h2>View-layer security</h2>
<p>&nbsp;As you may notice, filters only provide a coarse-grained security, limiting access at the request level like either you can access the resource or not. In some cases, you may want more fine-grained control over what the user is allowed to see. Maybe all users of an application will be allowed to see a certain page, but only users who are granted special authority may see certain elements on that page. To handle this, Spring Security uses JSP tag library. This tag library provides only 3 tags: <strong>&lt;authz:acl&gt;, &lt;authz:authentication&gt; </strong>and <strong>&lt;authz:authorize&gt;</strong>. You can use this tag to wrap around the UI element and conditionally allows it to display or not based on the role. I will not go through the detail of this here. Since I advocate to use Flex as View, so I will write another article to talk about how we can achieve it in Flex.</p>
<h2>Secure method invocation</h2>
<p>&nbsp;Similar</p>
<h2>Conclusion</h2>
<p>As you can tell, you don&#8217;t write much java code to protect your resource. Everything is almost driven by configuration there. It is nice. However, on the other hand, the tedious work is shifted to configuration. To me, reading the configuration is harder than reading code. You can tell most of the configuration there are not coupled with application. Only the section that is application specific is the security policies you put in under &quot;<strong>objectDefinitionSource</strong>&quot;.&nbsp; Again, to associate all the stuff I want to protect with the role names are tedious and hardcoded.</p>
<p><em><strong>UPDATE</strong>: Acegi is moved to Spring Security 2.0 that has new namespace for security. The main thing they fix is to make the configuration much cleaner. I will talk about that in my next article. </em></p>
<p><strong><em>UPDATE</em></strong><em>: Riable has walked us through how to upgrade from Acegi to Spring Security <a href="http://raibledesigns.com/rd/entry/upgrading_to_spring_security_2" target="_blank">here</a>. So, I don&#8217;t need to write one!</em></p>
<h2>Reference</h2>
<p><a target="_blank" href="http://springtips.blogspot.com/search/label/security">http://springtips.blogspot.com/search/label/security</a></p>
<p><a target="_blank" href="http://i-proving.ca/space/Technologies/Acegi+Security+System+for+Spring">http://i-proving.ca/space/Technologies/Acegi+Security+System+for+Spring</a></p>
<p><a target="_blank" href="http://static.springframework.org/spring-security/site/reference/pdf/springsecurity.pdf">http://static.springframework.org/spring-security/site/reference/pdf/springsecurity.pdf</a></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.solutionhacker.com/uncategorized/part-1-spring-security-architectural-review/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

