Tuesday, March 02, 2010

Adding Security to EJB

Alright let's take a quick look at the HelloBean.java file with security annotations:


package com.blogger.ramen;

import javax.ejb.Stateless;
import javax.annotation.security.RolesAllowed;
import javax.annotation.security.DeclareRoles;

@Stateless(name="HelloBean")
@DeclareRoles("SecureUser")
public class HelloBean implements HelloRemote {

@RolesAllowed("SecureUser")
public String sayHello() {
return "Hello from EJB!";
}

}


As you can see I've added the DeclareRoles and RolesAllowed annotations. The EJB container will read the meta-data in the class see the annotations and enforce the security described in them. This happens each time you call the method since it is Stateless.

So the next question is how does the container know you belong to the SecureUser role? Because the security mappings in your sun-ejb-jar.xml file. Here's what you need to add:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 EJB 3.0//EN" "http://www.sun.com/software/appserver/dtds/sun-ejb-jar_3_0-0.dtd">
<sun-ejb-jar>
<enterprise-beans>
<ejb>
<ejb-name>HelloBean</ejb-name>
<jndi-name>ejb/Helloness/HelloThere</jndi-name>
<ior-security-config>
<as-context>
<auth-method>USERNAME_PASSWORD</auth-method>
<realm>OurDBRealm</realm>
<required>true</required>
</as-context>
</ior-security-config>
</ejb>
</enterprise-beans>
</sun-ejb-jar>


As you can see the <ior-security-config> and all of it's friends to add a realm to our EJB. Our realm being OurDBRealm that we already setup using the JDBCRealm method that was given earlier. We need to add one more thing to that file, our security mapping, this will map something that will match an entry in the JDBCRealm with the annotation we've giving here. We add this snippit right after the <sun-ejb-jar> element.


<security-role-mapping>
<role-name>SecureUser</role-name>
<group-name>SUSER</group-name>
</security-role-mapping>


Deploy your EJB and rerun your client. You should get the default login prompt that's built into Glassfish. Login with the information you've stored in the database and you should see results. Viola! Secure EJB. Of course, if you give bad login information then you will get an exception. At any rate this is a pretty cut and dry use of secure EJBs. We'll look at how to provide your own login dialog and how to catch exceptions on login.

Cheers!

No comments: