Monday, November 30, 2015

A tutorial on how to use the Tapestry-Security module Part 1

It often bothered me how many times I've been answering questions from my students (and Stack) this question: "How do you use Tapestry-Security?"

Actually, Tynamo already wrote a guide but some are actually having a hard time figuring it out. They are confused by the database part and how it connects to the authentication and authorization parts. So this is where I come in and since this is should be pretty long post, I'm breaking it into two parts. Also, I'd be working on the assumption readers:
  • Have working knowledge of Tapestry5
  • Can get a Tapestry5 DAO service going
  • Basic understanding how Shiro works (or at least read the tutorial); YOU NEED TO UNDERSTAND SHIRO because Tapestry-Security is based on it.
  • Are OK with me using jasypt lib for encryption; I know it's not the best so chill your titties, we need to make work first THEN we'll deal with a much stronger encryption procedure.
To get started,

Open your POM.xml file and add the Tapestry-Security and Jasypt modules as a dependency.

<dependency>  
  <groupId>org.tynamo</groupId>  
  <artifactId>tapestry-security</artifactId>  
  <version>0.6.2</version>  
</dependency> 

<dependency>  
  <groupId>org.jasypt</groupId>  
  <artifactId>jasypt</artifactId>  
  <version>1.9.2</version>  
</dependency> 

Rebuild your project after to get the module.

Once that's out of the way, we should start creating a Realm. We are making an Authorizing Realm, which authenticates subjects (or users) AND authorizes them with either Roles or Permissions. Here's a sample:

public class MySecurityRealm extends AuthorizingRealm {

    @Inject
    private UserMembershipDAO umDAO;
    
    public MiscAppRealm() {
        super(new MemoryConstrainedCacheManager());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

You then need to configure your WebSecurityManager to use this realm. The WebSecurityManager service is something that Tapestry-Security module adds. Also, don't worry about the unimplemented methods in the realm. We're going to fix that on the next post.