Saturday, September 18, 2010

Grails and simple realm-based authentication

Today's post is brought to you by skamster from the #grails IRC channel on freenode and describes how to setup memory-realm-based authentication with Tomcat.

First, you will need to "install templates" if you haven't already. Next, you will need to edit your web.xml file located in src/templates/war and replace the old security constraint (towards the end of the file) with the following:

<security-constraint>
<web-resource-collection>
<web-resource-name>
web
</web-resource-name>
<!-- This would protect the entire site -->
<url-pattern>/*</url-pattern>

</web-resource-collection>
<auth-constraint>
<!-- Roles that have access -->
<role-name>testRole</role-name>
</auth-constraint>
</security-constraint>

<!-- BASIC authentication -->
<login-config>
<auth-method>BASIC</auth-method>
<realm-name> Example Basic Authentication </realm-name>
</login-config>

The above is telling Tomcat that you want require basic authentication for all URLs and what Roles have access. Next, you will need to add a user and role.

The final step is to create a script called "_Events.groovy" in your scripts directory for your project with the following:

eventConfigureTomcat = {tomcat ->
tomcat.addUser("testUser", "testpassword")
tomcat.addRole("testUser", "testRole")
}

This simply adds a user (testUser) with the role of "testRole" to the authentication realm for Tomcat.

That's it. Now you have simple realm-based authentication setup for your application. Enjoy!

No comments:

Post a Comment