Tuesday, April 8, 2008

J2EE/JBoss webapp authentication for the impatient

I just went through tons of articles and documents and howtos to implement a simple web application authorization, so I thought I should save the effort for other impatient people like me. Read through the extensive JBoss documentation for detailed specifications and such, if you're in the mood.

Basic concept:
I want a set of pages to require username-password authentication.

* The username-password combination should be stored in a database
* I am not concerned about EJB security right now, just the webapp
* I don't want to write my own code for this
* I'm using MySQL



Secure the protected URLs in your web.xml. Put the following lines into the web.xml file in your WEB-INF directory:

Secure Content



The Restricted Zone

The role required to access restricted content

This means that any page that's within the /restricted URL will get protected, the authentication mechanism will be BASIC (ugly popup screen which requests the credentials), and anyone who is in the AuthorizedUser role will be able to see it. See the login-config documentation about how to configure a JSP page with form based authentication instead of this.


Make the database accessible for JBoss. Drop the mysql client jar into your JBoss domain's lib folder, and customize the mysql-ds.xml file, which you can find in the JBoss docs/examples/jca directory, using your own database's URL, login, etc. Drop the modified file into your JBoss domain's deploy folder. This is a great feature for datasource configuration!


Create a Users and Roles table in mysql, with the following structure:
- Users should have an username and password field
- Roles table should have a username field, and a roles and role_group field.


Configure JBoss to use your new table for the JBoss-provided DatabaseServerLoginModule. This is configured in your JBoss domain's conf folder, in the login-config.xml file. Basically you need to provide the datasource, and the SQL selects you would use to return these values.


select passwd from Users where username=?

select role, role_group from Roles where username=?

Make sure your Datasource name matches the one you configured in the Mysql DS xml file.


Connect your webapp's J2EE standard authorization settings with the JBoss-specific provider implementation. The place for this is the jboss-web.xml file in your webapp's WEB-INF directory.


This will make JBoss look up the myOwnDomain settings in the login-config.xml file, which will use the JDBC based module to query your database for authentication.

It is quite straight forward to use hashed passwords as well, this is documented in the DatabaseServerLoginModule provider's documentation. Enjoy!

No comments: