englishteeth.co.uk

… the weblog of Ian “English Teeth” Robinson
  • rss
  • Home

Grails: Role based security on Jetty & JBoss

Ian | October 22, 2008

Todays challenge.. Security!

Hardly a challenge at all really, the JSecurity Plugin - Quick Start takes you through everything you need to do and there’s also a AcegiSecurity Plugin, if that’s your bag.

There you go, post done.

Well… unless you want/need to use JEE role based authentication at the application server level. That’s a little more involved.

Unfortunately, this involves a little jiggery pokery in grails itself, but this is only really to have the bundled jetty server include some security configuration. The intention here is after all, having the authentication at the application server level.

The task has been covered admirably at the coders corner in the article Setting up Grails to work with JEE role based authentication. This then goes on expand on how to expose the grails project’s web.xml, in order to configure the access.
grails install-templates
And what you need to put in src/templates/web.xml to configure the access is covered in Using Role based security, in much greater detail than I would want to duplicate here.

There really is nothing to add so far, the steps described just work.

The next step took a bit more digging and looking outside of grails oriented guides. The actual deployment environment I have to target is JBoss, but the best description of the security configuration I found was in the article JBoss Role-Based Security.

This got me 90% there. To bend it to grails, I had to add a little bit more to the jboss-web.xml file I added for deploying to JBoss:

    <context-root>/my_app</context-root>
    <security-domain>java:/jaas/my_app_policy</security-domain>

Obviously making sure the domain matched what I had put in the JBoss configuration.

I also happened to include two properties files for roles and users in src\java so they were deployed with the application and reference these in the JBoss configuration file login-config.xml:

  <application-policy name ="my_app_policy">
    <authentication>
      <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required">
        <module-option name="usersProperties">my_app-users.properties</module-option>
        <module-option name="rolesProperties">my_app-roles.properties</module-option>
      </login-module>
    </authentication>
  </application-policy>

This has worked for me locally, but as I describe it, I feel that it is a bit odd having a dependency between the server configuration and specific files in a deployed application; even though their absence doesn’t seem to cause a problem. I think I might move those into the folder along with login-config.xml

I also believe that these could be just as easily be the default files JBoss expects by not specifying the above module-option elements.

All this done…

It didn’t work!

As soon as I tried to access a protected resource, I got a 404 error trying to locate the authentication controller actions I have in my application!

I couldn’t find a clear reference to this problem, but the following entry on the struts issues dashboard -
Action’s can’t be used for web.xml declarative security URL’s certainly describes the problem and also provided me with a fudge solution.

I edited my web.xml to point at a jsp:

    <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>/login_redirect.jsp</form-login-page>
            <form-error-page>/login_redirect.jsp?success=false</form-error-page>
        </form-login-config>
    </login-config>

and added a login_redirect.jsp:

   <%
        if ("false".equals(request.getParameter("success"))) {
            response.sendRedirect( request.getContextPath() + "/auth/failed" );
        } else {
            response.sendRedirect( request.getContextPath() + "/auth/login" );
        }
    %>

Now it works!

Comments
No Comments »
Categories
development
Tags
grails, jaas, jboss, jetty, security
Comments rss Comments rss
Trackback Trackback

Deplyoing a Grails application to JBoss

Ian | October 17, 2008

So it seems that every month or so I am able to blow the dust off my little Groovy on Grails project and progress it a little. A little frustrating, since the elapsed time of this belies the gains in using grails.

I have a working application. It has a few rough edges, but for all intents and purposes, it’s there. I just needed to see if creating war and deploying to the target environment, JBoss.

Surely it can’t be as simple as…
C:\local\groovy\my_app> grails war

No, it isn’t… But nearly!

Deploying into JBoss, the problem I hit was down to log4j and the jar within the deployed grails application conflicting with the one in JBoss.

Obviously this has all been covered before and a few alternatives are offered on the grails faq.
Q: I’m getting errors when deploying on JBoss 4.0.x What do I do?

First off I had to scope the application classloader. To do this for a war, create a file called jboss-web.xml with content like the following:

<jboss-web>
    <class-loading java2ClassLoadingCompliance = "false">
        <loader-repository>
            my_app:loader=my_app-0.1.war
            <loader-repository-config>java2ParentDelegation=false</loader-repository-config>
        </loader-repository>
    </class-loading>
</jboss-web>

and place it in the web-app\WEB-INF folder.

This still isn’t quite enough to get it to work though, since the log4j.properties file used by JBoss still results in a conflict of interest.

Luckily enough I was able to take the preferred solution of renaming JBoss’ log4j.xml to jboss-log4j.xml and editing the jboss-service.xml file such that the ConfigurationURL of org.jboss.logging.Log4JService points to the renamed file.

Et voila!

Comments
1 Comment »
Categories
development
Tags
deploy, grails, jboss
Comments rss Comments rss
Trackback Trackback

Groovy on Grails and my “Test First” impasse

Ian | September 4, 2008

