Securing a Grails Application with Acegi Security (Fadi Shami)

, , February 25th, 2008

Groovy is a powerful, high level language for the Java platform which compiles down to Java bytecode. It is similar in concept to Ruby or Python, however it is tightly integrated with the Java platform. This allows you to utilize a powerful and concise coding syntax while at the same time allowing you to stay on the JVM and protect your investment in the existing Java platform and surrounding libraries.

Grails is a full stack framework implemented in Groovy. Grails attempts to solve many pieces of the web development puzzle through both the Grails core technology and associated plug-ins. Out-of-the-box capabilities include:

  • An Object/Relational Mapping (ORM) layer built on Hibernate
  • An expressive view technology called Groovy Server Pages (GSP)
  • A controller layer built on Spring MVC
  • A command line scripting environment built on Gant, a Groovy-based version of Ant
  • An embedded Jetty container which is configured for on-the-fly reloading of resources
  • Dependency injection via the built-in Spring container
  • Support for internationalization (i18n) built through Spring’s MessageSource API
  • A transactional service layer which utilizes Spring transaction management
  • Extensive use of Domain-Specific Languages (DSLs)

Acegi Security is a powerful, flexible security solution for enterprise software, with a particular emphasis on applications that use Spring. Acegi provides comprehensive authentication, authorization, instance-based access control, channel security and human user detection capabilities.

This article assumes that you have completed the Grails tutorial found in Getting Started with Grails by Jason Rudolph, and have implemented the RaceTrack sample application. The grails-acegi plugin will then be integrated with RaceTrack to provide security for your application. Utilizing the grails-acegi plugin avoids the overhead of having to implement Grails interceptors in your application, provides more flexibility than interceptors, and also saves reimplementing your own security system by leveraging Acegi.

Setting up the RaceTrack sample application

First, you will need to download Grails 1.0, the grails-acegi-0.2 plugin and Java SE JDK 5.0 or greater.

At this point, you are assumed to have implemented most of the RaceTrack application as described in Getting Started with Grails. However, you do not have to complete the entire tutorial in order to test the grails-acegi plugin – all which is required are the domain classes and controllers, and scaffolding of the controllers is good enough for testing.

Figure 1 - Directory structure after creating the racetrack application Figure 1 – Directory structure after creating the racetrack application

Your RaceTrack application directory should look like the one shown in Figure 1 above. Now, open up the \grails-app\domain folder:

Figure 2 - domain classes directory Figure 2 – domain classes directory

As you can see in Figure 2, the “domain” directory only contains 2 domain classes: Race and Registration. Now, open up the \grails-app\controllers folder and confirm that it has a controller for each domain class as shown in Figure 3 below:

Figure 3 - Controllers directory Figure 3 – Controllers directory

These controllers can be empty, scaffold controllers, e.g.:

  class RaceController { def scaffold = Race }

  class RegistrationController { def scaffold = Registration }

This is sufficient to get the application up and running. After you start the RaceTrack application, you should be able to see the 2 controllers you created in the controller list as in Figure 4 below:

Figure 4 - Index page before Grails-Acegi Plugin Figure 4 – Index page before Grails-Acegi Plugin

Installing the Grails Acegi plugin

Next is the installation of the grails-acegi plugin so that the RaceTrack take advantage of the role-based security this plugin provides. In the command prompt , navigate to “racetrack” directory and run this command:

grails install-plugin [path-to]/grails-acegi-0.2.zip

This command creates a plugin directory under the “racetrack” directory as in Figure 5 below:

Figure 5 - plugins directory created after installing the plugin Figure 5 – plugins directory created after installing the plugin

Creating the Acegi Security components

The next step is to create domain classes that will represent User Accounts and Roles. To begin this process, run the following command:

grails create-auth-domains AuthUser Role

This will create two domain classes (AuthUser and Role), set up the AcegiConfig class, and create the Login and Logout controllers. The AuthUser domain class will represent your users, so for every new user will create a new record in the Auth_User table. The Role domain class will represent security roles that every user is allowed to have – Roles will be assigned to AuthUsers. Both of these classes are shown in Figure 6 below.

The AcegiConfig class (Figure 7) defines the security configuration for your application. It contains the names of the user domain class (in this case AuthUser) and the role domain class (in this case Role), whether to use dynamic vs. static secured urls, and how to setup email alerts (turns them off or on).

Figure 6 - AuthUser.groovy, Role.groovy and Requestmap.groovy (used in AcegiConfig) Figure 6 – AuthUser.groovy, Role.groovy and Requestmap.groovy (used in AcegiConfig)

