Motivation

OpenID is a service providing single-sign-on features. At our institute we are operating an OpenID provider that delegates authentication to our ActiveDirectory where all our students are registered. For a course planning system I was assessing Tapestrys integration possibilities with this OpenID provider and found out, that the tapestry-spring-security project already has much of the stuff needed for integration with our provider on board. This is a description of what you have to do in order to have OpenID authentication in your Tapestry apps.

Background

Spring Security already comes with everything needed for authenticating users against an OpenID provider (although this is somewhat incomplete regarding additional attributes that can be provided by the OpenID provider). But the tapestry-spring-security lacks the configuration needed to use this out of the box. In particular it lacks the filter configuration for the OpenIDAuthenticationProcessingFilter that processes incoming OpenID authentications. In a "normal" setup this is just another Filter that you configure in your web.xml. In a Tapestry setup though, Tapestry receives all incoming requests and processes them in the HttpServletRequestHandler pipeline. Fortunately this pipeline can be extended by contributing HttpServletRequestFilters. So all we need to do is wrap the OpenIDAuthenticationProcessingFilter and contribute it to the HttpServletRequestHandler pipeline. Such a wrapper is provided by the tapestry-spring-security project. With that in place we can process incoming OpenID authentication requests. Next, we have to look up the authenticated user in our local database where we store the roles assigned to a user. For this we have to implement a UserDetailsService which retrieves a user and his roles from some data store. The user object that is returned has to implement the UserDetails interface and the roles he holds have to implement the GrantedAuthority interface. If you don't want to grant access to some OpenID authenticated user, you have to do that in the UserDetailsService. The implementation I will show you grants accesss to EVERY OpenID authenticated user so don't use this in a "real" environment.

Requirements

tapestry-hibernate and tapestry-spring-security have to be in your pom.xml (or their jars and all of their dependencies have to be in your classpath). Configuring tapestry-hibernate is outside the scope of this article, please consult it's own documentation.

Implementation

Let's begin with the User and Role objects that implement the UserDetails and GrantedAuthority interfaces, respectively. These are used to store users and their roles in a local database using Hibernate. The User is a minimalistic implementation that only stores an id and a username.

   1 package org.mygroup.myapp.entities;
   2 
   3 import java.util.HashSet;
   4 import java.util.Set;
   5 
   6 import javax.persistence.Entity;
   7 import javax.persistence.GeneratedValue;
   8 import javax.persistence.GenerationType;
   9 import javax.persistence.Id;
  10 import javax.persistence.ManyToMany;
  11 import javax.persistence.Transient;
  12 
  13 import org.springframework.security.GrantedAuthority;
  14 import org.springframework.security.GrantedAuthorityImpl;
  15 import org.springframework.security.userdetails.UserDetails;
  16 
  17 /**
  18  * A minimalistic UserDetails implementation providing a username only. Storing
  19  * a password is not necessary since the OpenID provider will do the authentication.
  20  * 
  21  * @author Ulrich Stärk
  22  */
  23 @Entity
  24 public class User implements UserDetails
  25 {
  26     private static final long serialVersionUID = 4068206679084877888L;
  27 
  28     private int id;
  29 
  30     private String username;
  31 
  32     private Set<Role> roles;
  33 
  34     @Id
  35     @GeneratedValue(strategy = GenerationType.AUTO)
  36     public int getId()
  37     {
  38         return id;
  39     }
  40 
  41     public void setId(int id)
  42     {
  43         this.id = id;
  44     }
  45 
  46     @ManyToMany
  47     public Set<Role> getRoles()
  48     {
  49         return roles;
  50     }
  51 
  52     public void setRoles(Set<Role> roles)
  53     {
  54         this.roles = roles;
  55     }
  56 
  57     @Transient
  58     public GrantedAuthority[] getAuthorities()
  59     {
  60         Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
  61 
  62         for (Role role : getRoles())
  63         {
  64             authorities.add(new GrantedAuthorityImpl(role.getAuthority()));
  65         }
  66 
  67         return authorities.toArray(new GrantedAuthority[authorities.size()]);
  68     }
  69 
  70     @Transient
  71     public String getPassword()
  72     {
  73         return "notused";
  74     }
  75 
  76     public String getUsername()
  77     {
  78         return username;
  79     }
  80 
  81     public void setUsername(String username)
  82     {
  83         this.username = username;
  84     }
  85 
  86     @Transient
  87     public boolean isAccountNonExpired()
  88     {
  89         return true;
  90     }
  91 
  92     @Transient
  93     public boolean isAccountNonLocked()
  94     {
  95         return true;
  96     }
  97 
  98     @Transient
  99     public boolean isCredentialsNonExpired()
 100     {
 101         return true;
 102     }
 103 
 104     @Transient
 105     public boolean isEnabled()
 106     {
 107         return true;
 108     }
 109 }

   1 package org.mygroup.myapp.entities;
   2 
   3 import javax.persistence.Entity;
   4 import javax.persistence.GeneratedValue;
   5 import javax.persistence.GenerationType;
   6 import javax.persistence.Id;
   7 
   8 import org.springframework.security.GrantedAuthority;
   9 
  10 /**
  11  * A GrantedAuthority (aka Role) implementation. hashCode, equals and compareTo are
  12  * a bit messy (auto-generated), you might want to change this.
  13  * 
  14  * @author Ulrich St&auml;rk
  15  */
  16 @Entity
  17 public class Role implements GrantedAuthority
  18 {
  19     private static final long serialVersionUID = -117212611936641518L;
  20 
  21     @Id
  22     @GeneratedValue(strategy = GenerationType.AUTO)
  23     private int id;
  24 
  25     private String authority;
  26 
  27     public int getId()
  28     {
  29         return id;
  30     }
  31 
  32     public void setId(int id)
  33     {
  34         this.id = id;
  35     }
  36 
  37     public String getAuthority()
  38     {
  39         return authority;
  40     }
  41 
  42     public void setAuthority(String authority)
  43     {
  44         this.authority = authority;
  45     }
  46 
  47     @Override
  48     public int hashCode()
  49     {
  50         return authority.hashCode();
  51     }
  52 
  53     @Override
  54     public boolean equals(Object obj)
  55     {
  56         if (this == obj) return true;
  57         if (obj == null) return false;
  58         if (obj instanceof String) return obj.equals(authority);
  59         if (getClass() != obj.getClass()) return false;
  60         final Role other = (Role) obj;
  61         if (authority == null)
  62         {
  63             if (other.authority != null) return false;
  64         }
  65         else if (!authority.equals(other.authority)) return false;
  66         return true;
  67     }
  68 
  69     public int compareTo(Object o)
  70     {
  71         if (this == o) return 0;
  72         if (o == null) return -1;
  73         if (o.getClass() == String.class) return authority.compareTo((String) o);
  74         if (getClass() != o.getClass()) return -1;
  75         final Role other = (Role) o;
  76         if (authority == null)
  77         {
  78             if (other.authority != null) return 1;
  79         }
  80         else
  81             return authority.compareTo(other.authority);
  82         return -1;
  83     }
  84 }