I’ve hit what would be a test first impasse (if I had tried to write my test first). So in an attempt to leave it alone, I’ll record where I got to and the resources that I think nearly got me to a solution…

I have a domain object for which I want to return a filtered set. I know that this can be done as a closure to the list method of hibernate criteria and having figured out how to mock a closure I can assert that a filter has indeed been applied.

 def criteria = Customer.createCriteria()
 items = criteria.list(params) {
   or {
     ilike ('surname', "%${params.filter}%")
     ilike ('forename', "%${params.filter}%")
     ilike ('emailAddress', "%${params.filter}%")
   }
 }
---
def customerCriteria = new MockFor(org.hibernate.Criteria)
customerCriteria.demand.list { Map params, Closure cls -> testItems }
Customer.metaClass.static.createCriteria = { org.hibernate.Criteria }

But how can I assert that the filter closure contains/does what I want?
Having mocked the closure call, I now want to define what it is supposed to do in my unit test.

I just can’t figure out how and I have started delving much deeper into how closures work than I originally wanted to. Unfortunately, I don’t seem to get any further than the MetaClass, where everything is still a little abstract. There must be some representation of the code to be run/resolved in there somewhere!?

I’ve poured over the hierarchy for package groovy.lang and pages on Closures and the ExpandoMetaClass - GroovyObject Methods.

Kick started by Fun with Groovy and the Reflection API and definitely helped by What methods does my Groovy/Grails class have? I distilled my problem to a script and proceeded to dump anything and everything I could think of or come across…

class MyClassUnderTest {

  def foo() { return "foo" }
  def bar() { return "bar" }
  def ray() { return "ray" }

  def someMethod(Closure val) {

      println("Closure:")
      println(val.dump())
      println("-----------------------------------------------------------------")
      println("My Closure: ")
      println(val.getMyClosure().dump())
      println("-----------------------------------------------------------------")
      println("Meta Class: ")
      println(val.getMyClosure().metaClass.dump())
      println("-----------------------------------------------------------------")
      println("My Meta Class: ")
      println(val.getMyClosure().metaClass.myMetaClass.dump())
      println("-----------------------------------------------------------------")
      println("My Meta Class Methods Index: ")
      println(val.getMyClosure().metaClass.myMetaClass.metaMethodIndex.table*.name.sort().unique() )
      println("-----------------------------------------------------------------")
      println(val.getMyClosure().metaClass.inheritedMetaMethods*.name.sort().unique())
      println(val.getMyClosure().metaClass.methods*.name.sort().unique())
      println("-----------------------------------------------------------------")
      println(val.getMyClosure().metaClass.theClass.dump())
      println("-----------------------------------------------------------------")
      println("Constructors:")
      val.getMyClosure().metaClass.theClass.declaredConstructors.each { println it.toGenericString() }
      println("-----------------------------------------------------------------")
      println("Methods:")
      val.getMyClosure().metaClass.theClass.declaredMethods.each { println it.toGenericString() }
      println("-----------------------------------------------------------------")

      return 'result!'
  }

}

def cut = new MyClassUnderTest()
def myClosure = {
    foo ('valueOne')
    bar ('valueTwo')
    ray ('valueThree')
    'valueFour'
}
cut.someMethod { myClosure }

I thought I might have struck lucky when came across a post by Danno Ferrin who had learned more than he wanted to know about groovy.lang.Closure. This cleared up a great deal about scope and lead me to a post by Guillaume Laforge on knowing which variables are bound or not in a Groovy script.

Unfortunately the actual contents of the closure still allude me, but I’ve got work to do and this has had far more of my time than I can justify!

Comments
No Comments »
Categories
development
Tags
grails, groovy, hibernate, mock, testing
Comments rss Comments rss
Trackback Trackback

Grails Unit Testing: How to mock a closure

Ian | August 29, 2008

I have found numerous resources on testing in grails, unit testing and Using MockFor and StubFor in groovy. However, given that closures are one of the key features of groovy, I found very little on how to accommodate them in testing.

The following is a simple controller with a list action that returns a set of Customer domain objects from a database and this action applies some simple filter criteria (thanks to this post I came across):

   def list = {
        def items

        if(!params.max) params.max = 10
        if(!params.sort) params.sort = "lastUpdated"
        if(!params.order) params.order= "desc"
        if (params?.filter) {
            def criteria = Customer.createCriteria()
            items = criteria.list(params) {
                or {
                        ilike ('surname', "%${params.filter}%")
                        ilike ('forename', "%${params.filter}%")
                        ilike ('emailAddress', "%${params.filter}%")
                }
            }
        }
        else {
            items = Customer.list (params)
        }

        render (view: 'list', model: [ customerList: items, filter:params.filter ], params: params)
    }

This action uses the Hibernate Criteria Builder to construct the query.

When unit testing Grails does not inject any of the dynamic methods and so these must be provided for. For this I covered the dynamic controller methods in the set up and tear down operations (thanks wholly to Glen Smith’s MockFor(March): Unit Testing Grails Controllers…

    def redirectParams
    def renderParams
    def params

    /** Setup metaclass fixtures for mocking. */
    void setUp() {

        params = [ : ]
        CustomerController.metaClass.getParams = { -> params }

        redirectParams = [ : ]
        CustomerController.metaClass.redirect = { Map args -> redirectParams = args  }

        renderParams= [ : ]
        CustomerController.metaClass.render = { Map args -> renderParams = args  }

    } 

    /** Remove metaclass fixtures for mocking. */
    void tearDown() {
        def remove = GroovySystem.metaClassRegistry.&removeMetaClass
        remove CustomerController
    }

The dynamic methods for the domain class I covered in the test where they were used.

    void testNoFilterReturnsList() {

        def testItems = [ 'x', 'y', 'z' ]

        params['filter'] = null ;

        // mock the static list and count methods
        Customer.metaClass.static.list = { Map params -> testItems } 

        CustomerController cc = new CustomerController()
        cc.list()

        assertNull renderParams.model.filter
        assertEquals testItems, renderParams.model.customerList

    }

This could hardly be simpler and is covered in much more detail elsewhere. Where I ran into difficulty was testing the the criteria was applied.

I wanted to provide a mock object for the org.hibernate.Criteria object returned for the domain.
def customerCriteria = new MockFor(org.hibernate.Criteria)
Defining expectations on the mock object is straight forward too, just demand it!
customerCriteria.demand.list { -> testItems }
Except that what ever I seemed to try would not match the signature of the call to list that I was trying to do in the filter test above.

Despite being a little elusive, the answer was simple enough. The closure defining the search criteria is a parameter to the call. There must be a list method declared with a signature along the lines of
def list (Map params, Closure criteria)(At least, that’s what I had to do in a test class to mimic that results I was seeing.)

So, to define a demand to match that… well, just treat it as such.

    void testFilterAppliedToCriteria() {

        def testItems = [ 'x', 'y', 'z' ]

        params['filter'] = 'search on something' ;

        def customerCriteria = new MockFor(org.hibernate.Criteria)
        customerCriteria.demand.list { Map params, Closure cls -> testItems }
        Customer.metaClass.static.createCriteria = { org.hibernate.Criteria }
        customerCriteria.use{
        	CustomerController cc = new CustomerController()
        	cc.list()

        	assertEquals params.filter, renderParams.model.filter
        	assertEquals testItems, renderParams.model.customerList
        }
    }

I continue to stumble through, though I’m becoming more convinced that I don’t know what I am doing.

Comments
4 Comments »
Categories
development
Tags
closures, grails, groovy, hibernate, testing
Comments rss Comments rss
Trackback Trackback

Grails ClassCastException for Application

Ian | August 21, 2008

Having persevered with mapping my existing database in grails, it actually made for much cleaner domain objects.

I never much liked when hibernate started creeping out of configuration and into the code via Java annotations, so on the same score, it was cathartic to remove the database aware gorm mappings from my domain classes.

Adding the hibernate configuration was straight forward and clean and tucked away in the conf/hibernate directory; an hibernate.cfg.xml file listing the mapping resources and an hbm.xml resource file for each entity.

All was going swimmingly until I was adding my last domain class; modelling an Application.

As soon as I wanted to “show” a particular Application I was getting a ClassCastException.

It would appear that I’m not the first to hit this, so luckily I didn’t have waste too much time trying to figure out why:

application/create throws java.lang.ClassCastException: Application cannot be cast to javax.servlet.ServletContext

Apparently…

there is a variable in the GSP binding called ‘application’ that is the ServletContext this gets overridden when you return the model from the controller

The bug is on create, but I guess as I am coming from the legacy database angle, I didn’t have to “create” before I tried to “show”.

Mmm.

Comments
No Comments »
Categories
development
Tags
domain, gorm, grails, hibernate, java
Comments rss Comments rss
Trackback Trackback

« Previous Entries

Author

Ian Robinson is a relatively agile software engineer interested in things both sides of the object relational divide and beyond.

Categories

  • development (37)
  • miscellaneous (28)
  • music (7)
  • software (19)

What I'm Doing...

  • @noelfielding11 why are you in watching telly!? in reply to noelfielding11 2010-04-16
  • What was so good about Nick Drake? These "artists" are covering, music is spot on but no effect at all. Totally lacking the goose pimples. 2010-04-16
  • Some Ginger bloke's on telly covering Nick Drake in a mediocre style. 2010-04-16
  • More updates...

Posting tweet...

Powered by Twitter Tools.

Blogroll

  • Dan North
  • Dave Astels
  • Dave Wood
  • eirikso.com
  • Matt Raible
  • Object Mentor Blog
  • The Ancient Art of Programming
  • The Wisdom of Ganesh

Tags

active-mq architecture bauhaus css db eclipse esb festivals freesat gorm grails groovy hd hibernate htpc java jboss jms junit links mce media center mini music oracle osgi patterns pirsig plugins satellite soa software spring sql struts2 testing themes tools tv vmc web wordpress xml xpath xslt
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox