Skip to content
accelerando

Category Archives: Java

CSRF protection with Spring Security revisited

29-Jan-14

At the end of last year, Spring Security 3.2 was released and brought a lot of new features, among them a built-in “Cross Site Request Forgery” protection”.

Nearly two years earlier i wrote my CSRF protection implementation with Spring Security 3.1, have a look here.

I really like the built-in implementation and most of it is very similar to my solution. The main difference is that the protection is at security filter level and not at application level like mine was. Also they use a token class for encapsulating the tokens name and value.

My solution can be very easily adapted to Spring Security 3.2.

First of all, configure it with the onliner

<csrf  />

or use the new annotation based configuration method.

Then throw away everything from my solution except the CSRFTokenTag. Edit the later one to contain the following code:

import java.io.IOException;
import java.util.Random;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
 
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
 
/**
 * Creates a hidden input field with the CSRF Token
 * @author michael.simons, 2011-09-20
 */
@Configurable
public class CSRFTokenTag extends TagSupport {
	private final static Random random = new Random(System.currentTimeMillis());
 
	private static final long serialVersionUID = 745177955805541350L;
 
	private boolean plainToken = false;
	private String elementId;
 
	@Autowired
	private CsrfTokenRepository csrfTokenRepository;
 
	@Override
	public int doStartTag() throws JspException {		
		final CsrfToken token = csrfTokenRepository.loadToken((HttpServletRequest) super.pageContext.getRequest());
		if(token != null)
			try {
				if(plainToken)
					pageContext.getOut().write(token.getToken());
				else
					pageContext.getOut().write(String.format("<input type=\"hidden\" name=\"%s\" id=\"%s\" value=\"%s\" />", token.getParameterName(), StringUtils.isNotBlank(this.elementId) ? this.elementId : String.format("%s_%d", token.getParameterName(), random.nextInt()), token.getToken()));
			} catch (IOException e) {
			}
		return SKIP_BODY;
	}
 
	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}
 
	public boolean isPlainToken() {
		return plainToken;
	}
 
	public void setPlainToken(boolean plainToken) {
		this.plainToken = plainToken;
	}
 
	public String getElementId() {
		return elementId;
	}
 
	public void setElementId(String elementId) {
		this.elementId = elementId;
	}	
}

The guys at Spring have a nice suggestions for including the token for AJAX/Jsons request. The new filter also validates request headers. The recommend adding the header name and token value to the pages meta information like so

  <meta name="_csrf" content="${_csrf.token}"/>
  <meta name="_csrf_header" content="${_csrf.headerName}"/>

and then manually add the header to each JavaScript request made with jQuery.

An alternative for jQuery users would be the following pre filter:

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
	var token = $("meta[name='_csrf']").attr("content");
	var header = $("meta[name='_csrf_header']").attr("content");		  
	jqXHR.setRequestHeader(header, token);
});

I’m happy to be able to get rid of some code of mine, though the solution worked quite well for 2 years now.

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.

Maven snippets

26-Feb-13

This post will contain some Maven snippets that i use and forget regularly (similar to my Git Post).

Download the sources of all dependencies of a project if available:

mvn dependency:sources

Download the JavaDoc for all dependencies if available:

mvn dependency:resolve -Dclassifier=javadoc -Dtype=jar

Check for updates of all direct dependencies:

mvn versions:display-dependency-updates

Skip signing of artifacts (i.e. for a local install of a snapshot)

mvn -Dgpg.skip=true install

If you need to branch from a tag and fix some bugs, i recommend to checkout the tag and then use

mvn release:branch -DbranchName=my-branch -DupdateBranchVersions=true -DupdateWorkingCopyVersions=false

This creates a new branch “my-branch” and updates the version to x.x.x-SNAPSHOT in the branch and leaves the working copy as is.

Last update: 2014/02/08

Java implementation of Excels statistical functions NORMINV

21-Feb-13

I was recently in need of a java implementation of the inverted normal distribution function, named “NORMINV” in Excel 2003 and later: NORMINV.

I only found a JavaScript implementation in kmpm’s repository norminv.js. It has quite a history, coming over C# from C++. I have the impression nobody wants to deal with the mathematics ;)

So here is my Java implementation of NORMINV. As an added bonus it implements org.apache.poi.ss.formula.functions.FreeRefFunction to be used as a User defined function in Apache POI:

import org.apache.poi.ss.formula.OperationEvaluationContext;
import org.apache.poi.ss.formula.eval.EvaluationException;
import org.apache.poi.ss.formula.eval.NumberEval;
import org.apache.poi.ss.formula.eval.OperandResolver;
import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.formula.functions.FreeRefFunction;
 
/**
 * Java Implementation of http://support.microsoft.com/kb/827358/en-us implementing 
 * Apache POIs {@link FreeRefFunction} to be used as a user defined function.
 * 
 * Mathematics found here: 
 * https://gist.github.com/kmpm/1211922/
 * https://gist.github.com/kmpm/1211922/raw/a11e0dfc9fab493bcdadc669f3213d11f1897ebf/norminv.js
 * 
 * Register for a given workbook with:
 * 
    <code>
		final UDFFinder udfs = new DefaultUDFFinder(new String[]{ "MS_NormInv" }, new FreeRefFunction[]{ new NormInv() }) ;        
		workbook.addToolPack(new AggregatingUDFFinder(new UDFFinder[] {udfs}));
    </code>
 * @author michael.simons
 */
public class NormInv implements FreeRefFunction {
	public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {		
		try {
			final ValueEval p = OperandResolver.getSingleValue(args[0], ec.getRowIndex(), ec.getColumnIndex()) ;
			final ValueEval mu = OperandResolver.getSingleValue(args[1], ec.getRowIndex(), ec.getColumnIndex()) ;
			final ValueEval sigma = OperandResolver.getSingleValue(args[2], ec.getRowIndex(), ec.getColumnIndex()) ;			
			return new NumberEval(this.compute(OperandResolver.coerceValueToDouble(p), OperandResolver.coerceValueToDouble(mu), OperandResolver.coerceValueToDouble(sigma)));
		} catch (EvaluationException e) {
			return e.getErrorEval();
		}			 		
	}
 
	/**
	 * Original C++ implementation found at http://www.wilmott.com/messageview.cfm?catid=10&threadid=38771
	 * C# implementation found at http://weblogs.asp.net/esanchez/archive/2010/07/29/a-quick-and-dirty-implementation-of-excel-norminv-function-in-c.aspx
	 *    Compute the quantile function for the normal distribution.
	 *
	 *    For small to moderate probabilities, algorithm referenced
	 *    below is used to obtain an initial approximation which is
	 *    polished with a final Newton step.
	 *    For very large arguments, an algorithm of Wichura is used.
	 *
	 *  REFERENCE
	 *
	 *    Beasley, J. D. and S. G. Springer (1977).
	 *    Algorithm AS 111: The percentage points of the normal distribution,
	 *    Applied Statistics, 26, 118-121.
	 *
	 *     Wichura, M.J. (1988).
	 *     Algorithm AS 241: The Percentage Points of the Normal Distribution.
	 *     Applied Statistics, 37, 477-484.
	 * @param p
	 * @param mu
	 * @param sigma
	 * @return
	 */
	public double compute(double p, double mu, double sigma) {
		if(p < 0 || p > 1) 
			throw new RuntimeException("The probality p must be bigger than 0 and smaller than 1");		
		if(sigma < 0)
			throw new RuntimeException("The standard deviation sigma must be positive");
		if(p == 0)
			return Double.NEGATIVE_INFINITY;		
		if(p == 1)
			return Double.POSITIVE_INFINITY;		
		if(sigma == 0)
			return mu;		
		double  q, r, val;
 
		q = p - 0.5;
 
		/* 0.075 <= p <= 0.925 */
		if(Math.abs(q) <= .425) {
			r = .180625 - q * q;
			val =
		         q * (((((((r * 2509.0809287301226727 +
		                    33430.575583588128105) * r + 67265.770927008700853) * r +
		                  45921.953931549871457) * r + 13731.693765509461125) * r +
		                1971.5909503065514427) * r + 133.14166789178437745) * r +
		              3.387132872796366608)
		         / (((((((r * 5226.495278852854561 +
		                  28729.085735721942674) * r + 39307.89580009271061) * r +
		                21213.794301586595867) * r + 5394.1960214247511077) * r +
		              687.1870074920579083) * r + 42.313330701600911252) * r + 1);
		}
		/* closer than 0.075 from {0,1} boundary */
		else {
		     /* r = min(p, 1-p) < 0.075 */
			 if (q > 0) {
				 r = 1 - p;
			 } else {
				 r = p;
			 }
 
			 r = Math.sqrt(-Math.log(r));
			 /* r = sqrt(-log(r))  < ==>  min(p, 1-p) = exp( - r^2 ) */
 
			 if (r < = 5) { /* <==> min(p,1-p) >= exp(-25) ~= 1.3888e-11 */
				 r += -1.6;
				 val = (((((((r * 7.7454501427834140764e-4 +
		                     .0227238449892691845833) * r + .24178072517745061177) *
		                   r + 1.27045825245236838258) * r +
		                  3.64784832476320460504) * r + 5.7694972214606914055) *
		                r + 4.6303378461565452959) * r +
		               1.42343711074968357734)
		              / (((((((r *
		                       1.05075007164441684324e-9 + 5.475938084995344946e-4) *
		                      r + .0151986665636164571966) * r +
		                     .14810397642748007459) * r + .68976733498510000455) *
		                   r + 1.6763848301838038494) * r +
		                  2.05319162663775882187) * r + 1);
			 } else { /* very close to  0 or 1 */
				 r += -5;
				 val = (((((((r * 2.01033439929228813265e-7 +
		                     2.71155556874348757815e-5) * r +
		                    .0012426609473880784386) * r + .026532189526576123093) *
		                  r + .29656057182850489123) * r +
		                 1.7848265399172913358) * r + 5.4637849111641143699) *
		               r + 6.6579046435011037772)
		              / (((((((r *
		                       2.04426310338993978564e-15 + 1.4215117583164458887e-7) *
		                      r + 1.8463183175100546818e-5) * r +
		                     7.868691311456132591e-4) * r + .0148753612908506148525)
		                   * r + .13692988092273580531) * r +
		                  .59983220655588793769) * r + 1);
		      }
 
		      if (q < 0.0) {
		          val = -val;
		      }
		  }
 
		  return mu + sigma * val;		
	}
}

More…

Close
E-mail It