Thursday, November 19, 2009

What's wrong with me?

Okay now a little bit of Java code to get into the mindset of using Glassfish.

What is wrong with this code?

File: SimpleMessageRemote.java


package com.blogspot.ramenboy.logintest;

import javax.ejb.Remote;

@Remote
public interface SimpleMessageRemote {

String sayWorld();

}


File: SimpleMessage.java


package com.blogspot.ramenboy.logintest;

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

@DeclareRoles("AUser")
@Stateless
public class SimpleMessage implements SimpleMessageRemote {

@RolesAllowed("AUser")
public String sayWorld() {
return "World!!";
}
}


File: Main.java


package logintest01;

import com.blogspot.ramenboy.logintest.SimpleMessageRemote;
import javax.swing.JOptionPane;
import javax.ejb.EJB;

public class Main {

@EJB
private static SimpleMessageRemote s;

public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hello... " + s.sayWorld());
}
}


The problem with this code is (we are assuming that all the XML descriptors are in order) that we are injecting an EJB that is protected. Now there is nothing wrong with injecting a protected EJB but we shouldn't do this in our Main method. Injecting secure EJBs should be done once we have established the user as belonging to the system.

Why?

If the user fails to login properly (mistyped something or what-have-you). The Injection fails and the end result is an unusable object. The object being the whole freaking program, since this is the main method.

Ergo, don't do this unless you are just writing a simple test. This isn't really production grade programming to inject secure beans all over the place. A failed injection will bring your application client to a grinding halt with a very confusing error.

No comments: