Saturday, May 30, 2009

Authentication and authorization with JBoss security domains

Authentication and authorization comprise the fundamentals of security, and as such, they are important aspects of almost any application. Having in mind that security is such a frequent issue, it comes as no surprise that many people have devised many different ways of carrying it out, and so we now have literally countless options to choose from. If you are going to deploy your application to JBoss AS, you can get the basic authentication and authorization set up in virtually no time. To carry out these tasks, JBoss uses the notion of a security domain overlaying the standard JAAS (Java Authentication and Authorization Service).

Configuring the data source (*-ds.xml)



In order to set up a security domain for your app to use, you first need to set up a data source against which you will check the user's credentials. More often than not, your source of data will be a relational database. JBoss conveniently provides templates for many populars databases, so setting up a data source should be a breeze. These templates can be found under
<JBoss home>/docs/examples/jca1. Notice that all the filenames in this directory end with "-ds". This is the convention for naming the data source configuration files.

Let's assume we want to use MySQL. All we need to do, is make a copy of mysql-ds.xml, edit it to reflect our situation, and put it into the deployment directory. Editing this file is pretty straight forward, you decide on a JNDI name you want your data source bound to (I'll use MySqlDS), input your connection URL, username and password. There's really no need to change the driver class.

When this is done, you place this file under <JBoss home>/server/<profile name>/deploy2. That's it for this step.

Configuring a security domain (login-config.xml)



Next, you need to edit JBoss' login-config.xml file (found under<JBoss home>/server/<profile name>/conf). There are other ways to set up the security domain, but is by far the easiest. All you need to do here is nest a snippet similar to the following inside the policy element.
<!-- My custom security domain -->
<application-policy name="custom-domain">
<authentication>
<login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule"
flag = "required">
<module-option name="dsJndiName">java:/MySqlDS</module-option>
<module-option name="principalsQuery">SELECT password FROM USERS WHERE username=?</module-option>
<module-option name="rolesQuery">SELECT role, 'Roles' FROM ROLES WHERE username=?</module-option>
</login-module>
</authentication>
</application-policy>

Pay attention that dsJndiName attribute value must be identical to the jndi-name you chose in your mysql-ds.xml, preceded by java:/.
principalsQuery is the SQL query used to retrieve the user's password which, of course, has to match the one entered, and rolesQuery is the SQL query used to retrieve the roles associated with the user (leave the 'Roles' part as it is, it's not clear from the JBoss' documentation what purpose it has).

Our security domain is now ready. The next thing to do would be to instruct our application to use it.

Declaring page-level security (web.xml)



Presume we have a web.xml with the following security constraints configured:
<security-constraint>
<web-resource-collection>
<web-resource-name>Secure Resource</web-resource-name>
<url-pattern>/secure/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>registereduser</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.html</form-login-page>
<form-error-page>/error.html</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>registereduser</role-name>
</security-role>
<resource-ref>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

This tells our app server that only the users with the registereduser role can access the resources under /secure/ (this is the job of the url-pattern element). It also tells we are going to use a form to perform authentication (notice the auth-method element), and that this form is found on the page named login.html (the form-login-page element). The request gets redirected to the page specified under form-error-page in case the login failed. You can also use BASIC authentication method (just place BASIC instead of FORM inside auth-method element) . This will cause the browser to display a simple pop-up dialog that asks for username and password when a secured resource is requested. You don't need form-login-config for this approach.

Creating a login form (j_security_check)



The login page is obviously required to contain a login form. This form must specify j_security_check as it's action, and it also must have a username input field named j_username and a password input field named j_password.

This is how it might look like in it's simplest form:
<form name="loginForm" method="post" action="j_security_check">
<table>
<tr>
<td>User Name:</td>
<td><input type="text" name="j_username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="j_password"></td>
</tr>
<tr colspan="2">
<td><input type="submit" value="login"></td>
</tr>
</table>
</form>

Binding the application to a security domain (jboss-web.xml)


So, web.xml dictates the security constraints, but there is no mention of how these constraints will be carried out. This is the job of the jboss-web.xml config file (which is, of course, JBoss specific). It is in this file where we specify what security domain we want to use for authentication. Here's how it should look like in this case:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
<security-domain>java:/jaas/custom-domain</security-domain>
<resource-ref>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<jndi-name>java:/MySqlDS</jndi-name>
</resource-ref>
</jboss-web>

Pay attention to the security-domain element. It is necessary to prefix the domain name with java:/jaas/, and the name its self must be exactly the same as the one you typed into the login-config.xml file.

That's it! Now every unauthenticated request to the secure resource (under /secure/, as specified in web.xml) will first be redirected to the login page (or, in case of BASIC auth-method, a login pop-up will displayed). If the user logs in successfully and is authorized i.e. associated with any of the required roles (only registereduser in our case), the requested resource will be displayed. Otherwise, if the login attempt fails, or the user doesn't have any of the required roles, the error page will be displayed instead. Users stay logged in for the entire duration of the session.

Method-level security (isUserInRole)



Declarative security in web.xml is enough if you only need page-level security (based on the URL pattern), but if you need to dynamically check user's role on a method level, you can do so by calling isUserInRole("registereduser") on a request object (acquired from the ExtrnalContext). Here's a short example of a method doing this:

public Boolean isRegisteredUser() {
HttpServletRequest httpServletRequest =
(HttpServletRequest) FacesContext.getCurrentInstance() //first get the current FacesContext instance
.getExternalContext() //than get the ExternalContext
.getRequest(); //get the underlying request
// return True if this request was issued by a user with a "registereduser" role
return httpServletRequest.isUserInRole("registereduser");
}

You can get the username in pretty much the same way, just call getRemoteUser() instead of isUserInRole("...").

Notes:
1 <JBoss home> refers to your JBoss installation directory (the same as JBOSS_HOME environmental variable).
2 <profile name> refers to your deployment profile name (you will probably be using default).

8 comments:

  1. I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards

    ReplyDelete
  2. Thanks, I'm glad to hear you found my blog useful :)
    Feel free to suggest a topic if you wish.

    ReplyDelete
  3. hello, what's your JBoss version? Did you tried in JBoss 5.1ga? Thanks Joyce

    ReplyDelete
  4. Sorry for not replying...
    I can't remember if this was on 5.0 or 5.1, but I guess the differences shouldn't be too big (if any). I'll give it a shot on JBoss AS 5.1 and update the post if there's any significant change.
    Also, I'll probably post an update on JBoss AS 6 at some point.

    Thanks for the visit :)

    ReplyDelete
  5. Hi
    I've used your post to set this up on Jboss 4.2.1 to secure jmx-console. I'm getting a prompt for a login when I access http://localhost:8081/jmx-console but it doesn't matter if I put in valid credentials or invalid ones I still get just a blank page returned.

    Any ideas what I'm doing wrong please?

    ReplyDelete
  6. Hmmm, haven't really tried this with JBoss 4.x. Is there anything useful in the logs?

    ReplyDelete
  7. this is very helpful..keep it up

    ReplyDelete