Next, we need a UserDetailsService implementation, that finds users and their roles in our local database:

   1 package org.mygroup.myapp.services.impl;
   2 
   3 import java.util.HashSet;
   4 
   5 import org.apache.tapestry5.hibernate.HibernateSessionManager;
   6 import org.hibernate.Session;
   7 import org.hibernate.criterion.Restrictions;
   8 import org.slf4j.Logger;
   9 import org.springframework.dao.DataAccessException;
  10 import org.springframework.security.userdetails.UserDetails;
  11 import org.springframework.security.userdetails.UserDetailsService;
  12 import org.springframework.security.userdetails.UsernameNotFoundException;
  13 
  14 import de.spielviel.mailadmin.entities.Role;
  15 import de.spielviel.mailadmin.entities.User;
  16 
  17 /**
  18  * @author Ulrich St&auml;rk
  19  */
  20 public class UserDetailsServiceImpl implements UserDetailsService
  21 {
  22     private HibernateSessionManager sessionManager;
  23 
  24     private Logger logger;
  25 
  26     public UserDetailsServiceImpl(HibernateSessionManager sessionManager, Logger logger)
  27     {
  28         this.sessionManager = sessionManager;
  29         this.logger = logger;
  30     }
  31 
  32     /**
  33      * Try to find the given user in the local database. Since we are using OpenID that user
  34      * might not exist in our database yet. If it doesn't, create a new user and store it.
  35      * 
  36      * WARNING: This implementation will permit EVERY OpenID authenticated user to log in. In
  37      * a real environment you want to restrict this to trusted OpenID providers or you have
  38      * to restrict those users to non-sensible information (by means of roles).
  39      */
  40     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,
  41             DataAccessException
  42     {
  43         logger.debug("trying to find user " + username);
  44 
  45         Session session = sessionManager.getSession();
  46 
  47         User u = (User) session.createCriteria(User.class).add(
  48                 Restrictions.eq("username", username)).uniqueResult();
  49 
  50         if (u == null)
  51         {
  52             logger.debug("user not found, creating");
  53 
  54             Role r = (Role) session.createCriteria(Role.class).add(
  55                     Restrictions.eq("authority", "ROLE_USER")).uniqueResult();
  56 
  57             if (r == null)
  58             {
  59                 logger.debug("role not found, creating");
  60 
  61                 r = new Role();
  62 
  63                 r.setAuthority("ROLE_USER");
  64 
  65                 session.saveOrUpdate(r);
  66             }
  67 
  68             u = new User();
  69 
  70             u.setUsername(username);
  71 
  72             u.setRoles(new HashSet<Role>());
  73 
  74             u.getRoles().add(r);
  75 
  76             session.saveOrUpdate(u);
  77         }
  78 
  79         logger.debug("returning user " + u.getUsername());
  80 
  81         sessionManager.commit();
  82 
  83         return u;
  84     }
  85 
  86 }

