Securing GWT Apps using Spring Oauth & Spring Social

General purpose :

Provides a spring security configuration for any Oauth2 providers in our projects. For that I found many good starting points on the web and I merged them into a simple GWTP project forked from an existing repository ( which helped me to achieve this goal with minor changes.

This a solution for GWT developers who want to provide a session management using usual (Google, Facebook, …) or custom Oauth2 provider in their applications.

Dependency management :


<!-- Spring Social -->

<!-- Persistance dependencies -->

2 – Custom provider definition :

I added some classes here as other embedded Social provider to define my own provider

– Provider definition

public interface Corporate {
    CorporatePofile getUserProfile();

    void updateStatus(String message);

– Oauth2 provider service

public class CorporateServiceProvider extends AbstractOAuth2ServiceProvider<Corporate> {
    public CorporateServiceProvider(OAuth2Operations oauth2Operations) {

    public Corporate getApi(String s) {
        return new CorporateServiceTemplate(s);

– Provider service template

public class CorporateServiceTemplate extends AbstractOAuth2ApiBinding implements Corporate {
    private final static String corporateProfileURL = "http://localhost:8080/oauthprotoserver/profile/";
    private String accessToken;

    CorporateServiceTemplate(String accessToken) {
        this.accessToken = accessToken;

    public CorporatePofile getUserProfile() {
        try {
            ResponseEntity<String> content = getRestTemplate().exchange(URI.create(corporateProfileURL + accessToken),
                    HttpMethod.GET, null, String.class);

            // TODO Retrieve a Corporate JSON user build a serialized object
            return new CorporatePofile(content.getBody(),"","client1","employee","foo","bar");

        }  catch (HttpClientErrorException e2) {
            throw new OAuth2Exception(e2.getMessage());

    public void updateStatus(String message) {

And to perform the implicit SignUp and build a valid session with SocialUserDetails

– A SimpleConnectionSignUp which requires a JDBC user connection repository

public final class SimpleConnectionSignUp implements ConnectionSignUp {
    private final AtomicLong userIdSequence = new AtomicLong();

    public String execute(Connection<?> connection) {
        return Long.toString(userIdSequence.incrementAndGet());

– A SimpleSignInAdapter which will help to store UserDetails into Security Context

public class SimpleSignInAdapter implements SignInAdapter {
    private static final Logger log = LoggerFactory.getLogger(SimpleSignInAdapter.class);
    private final RequestCache requestCache;
    private final NuvolaCasDetailsService userService;

    public SimpleSignInAdapter(RequestCache requestCache,
                               NuvolaCasDetailsService userService) {
        this.requestCache = requestCache;
        this.userService = userService;

    public String signIn(String localUserId, Connection<?> connection, NativeWebRequest request) {
        SocialUserDetails user = userService.loadUserByUserId(connection.getDisplayName());
        // Return Application home page
        return "/";

This will help us into the final step add a simple login page to post a SignIn request catched by the ProviderSignInController (Framework controller)

<div align="center">
    <form id="casForm" name="casForm" action="/api/signin/corporate" method="POST" >
        <p><input name="login" value="Connexion via Portail" type="submit"></p>

The “corporate” at the end of the uri (/api/signin/corporate) is our providerId which is a Path parameter helping the controller to build a valid OAuth2ConnectionFactory.

3 – Spring security configuration :

public UserDetailsService userDetailsServiceBean() throws Exception {
    return super.userDetailsServiceBean();

OAuth2Template restTemplate() {
    return new OAuth2Template(corporateProvider().getClientId(),

@Scope(value="singleton", proxyMode= ScopedProxyMode.INTERFACES)
public SocialAuthenticationServiceLocator socialAuthenticationServiceLocator() {
    SocialAuthenticationServiceRegistry registry = new SocialAuthenticationServiceRegistry();
    registry.addConnectionFactory(new CorporateConnectionFactory(restTemplate()));

    return registry;

@Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES)
public UsersConnectionRepository usersConnectionRepository() {
    JdbcUsersConnectionRepository connectionRepository =
            new JdbcUsersConnectionRepository(dataSource, socialAuthenticationServiceLocator(), Encryptors.noOpText());
    connectionRepository.setConnectionSignUp(new SimpleConnectionSignUp());
    return connectionRepository;

public ProviderSignInController providerSignInController() {
    ProviderSignInController controller = new ProviderSignInController(socialAuthenticationServiceLocator(),
            usersConnectionRepository(), new SimpleSignInAdapter(new HttpSessionRequestCache(),
    return controller;

AuthorizationCodeResourceDetails corporateProvider() {
    AuthorizationCodeResourceDetails codeResourceDetails = new AuthorizationCodeResourceDetails();
    return codeResourceDetails;

AuthorizationCodeResourceDetails googleProvider() {
    return null;

AuthorizationCodeResourceDetails facebookProvider() {
    return null;

protected AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManager();

protected void configure(HttpSecurity http) throws Exception {
            .apply(new SpringSocialConfigurer()


The complete source code is available here : I hope this will help many developers to customize Oauth2 authorization and authentication process via providers. This implementation supports the Oauth2 authorization code flow. Thanks to Spring community for this huge work


Securing Spring Faces (Webflow 2 + Spring Security 3) application.

The post is for people who are using Spring Faces and need basic security aspects.

Update your spring faces dependency in the pom.xml if your project is a maven one :
There is a bug in the 2.3.0 Release between the flow executor and phase listener. This is important because our login page is a facelet which is not in a flow.


Add context security file to the configuration with this content :

<security:http auto-config="true">
		<security:intercept-url pattern="/views/**" access="ROLE_USER"/>
			login-page="/" authentication-failure-url="/"
			default-target-url="/flowprocess/shopping" />
	<security:user-service id="userService">
    		<security:user name="guest" password="guest" authorities="ROLE_USER"/>
		<security:authentication-provider user-service-ref="userService"/>

Configuring security into webflow in 2 steps:

1 – Adding secure flow context listener into the configuration file as shown below :

<beans:bean id="securityFlowExecutionListener" class="" />

<beans:bean id="facesContextListener" class="org.springframework.faces.webflow.FlowFacesContextLifecycleListener"/>

<flow-executor id="flowExecutor">
		<listener ref="facesContextListener"/>
		<listener ref="securityFlowExecutionListener"/>

2 – Configure the flow to check access and authorizations before runing by adding the secure tag into the flow.xml file:

<flow start-state="identifyCustomer" xmlns=""

<secured attributes="ROLE_USER"/>


Very Important Notice : If we’re using subflows in our architecture, Spring does not propagate the secured configuration to child. Secure tag must be explicitely mentionned in all our subflows. I hope this will be a fix in further releases.

Create a Spring security form-login as index page into the project.

<h:form prependId="false" >
	<table class="form">
		<td><h:outputLabel value="Identifiant: " for="j_username" /></td>
		<td><h:inputText id="j_username" required="true" value="#{authenticationBean.username}" styleClass="textInput" /></td>
		<td><h:outputLabel value="Mot de passe " for="j_password" /></td>
		<td><h:inputSecret id="j_password" required="true" value="#{authenticationBean.password}" styleClass="textInput" /></td>
	<div class="buttonContainer">
		<h:commandLink styleClass="styledButton" action="#{authenticationBean.onLogin}" value="Connect"  />

Now the flow is secure and to execute it, user should give corrects credentials. In the next article i’ll integrate OpenID authentication.

In my project i have shopping-flow wich use customer-flow as subflow. To check the point in notice above, try to call directly the shopping/customer here unsecured access to the subflow and secured access, redirection to the login

The complete project source code is available here github

Drools – Guvnor: Spring integration

Using Spring 2.5, Drools-guvnor 5.0

Download Drools guvnor standalone version here jboss-drools-guvnor

Spring configuration:
– bean rulesAgent is for communication between our application and guvnor,
the Drools platform BRMS.
– bean droolsService uses rulesAgent to provide the needed service.

<bean id="rulesAgent" class="com.test.droolsproto.utils.DroolsProtoAgent"></bean>
<bean id="droolsService" class="com.test.droolsproto.serviceImpl.RuleDroolServiceImpl">
<property name="ruleAgent" ref="rulesAgent"></property>

Create file “” for the ruleAgent:
In this file the link to use a running instance of guvnor. The package “com.test.droolsproto.rules” is an existing rules package in guvnor. DroolsDemo at the end of package value is the name of the snapshot. A snapshot in guvnor represents an image of rule’s package at specific time.

package= com.test.droolsproto.rules/DroolsDemo

In the web project add drools librairies (drools-api-5.0.1, drools-core-5.0.1) and create DroolsProtoAgent class:

public class DroolsProtoAgent {
   private RuleBase rulebase;
   private StatefulSession session;
   private DroolsProtoAgent(){
   public RuleBase getRulebase() {
    if (rulebase != null) return rulebase;
    else {
       RuleAgent agent = RuleAgent.newRuleAgent( "/" );
       RuleBase rulebase = agent.getRuleBase();
       return rulebase;
  public void setRulebase(RuleBase rulebase) {
    this.rulebase = rulebase;
  public void setSession(StatefulSession session) {
    this.session = session;
  public StatefulSession getSession() {
    if ( rulebase == null ) {
      rulebase = getRulebase();
    session = rulebase.newStatefulSession();
    return session;

Create a drools service:

public class RuleDroolServiceImpl implements RuleDroolsService {

   private DroolsProtoAgent ruleAgent;

   public String applyRule(ValueObject a, ValueObject b){

   try {
     // Load knowledge base session
     StatefulSession ksession = ruleAgent.getSession();
     ksession.startProcess("droolsProcess"); //Start a predefined process in guvnor
     // Insert VO as Fact

     ksession.fireAllRules(); //Apply rules
     return "success or specific guvnor response";
   } catch (Throwable t) {
     return "failure";

  public DroolsProtoAgent getRuleAgent() {
   return ruleAgent;

  public void setRuleAgent(DroolsProtoAgent ruleAgent) {
   this.ruleAgent = ruleAgent;

Drools integration is complete.