Skip to content
accelerando

Tag Archives: Spring

Vaadin & Spring: Integrating Vaadin with Spring Security

30-Mar-13

Note: You’ll find the complete working sources here: Vaadin-SpringSecurityViewProvider.

Finally, the 2nd post in my Vaadin & Spring series. This time about describing, instantiating and managing views with
and through Spring Security.

I’m a big fan of Spring Security as it is – at least for my purposes – incredible easy to add some long standing authorization mechanism we have in our databases. Apart from that, it most of the times just works.

I’ve read a lot about Shiro as well, but instead of learning another framework, i wanted to focus on something i already knew quite well to keep things secure. Regarding security i like to be conservative.

For the basic integration i’m using SpringVaadinIntegration by Alexander Fedorov and i’m very content with it, the ru.xpoft.vaadin.SpringVaadinServlet works very well.

My goals with adding custom stuff to it where the following:

  • I want to use Spring Security
  • The application need to use a Navigator
  • No redundant @Component and @Scope on every view

The following code implies a working Spring + AspectJ, Spring Security and Vaadin setup including the above mentioned SpringVaadinServlet.

So the first thing i came up with is my own ViewDescriptor annotation:

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;
 
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
 
import com.vaadin.navigator.View;
 
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
@Scope(SCOPE_PROTOTYPE)
public @interface ViewDescription {
  /** The name of the view, also used by the navigator, can be a complete path like /foo/bar/baz */
  String name() default "";
 
  /**
   * @return the Spring-EL expression to be evaluated before the view described here is finally added to the navigator.
   */
  String requiredPermissions() default "";
 
  /**
   * @return Can this view be cached if caching is available?
   */
  boolean cacheable() default false;
}

This thing can be used on every class implementing “com.vaadin.navigator.View” and makes it a managed spring component.

The next step is naturally to provide those view to the application using a custom ViewProvider. Here’s my solution that maps view names to view classes and retrieves them from the application context. As the components are prototype scoped it will be new instances for every application instance. If the views can and should be cached, this is implemented as well.

My first solution was a custom (overwritten) Navigator in conjunction with a specialized ViewProvider. But after writing this post and creating a custom project i thought a while longer.

In the end it just needs a custom view SpringSecurityViewProvider who takes care of finding views, checking permissions and caching the views if necessary. So in the end i used the stuff from my previous post to create a view provider who has an autowired ApplicationContext and is used in the Applications init method like this:

final ComponentContainerViewDisplay viewDisplay = new ComponentContainerViewDisplay(this.mainContent);
this.navigator = new Navigator(UI.getCurrent(), viewDisplay);
this.navigator.addProvider(
  SpringSecurityViewProvider.createViewProvider((Authentication) request.getUserPrincipal())
);

The little factory method became necessary because the Application Context cannot be injected into the constructor through it’s transient nature. If i hadn’t the need for the current authentication i probably would have used a @PostConstruct method instead.

In contrast to the first version of this post, the code for the ViewProvider is omitted as i have created a project on Github called Vaadin-SpringSecurityViewProvider. You’ll find the whole source code there including tests that show how to setup a correct load-time-weaving necessary for @Configurable’s.

Using only a custom ViewProvider (which by the way is an interface) is way better than a combination of Navigator and ViewProvider. That way the user can use all navigator constructors and functions.

Our views now looks like this:

@ViewDescription(
    name=SomeView.VIEW_NAME,
    requiredPermissions=
      "isAuthenticated() and " +
      "@authorizationService.hasExecutionalRight(principal, T(some.enumeration.of.BusinessProcesses).PROCESS_NAME)"
)
@DependsOn("application")
public class SomeView extends Panel implements View {
  public final static String VIEW_NAME = "/some/arbitrary/path";
}

You see all the power of SpEL and Spring Security in the requiredPermissions attribute: Not only checking for authentication but also calling an authorization service with the current principal as parameter and an enum constant describing a business process. The whole thing then actually calls an Oracle stored function by the way.

What do you think about this solution? Any ideas for improvement or comments?

Vaadin & Spring: Using @Configurable in Vaadin Components

12-Mar-13

This is going to be one post in a series regarding integration and usage of the Spring Framework with Vaadin.

First of all, thanks to @toberl for giving me a little kickstart to try Vaadin and for his hints for basic integration.

Pretty much every item in Vaadin is or should be serializable. The state of the UI is stored on the server and many container persists sessions between restarts or distribute session among many servers. So if a UI component or a container isn’t serializable, persistent or distributable sessions won’t work. Notice the hint by the author of spring-vaadin: “You should use “transient” attribute for ApplicationContext and other’s context’s beans.”.

For example, if a Vaadin container contains an EntityManager as an attribute, the container isn’t serializable anymore and any view using this container won’t be serializable.

Spring Framework provides a great benefit regarding this problem through it’s pretty integration of @AspectJ. In case you don’t know, read this chapter in the reference documentation. You can use @Configurable to make pretty much any class eligible for Spring-driven configuration.

What does that mean? You can inject any dependency from the application context via @Autowired into any bean not directly managed by spring, for example:

import java.util.Collection;
 
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
 
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
 
@Configurable
public class TestContainer implements Container {	
	private static final long serialVersionUID = -6686019829605781376L;
 
	@PersistenceContext
	private transient EntityManager entityManager;
 
	@Autowired
	private transient SomeService someService;
}

This container is serializable, contains an EntityManager and some arbitrary service. Both of them are not serializable and therefor marked as transient. Springs @AspectJ and @Configurable provides both of them after using standard constructor “new TestContainer()” as well after instances are deserialized. The only drawback here is that one is not able to mark them as final and use constructor injection.

I’m using the following @AspectJ and load-time-weaving configuration

@Configuration
@EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.ENABLED)
@EnableSpringConfigured
@EnableAspectJAutoProxy
public class LTWConfig {
}

together with the TomcatInstrumentableClassLoader:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" disableURLRewriting="true">
	<Loader delegate="false" loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader" />	
</Context>

and can use the dummy TestContainer above like i would use any other class by just calling new and have Spring inject my dependencies.

Optimizing web resources with wro4j, Spring and ehcache

18-Jan-12

I think that almost no website today can do without JavaScript. There are some incredible good JavaScript libraries like jQuery for which an enormous mass of plugins and extensions exits.

The downside of this is, that for example the JavaScript code of my daily picture project Daily Fratze is bigger than the whole startpage of my first “homepage” was.

With every problem there is a solution, namely JavaScript compressors and minifier. Those tools can compress the code by removing superfluous whitespaces, renaming variables and functions or even by optimizing the code.

So far i have used the YUI compressor maven mojo in my Spring based projects. This is a build time solution that compresses JavaScript and CSS files when creating a war file.

For me it had several disadvantages: I don’t see the effect of compressing when i develop my application and it could not concatenate multiple script files.

The later is important because every additional request a browser makes slows down the loading of a webpage. And manual hacking all JavaScript into one file? No way…

wro4j to the rescue:

Free and Open Source Java project which brings together almost all the modern web tools: JsHint, CssLint, JsMin, Google Closure compressor, YUI Compressor, UglifyJs, Dojo Shrinksafe, Css Variables Support, JSON Compression, Less, Sass, CoffeeScript and much more. In the same time, the aim is to keep it as simple as possible and as extensible as possible in order to be easily adapted to application specific needs.

My goal was to integrate wro4j with Spring and ehcache with a minimum number of additional configuration files.

If you’re interested in some of my ideas, read on:

More…

Creating a CSRF protection with Spring 3.1

11-Jan-12

CSRF Attacks still seems to be a problem, a pity that there is no standard solution in the Spring 3.1 framework. Although not probably, i wanted to protect my projects by malicious crafted links.

I didn’t want to use an extra library but something which is already available in the Spring framework. Here is what i come up with:

More…

Creating a better PathMatcher for Spring 3

09-Mar-11

Spring 3 has excellent support for mapping URLs to @Controller methods through the @RequestMapping annotation. This works quite well and i especially like the fact having the mapping right next to the method and not in some other config file like routes.rb.

My goal was to have urls like http://foobar.com/resource, http://foobar.com/resource.html, http://foobar.com/resource.zip etc. This is no problem at all thanks to the ContentNegotiatingViewResolver.

The solution has only one draw back: The format is not known to the controller. Yes, this shouldn’t be a controller concern in most cases but what if you have a format that you don’t want to be available to all users? Maybe an nice zip download of your resources? Handling authentication in a view? I don’t think so.

So my first attempt looked like this

@RequestMapping("/resource.{format}")
public String resource(
		final @PathVariable String format,
		final HttpServletRequest request,
		final Model model
)

That didn’t work because it wouldn’t work for the default text/html resource http://foobar.com/resource so i added

@RequestMapping("/resource")
public String resource(
		final Model model
) {
  this.resource('html', model);
}

That worked for http://foobar.com/resource but not for http://foobar.com/resource.zip… “format” was always html. Hmmm…

After much googling and reading StackOverflow.com i found the “useDefaultSuffixPattern” option on org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping. If set to true (which is the default) the mapping “/resource/” will also map to “/resource/” and “/resource.*”. Although both useful i tried disabling it through my spring-cfg.xml like

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    	<property name="order" value="0" />
    	<property name="useDefaultSuffixPattern" value="false" />
</bean>

Enter the next problem: First, i didn’t work either. Second, all urls where mapped twice. Without the default suffix pattern and with. I spend 2 hours trying to locate the place where the spring config was loaded twice. In the end it was that one line that caused me trouble:

  <mvc:annotation-driven/>

That tag enables a lot of stuff in Spring 3, like the @Controller programming model and many other goodies. What it also does is establishing an AnnotationHandlerMapping that cannot be overwritten. So the next thing i did was browsing through the Spring sources to see what it does and redid with Spring beans in my config file (code follows later).

With that implemented, my urls still didn’t work, for all cases the URL without .{format} was called.

As i was already deep down in the Spring sources i had a look at the default path parser and matcher called AntPathMatcher. There is nothing wrong with the parsing code but the “getPatternComparator” method that “Given a full path, returns a Comparator suitable for sorting patterns in order of explicitness.” had some flaws, at least for my use case.

It sorts the patterns by explicitness and that explicitness is (among others) defined by how many placeholders for path variables are present. So my “/resource” is more explicit that “/resource.{format}”. With that in mind, i extend the path matcher like so:

This PathMatcher delegates most of his methods to the default AntPathMatcher but overwrites the getPatternComparator. If you have a look at the sources you’ll see that it is also partly copied. In the last else branch you’ll see that i sort both patterns by length, strip the default suffix (.*) and check wether the longer pattern starts with the other one. If it does i check wether the difference is just a .{format} (hardcoded). If that’s true, than the pattern with the format suffix is more explicit. Otherwise, i’ll use the default algorithm.

To get this to work, you cannot use the mvc:annotation-driven tag as the PathMatcher is a property of the AnnotationMappingHandler which in turn cannot be overwritten. So to get the same functionality like in Spring 3.0.5 with my PathMatcher use

As you can see i left the useDefaultSuffixPattern option enabled as it works very well with my PathMatcher and i didn’t want to care about mapping “/resource”, “/resource/” etc…

I really hope that the gists will save someone some time. I cannot imagine that i’m the only one having this kind of requirement. The solution is really simple but the way to it was not that easy.

Close
E-mail It