Figure 7 - AcegiConfig.groovy created Figure 7 – AcegiConfig.groovy created

In order to create new AuthUsers, create new Roles and assign Roles to AuthUsers, we will have to run two commands. One will generate the CRUD controls for domains:

grails generate-manager

and the second to generate registration for controllers and domains:

grails generate-registration

These commands give the user the ability to register and create their username and password, and the default security role will be assigned to that user. The set of controllers generated can be seen in Figure 8 below:

Figure 8 - CRUD controllers (Login and Logout controllers are created when the Auth and Role domains are created)

Figure 8 – CRUD controllers (Login and Logout controllers are created when the Auth and Role domains are created)

Figure 9 - Controllers available after grails-acegi-plugin installation

Figure 9 – Controllers available after grails-acegi-plugin installation

Go to the RaceTrack homepage – it should look similar to Figure 9 above.

Configuring Acegi Security to secure the application

We will now create a User role and a Manager role – to do this, first click on RoleController, and then enter a Role Name of ‘user’ and some sort of role description (Figure 10). Note that the RoleController will take care of converting ‘user’ to ‘ROLE_USER’, which is what it is called in the database and by Acegi’s configuration. Repeat the same steps to create a manager role.

Figure 10 - Creating a user role Figure 10 – Creating a user role

Go back to the home page, and click on UserController. Now, create a user with the ‘user’ role, and another user with a ‘manager’ role, as in Figure 11 below:

Figure 11 - Create a standard user, enable the account and assign the 'user' role Figure 11 – Create a standard user, enable the account and assign the ‘user’ role

Our Roles and Users are now sufficiently configured, so the next step is securing the RaceTrack application. There are two ways to how you can secure your URLs: One is dynamically via RequestmapController, and the other is through editing the AcegiConfig.groovy file directly. The dynamic configuration is the recommended choice, so we will proceed with that.

Before we secure the application, we need to think about the access rules that should be present in the application. A manager is allowed read/write access to any page in the application, which means:

  • /race/*
  • /registration/*

A user is allowed read-only access to some of the pages, including:

  • /race/list/*
  • /race/show/*
  • /registration/list/*
  • /registration/show/*

These rules now need to be translated into entries in the Acegi request map using the RequestmapController. From the RaceTrack homepage, click on RequestmapController, and go to the ‘create a new requestmap’ page. In the URL field enter “/race/**”, and in the Role field enter “manager” (Figure 12) – this will create a rule which allows any user with the manager role to access all URLs under /race. Do the same thing for registration (URL: /registration/**).

Figure 12 - Manager access rules Figure 12 – Manager access rules

As a note, a good practice is to grant all user rights to the manager role as well. Next the access rules for the user role will be created — in the URL field enter “/race/list/**”, and in the Role field enter “user, manager” (Figure 13 - note that roles are separated with a comma). This will create an access rule which allows both users and managers to access the race list page. Note that you will needed to specify both roles — if you only assign this URL to the user role, it will override the previous rule for manager and will only allow the user role to access the page. Repeat the previous step for the rest of the rules defined previously – this will create all of the access rules for the race and registration pages.

Figure 13 - Creating rule for /race/list/** page - give access to users and managers Figure 13 – Creating rule for /race/list/** page – give access to users and managers

Testing

From the RaceTrack homepage, click on either RaceController or RegistrationController (the controllers for the views we secured). You will now notice that you have been automatically redirected to the Login page. If you first log in as a user with the manager role, notice that you will be able to view, create, update and delete anything on the race and registration pages.

Figure 14 - Logging in as a user Figure 14 – Logging in as a user

Return to the RaceTrack homepage and click on the LogoutController — this will invalidate your user session and log you out. Click on LoginController again, but this time log in as a user with the user role.If you then go to the /race/list subpage (either by going directly to http://localhost:8080/racetrack/race/list or by navigating through the controller interface), you should be able to see the race/list view (Figure 15).

Remember that the access rules allow only managers to create new records, and users can only read data through the List and Show views – this means that if you try to click on New Race (http://localhost:8080/racetrack/race/create) while logged in as a user with the user role, Acegi will prevent you from navigating to that page, which prevents creation of a new record.

How does this work? Recall that we granted access to /race/* to a manager, but only granted access to /race/list/* and /race/show/* to a user. When a user with the ‘user’ role attempts to access the /race/create page, Acegi looks at the set of roles for the user and sees that they only have the ‘user’ role – since our Request map said that the user must have the ‘manager’ role to be granted access to this page, permission to access the page is denied.

As a side note, in a real application you will probably want to display a better error page than the default one (Figure 16).

Figure 15 - Race List view

Figure 15 – Race List view

Figure 16 - Access denied error page Figure 16 – Access denied error page

Congratulations – you now have a fully secured instance of the RaceTrack application!

Fadi Shami, InfoQ

Tags: , ,

My First Impressions of Grails (Tyro Trader)

, , February 22nd, 2008

I’m embarrassed to say that I’ve become a “Java Guy”. It’s fine to know a language well, but when you become defined by a single language, you’ve given up learning. It’s a polite way of saying that you stopped caring. At different points in my life I’d try new languages, new tools and play around, just to learn. In fact, that was how I got interested in Java in the beginning - I was in school and I heard of this new “Java” thing which was only in version 0.6 or 0.7 but already it seemed pretty cool so I printed off the specs and got ahold of the alpha releases from sun and started hacking. What a hoot!

I’ve only done something like that a handful of times and in each case, real life work ground me down. The last time was when I got interested in AspectJ and Aspect Oriented Programming. It seemed very cool and I talked a lot about it with my co-workers and then made the mistake of pushing to get it adopted on a big project. Next thing I new, every bug and every question that arose in any one of a dozen different teams spread across three countries would arrive at my desk and I quickly grew to loathe the whole process. Now that I’m working independently, I’ve had a chance to look into a number of different toolkits and languages, but I never drifted too far from Java.

On a whim, I started playing with a language called Groovy and Grails which compile down to Java bytecode which was “safe” and smart as it let me use all the libraries I’ve already written, but wow, what an difference! To start, here’s what I had in mind for the application.

I want something which can centralize a lot of the swing trading related tasks that I perform regularly and I thought it would be interesting to place them all into a single webapplication. It would let me import all of the executions from Interactive Brokers into a database, define my trades with stoplosses, handle reporting and generate charts (all things I do now using a fat client I wrote in SWT a couple years back), but it would also display an updating list of the most active stocks on the exchanges, compare the different sectors, list some of my watchlists and gather together the different scans that I run during the week.

Over the years, I’ve written dozens of web apps and I’ve grown to hate them. So bloody tedious. If you want to add a page which does something slightly different like say search for trades within a certain date range, then you’ve got to code the new command, register the new command in three different configuration files so the servlet engine knows how to handle it, add new search methods to your DAO, write new SQL to retrieve the data and splatter it throughout your configuration files, handle errors and on and on. I grew to accept it, but I never liked it which is why I wrote my first application for trading as a fat, desktop application - I’d had it with web apps.

But Groovy on Grails is different. It’s founding principle is “Don’t Repeat Yourself” and it does it excellently. It takes some of the strongest features of Groovy and pushes them hard. The domain objects just declare their fields and their constraints and Grails maintains all of the database tables, the CRUD methods (Create, Retrieve, Update, Delete) and a boggling-array of retrieval methods. It also has the simplest way of adding new web services I’ve seen - you just add a new method (”Closure”, really) to a controller class and Grails will do all the wiring for rendering the page. For instance, my domain object “Executions” comes with list functionality by default, but I really want to list the Executions that haven’t been added to a trade, and I wanted to list the results. It wouldn’t be complicated to do using Struts or other frameworks, but it would be tedious and require changing a lot of files.

In Grails, it takes exactly two changes. I added one line to my gsp (”Groovy Server Page”) to link to the new search page:

    <g:link action="searchUnassigned">Search for Unassigned</g:link>

Then in the controller, I added a new “closure” matching this action:

def searchUnassigned = {
    render(view:'list',
        model:[exs: Execution.findAllByTradeIsNull()])
}

It builds a list of executions which do not have trades associated, and sends them to the list view. I didn’t even have to write any of the SQL, all the necessary information is in the function name and Grails is smart enough to handle it properly. And it works, first try!

I then went on to look at adding new Trades and found a line of code which really highlights why Groovy kicks so much ass over Java. The “saveTrade” method would have to extract all of the params from the request object, convert them to the correct object type, munge the order and pass it to the constructor, something like:

public void saveTrade(Request req, Response resp) {
try {
    Map<string,string> params = req.getHttpParameters();
    String symbol = (String)params.get("symbol");
    Date lastupdate = pstDateFormatter.parse((String)params.get("lastupdate"));
    double stoploss = Double.parseDouble((String)params.get("stoploss"));
    boolean isComplete = Boolean.parseBool((String)params.get("isComplete"));
} catch( Exception e ) {
    resp.redirect("error.jsp");
    return;
}
if( symbol == null || symbol.size()<> 6 ) {
    // invalid size
    resp.redirect("error.jsp");
    return;
}
// [...  more error checking ...]

Trade trade = new Trade(symbol, lastupdate, stoploss, isComplete);
if( !WebDAO.saveTrade(trade) ) {
    resp.redirect("error.jsp");
}

resp.put("trade", trade);
resp.redirect("show.jsp");
}

And that’s the short version without all the error checking (and no flames if the syntax isn’t quite correct - that should illustrate how hard it is to get this working properly). To make matters fun, all this stupid error checking has to be done everywhere that a trade is created. It’s bloody irritating and it’s hard to maintain. And this doesn’t even go into the depth of coding the freaking saveTrade() method, which is a pain in itself.

So how is this done in Groovy?

def save = {
def trade = new Trade(params)

if(!trade.hasErrors() && trade.save()) {
    flash.message = "Trade ${trade.id} created"
    redirect(action:show,id:trade.id)
}
else {
    render(view:'create',model:[trade:trade])
}
}

Because Groovy’s constructors take a map, you can just pass in the params map. Sweet, there’s a couple dozen lines shrunk down into one. And because the trade object already has a save() method built for you, no need to code it up. What’s especially interesting is that this reduced method (closure, actually) has better error handling than the huge Java method. And all of that work trying to check for valid data in the Java code? Simple, Grails lets you declare that in one place - in the Trade class where it belongs. Here’s what it looks like:

static constraints = {
symbol(maxLength:6,blank:false)
stoploss(min:1.00d, max:100000.00d)
}

How sweet is that? You do it in one place in a simple, declarative fashion without all the messy code and if you ever violate one of these constraints, it even generates friendly error messages telling you what went wrong! It’s just brilliant! It’s exactly how you want to write it, simple and clear and because it’s so simple and clear (and not replicated everywhere) it’s much less likely to have bugs.

AJAX and Plugins

AJAX is one of the Big Things in web sites these days. It’s the technology which allows Google Maps and GMail to act like desktop applications. It decomposes the page into tiny elements and uses JavaScript and custom web services to populate each element separately. That way you can read mail and refresh only the current message, and you can get notifications when new messages arrive without redrawing the entire page, and it lets you scroll Google Maps as if you had downloaded the entire atlas yet still lets pages load quickly. There are a lot of nifty tools to let you develop these applications without having to hand-code all of the JavaScript (like Google’s GWT) and Grails is no exception.

Grails isn’t wedded to a single technology either and lets you pick and choose, but this can lead to potential problems. One of the big failings that I’ve found with these large frameworks is how poorly integrated they are with other tools. Sure you can use JSF or portlets but can you make them work with anything else? Grails has dealt with this issue through the use of “plugins”. The Grails home stores a list of plugins that are vetted to work with the framework and you can automatically download them and all of the associated library versions. There are a lot of cool features of plugins (like integration with the Grails version) but I’ll just show you how easy they are to use.

I had always wanted to have a UI which would show a calendar-based view of my trades, much like Dave’s excellent Stocktickr journal tool but I couldn’t find a way to cram it into my SWT, Swing or AWT tools. But in the web world, MIT has a free tool called SIMILE | Timeline which does just what I want using a goop-load of JavaScript and XML. Fortunately, there is a plugin (”richui”) which simplifies most of the process. In your GSP, you add the tag:

<richui:timeline
    style="border: 1px; height: 450px; width: 100%;"
    startDate="${new Date() - 20}"
    datasource="http://localhost:8080/StockMonitor/reporting/timeEvents" />

and then in the ReportingController, create the “timeEvents” method (really a Closure, but that’s a discussion for another time) which returns the XML data to display. Again, Groovy comes to our aid with the Builder tools, letting us build the XML in a language-friendly fashion.

For my tool, I wanted to query all trades between a user-supplied interval and show my winners in green and losers in red, with incomplete trades marked with an icon and their symbol name:

def timeEvents = {
initParams(params)
   def trades = Trade.findAllByLastupdateBetween(
                        params.startDate, params.endDate)

render(contentType: "text/xml") {
    data() {
       trades.each() { trade ->
         if( trade.isComplete) {
            event('start':dateForm.format(trade.start()),
                  'end':dateForm.format(trade.end()),
                  'title': rForm.format(trade.R())+ "R",
                  )
         } else {
            event('start': dateForm.format(trade.start()),
                  'end':dateForm.format(new Date()),
                  'title': "${trade.symbol}",
                  'color': "blue"
                  )
          }
      }
    }

To non-coders it may look like a mess, but it’s pretty simple. It starts by fetching all matching trades, then builds the XML structure. The event() method declares an node with the attributes “start”, “end”, and “title”. And if you want to change from XML to JSON or other protocols, you just change the content type of the render() method and everything else remains the same!

The result is this:

(Perceptive readers may notice one reason why I’m trading very small size and why I’m not totally stoked with my performance in the market right now.)

So that’s one of the things I’ve been doing in my spare time. I also wrote a Groovy-based API for QuoteTracker which I’m cleaning up and bug testing with the hopes of writing a simple ATS that leverages the charting, studies and alert system of QuoteTracker (this was by far the hardest bit of code that I encountered on my last attempt and I’m trying to learn from my mistakes). I hope to expand this over the coming months and see if I can’t resurrect some day trading ideas.

Tyro Trader (Original)

Tags: , ,

eWeek: Groovy Climbing Programmer Ranks (Darryl Taft)

, , , , February 22nd, 2008

Groovy is what Java would look like if it had been invented in the 21st century, said one developer.

RESTON, Va. – Groovy is getting its groove on and is moving up the charts.

At the 2G Groovy/Grails Experience conference here, Scott Davis, author of several books on Groovy, Java and editor in chief of aboutGroovy.com, said the Groovy language is moving fast up the charts of languages favored by developers.

Groovy now ranks 31 on the list of top programming languages, according to Davis and data from the TIOBE Software BV. Groovy had cracked the top 100 six months ago, moving from 103 to 52, and jumped to its current position in a January poll. Java remains the most popular programming language today, followed by the C language, Visual Basic, PHP, C++, Perl, Python and C#. Fortan, ColdFusion and ActionScript, also rank higher than Groovy.

Groovy, based on Java, is a dynamic language that runs on the Java Virtual Machine, or JVM. James Strachan, the creator of Groovy, first discussed the language on his blog in 2003, but early versions of the language did not appear until 2004, and a 1.0 release came out in January of 2007.

“Groovy is what Java would look like if it had been invented in the 21st century,” Davis said, noting that Groovy is “the next generation of Java.”

Davis, who delivered the opening keynote for the Groovy/Grails Experience, said people often ask whether Groovy will be a replacement for Java.

“It’s like saying do you think icing will ever replace cake,” Davis said. “It’s the same kind of relationship here. What we do is put a nice Groovy facade over Java things like icing over a cake.”

Davis said there is a symbiotic relationship between Groovy and Java. And that makes all the difference between Groovy and other dynamic languages that run on the JVM, he said.

“There’s JRuby out there,” Davis said. JRuby is an implementation of Ruby that runs on the JVM.

“JRuby is a great dynamic language if you already know Ruby,” Davis said. “And Jython is a great dynamic language if you know Python. But when you run JRuby on the JVM you’ve got this weird kind of disconnect.”

However, “Groovy is targeted at us: Java developers,” Davis said. “It is for us by us.”

Moreover, “because of the linguistic similarities between Java and Groovy it’s painless for developers to switch between Java and Groovy,” Davis said.

To implement Groovy, all a Java developer needs to do is “add a single JAR (Java Archive file) to your classpath; you don’t have to rewrite a single line of code,” Davis said.

Groovy runs on Java 1.4, 1.5 or 1.6.

Meanwhile, Grails is a Web application framework based on Groovy that is patterned after Ruby on Rails. Grails co-creator Graeme Rocher said Grails 1.0 shipped earlier this month. Rocher is the project lead for the open-source Grails project.

“Grails is a fully integrated, modern Java Web application in a box,” Davis said.

Grails includes support for Asynchronous JavaScript and AJAX frameworks.

“The plug-in system is really where the strength of Grails comes from,” Davis said. “Grails is a simple core, but it’s infinitely extensible through its plug-in system.”

Salil Deshpande, a partner at Bay Partners, a venture capital firm, said, “what’s cool about Groovy is it’s basically a language that is very Ruby-like, but it’s a superset of Java.”

Further, Deshpande explained that because Groovy is based on Java then “enterprises can preserve their legacy investments in Java” to extend their development to a dynamic language or lightweight Web development framework such as Grails.

“For the six to nine million Java developers out there, it’s easier for these guys to go to Groovy and Grails instead of Ruby and Rails,” Deshpande said.

Indeed, Matthew Porter, founder of Contegix, a managed hosting firm, said Contegix went to Groovy and Grails for several reasons, including being able to use their existing skill set in enterprise Java.

Darryl Taft, eWEEK

Tags: , , , ,