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:

/home/broersa/work/HelloApp/HelloSecurity/src/com/bekijkhet/HelloBean.java

[sourcecode language="java"]

package com.bekijkhet;
import javax.ejb.Stateless;
import javax.ejb.Remote;
import javax.annotation.security.RolesAllowed;
import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.DeclareRoles;
import javax.annotation.Resource;
import java.security.Principal;
import javax.ejb.SessionContext;
@Stateless
@Remote(Hello.class)
@DeclareRoles({"superuser","user"})
public class HelloBean implements Hello {
  @Resource SessionContext ctx;
  @RolesAllowed("superuser")
  public String sayHellosuperuser() {
    return "sayHellosuperuser";
  }
  @RolesAllowed({"user","superuser"})
  public String sayHellousersuperuser() {
    return "sayHellousersuperuser";
  }
  @RolesAllowed("user")
  public String sayHellouser() {
    return "sayHellouser";
  }
  @PermitAll
  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();
  }
  @DenyAll
  public String sayHelloDenyAll() {
    return "sayHelloDenyAll";
  }
}
[/sourcecode]

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:. -Djava.security.auth.login.config=$GLASSFISH_HOME/lib/appclient/appclientlogin.conf com.bekijkhet.helloclient.HelloClient myadmin myadmin

1
2
3
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.

2 comments:

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

    ReplyDelete