That's it. The rest is setting this all up in your AppModule.

Tying it together

Setting up the OpenID authentication is done in two steps. First we need to add an AuthenticationProvider that provides OpenID authentication and contribute this to the ProviderManager service which is defined by the tapestry-spring-security module. The OpenIDAuthenticationProvider comes directly from Spring security and just has to be set up correctly. Basically it is some kind of wrapper around the UserDetailsService. The following code builds the UserDetailsService and the OpenIDAuthenticationProvider and contributes it to the ProviderManager service:

   1 public static UserDetailsService buildUserDetailsService(Logger logger,
   2         @InjectService("HibernateSessionManager")
   3         HibernateSessionManager session)
   4 {
   5     return new UserDetailsServiceImpl(session, logger);
   6 }
   7 
   8 public static OpenIDAuthenticationProvider buildOpenIDAuthenticationProvider(
   9         @InjectService("UserDetailsService")
  10         UserDetailsService userDetailsService) throws Exception
  11 {
  12     OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
  13 
  14     provider.setUserDetailsService(userDetailsService);
  15 
  16     provider.afterPropertiesSet();
  17 
  18     return provider;
  19 }
  20 
  21 public static void contributeProviderManager(
  22         OrderedConfiguration<AuthenticationProvider> configuration,
  23         
  24         @InjectService("OpenIDAuthenticationProvider")
  25         AuthenticationProvider openIdAuthenticationProvider)
  26 {
  27     configuration.add("openIDAuthenticationProvider", openIdAuthenticationProvider);
  28 }

Next we have to define ourselves a URL to which incoming OpenID authentication requests will be send and which the filter intercepts. Background: Every filter is intercepting requests for it's specific URL. If we just used the URL of an existing filter, our OpenID filter would intercept requests for this filter, thus making authentication fail.

   1 public static void contributeApplicationDefaults(
   2         MappedConfiguration<String, String> configuration)
   3 {
   4     /* here goes your own configuration... */
   5     ...
   6 
   7     configuration.add("spring-security.openidcheck.url", "/j_spring_openid_security_check");
   8 }

The second part is to configure the filter that intercepts incoming OpenID authentication requests and delegates those to the respective services:

   1 public static OpenIDAuthenticationProcessingFilter buildRealOpenIDAuthenticationProcessingFilter(
   2         @SpringSecurityServices final AuthenticationManager manager,
   3         
   4         @SpringSecurityServices final RememberMeServices rememberMeServices,
   5         
   6         @Inject @Value("${spring-security.openidcheck.url}") final String authUrl,
   7         
   8         @Inject @Value("${spring-security.target.url}") final String targetUrl,
   9         
  10         @Inject @Value("${spring-security.failure.url}") final String failureUrl) throws Exception
  11 {
  12     OpenIDAuthenticationProcessingFilter filter = new OpenIDAuthenticationProcessingFilter();
  13 
  14     filter.setAuthenticationManager(manager);
  15 
  16     filter.setAuthenticationFailureUrl(failureUrl);
  17 
  18     filter.setDefaultTargetUrl(targetUrl);
  19 
  20     filter.setFilterProcessesUrl(authUrl);
  21 
  22     filter.setRememberMeServices(rememberMeServices);
  23 
  24     filter.afterPropertiesSet();
  25 
  26     return filter;
  27 }
  28 
  29 public static HttpServletRequestFilter buildOpenIDAuthenticationProcessingFilter(
  30         final OpenIDAuthenticationProcessingFilter filter)
  31 {
  32     return new HttpServletRequestFilterWrapper(filter);
  33 }

This filter then has to be contributed to the HttpServletRequestHandler pipeline. The order (before: and after:) is very important (don't get this wrong or nothing will work):

   1 public static void contributeHttpServletRequestHandler(
   2         OrderedConfiguration<HttpServletRequestFilter> configuration,
   3         
   4         @InjectService("OpenIDAuthenticationProcessingFilter")
   5         HttpServletRequestFilter openIDAuthenticationProcessingFilter)
   6 {
   7     configuration.add(
   8             "openIDAuthenticationProcessingFilter",
   9             
  10             openIDAuthenticationProcessingFilter,
  11             
  12             "before:springSecurityAuthenticationProcessingFilter",
  13             
  14             "after:springSecurityHttpSessionContextIntegrationFilter");
  15 }

And that's it. If you now secure your pages/methods with the @Secured annotation and provide a login page, you should be able to login with your OpenID. For the sake of completeness, here is the Login page and it's template:

   1 package org.yourgroup.yourapp.pages;
   2 
   3 import org.apache.tapestry5.ioc.annotations.Inject;
   4 import org.apache.tapestry5.ioc.annotations.Value;
   5 import org.apache.tapestry5.services.Request;
   6 
   7 /**
   8  * The login page (adapted from the tapestry-spring-security project).
   9  * 
  10  * @author Ulrich St&auml;rk
  11  */
  12 public class LoginPage
  13 {
  14     @Inject
  15     @Value("${spring-security.openidcheck.url}")
  16     private String checkUrl;
  17 
  18     @Inject
  19     private Request request;
  20 
  21     private boolean failed = false;
  22 
  23     public boolean isFailed()
  24     {
  25         return failed;
  26     }
  27 
  28     public String getLoginCheckUrl()
  29     {
  30         return request.getContextPath() + checkUrl;
  31     }
  32 
  33     void onActivate(String extra)
  34     {
  35         if (extra.equals("failed"))
  36         {
  37             failed = true;
  38         }
  39     }
  40 
  41 }

LoginPage.tml:

<html t:type="layout" xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd">
<form xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd" action="${loginCheckUrl}" method="POST">
    <t:if test="failed">Username and/or password was wrong!<br /></t:if>
    <label class="username" for="j_username">Username:</label>
    <input class="username" name="j_username" type="text" size="30"/>
    <input id="submit" class="submit" type="submit" value="log in"/>
</form>
</html>

An example of how a login page for both form-based and OpenID based login could look like:

LoginPage.java:

   1 package org.yourgroup.yourapp.pages;
   2 
   3 import org.apache.tapestry5.ioc.annotations.Inject;
   4 import org.apache.tapestry5.ioc.annotations.Value;
   5 import org.apache.tapestry5.services.Request;
   6 
   7 /**
   8  * The login page (adapted from the tapestry-spring-security project).
   9  * 
  10  * @author Ulrich St&auml;rk
  11  */
  12 public class LoginPage
  13 {
  14     @Inject
  15     @Value("${spring-security.check.url}")
  16     private String checkUrl;
  17     
  18     @Inject
  19     @Value("${spring-security.openidcheck.url}")
  20     private String openidCheckUrl;
  21 
  22     @Inject
  23     private Request request;
  24 
  25     private boolean failed = false;
  26 
  27     public boolean isFailed()
  28     {
  29         return failed;
  30     }
  31 
  32     public String getLoginCheckUrl()
  33     {
  34         return request.getContextPath() + checkUrl;
  35     }
  36     
  37     public String getOpenIdCheckUrl()
  38     {
  39         return request.getContextPath() + openidCheckUrl;
  40     }
  41 
  42     void onActivate(String extra)
  43     {
  44         if (extra.equals("failed"))
  45         {
  46             failed = true;
  47         }
  48     }
  49 }

LoginPage.tml:

<html t:type="layout" xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd">
OpenID: <br />
<form xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd" action="${openIdCheckUrl}" method="POST">
    <t:if test="failed">Username and/or password was wrong!<br /></t:if>
    <label class="username" for="j_username">Username:</label>
    <input class="username" name="j_username" type="text" size="30"/>
    <input id="submit" class="submit" type="submit" value="log in"/>
</form>
Form-based: <br />
<form xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd" action="${loginCheckUrl}" method="POST">
    <t:if test="failed">Username and/or password was wrong!<br /></t:if>
    <label class="username" for="j_username">Username:</label>
    <input class="username" name="j_username" type="text" size="30"/>
    <label class="password" for="j_password">Password</label>
    <input class="password" name="j_password" type="password" size="10" maxlength="30"/>
    <input id="submit" class="submit" type="submit" value="log in"/>
</form>
</html>

Tapestry5HowToSpringSecurityAndOpenId (last edited 2010-04-28 19:40:40 by newacct)