Wednesday, December 5, 2007

Secure EJB with stand alone client on Glassfish (part 2)

Wednesday, December 05, 2007 Posted by Andre Broers , 2 comments
In part 1 we created a sessionbean with authorization on the methods. In this exemple we get the same sessionbean but we add some progammatic logic in the method the make the authorization a bit more controllable. We add two functions to get the group info and one to get the current username.

For this example we use the same code from part 1. The only file we change is the one below:


[sourcecode language="java"]

package com.bekijkhet;
import javax.ejb.Stateless;
import javax.ejb.Remote;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
public class HelloBean implements Hello {
  @Resource SessionContext ctx;
  public String sayHellosuperuser() {
    return "sayHellosuperuser";
  public String sayHellousersuperuser() {
    return "sayHellousersuperuser";
  public String sayHellouser() {
    return "sayHellouser";
  public String sayHelloPermitAll() {
    Principal callerPrincipal = ctx.getCallerPrincipal();
    if (ctx.isCallerInRole("superuser")) {
      return "sayHelloPermitAll as role superuser by "+callerPrincipal.getName();
    if (ctx.isCallerInRole("user")) {
      return "sayHelloPermitAll as role user by "+callerPrincipal.getName();
    return "sayHelloPermitAll as role by "+callerPrincipal.getName();
  public String sayHelloDenyAll() {
    return "sayHelloDenyAll";

use asant dist to recreate the jar.

redeploy the jar with asadmin deploy dist/HelloSecurity.jar

rerun the client with the myadmin account:

java -cp $GLASSFISH_HOME/lib/appserv-rt.jar:$GLASSFISH_HOME/lib/appserv-admin.jar:$GLASSFISH_HOME/lib/javaee.jar:$HOME/work/HelloApp/HelloSecurity/dist/HelloSecurity.jar:.$GLASSFISH_HOME/lib/appclient/appclientlogin.conf com.bekijkhet.helloclient.HelloClient myadmin myadmin

sayHellosuperuser: sayHellosuperuser
sayHellousersuperuser: sayHellousersuperuser
sayHellouser: No Permission
sayHelloPermitAll: sayHelloPermitAll as role superuser by myadmin
sayHelloDenyAll: No Permission

We see that we get the role and the username.  You can do the same with the myuser1 and myuser2 accounts and discover that they are in the user role.


  1. Situated at the fringe of short distance to city, Sant Ritz at Potong Pasir (Singapore) in District 13.
    the interlace condo