users@jersey.java.net

[Jersey] Injecting Principal best practices

From: Christopher Piggott <cpiggott_at_gmail.com>
Date: Sun, 13 Feb 2011 15:58:45 -0500

Hi,

I find myself all over the place injecting SecurityContext so that I
can do this:

@RequestScoped
public class SomeResource {
   @Context SecurityContext sc;

   public Response someResourceMethod() {
      MyPrincipal p = (MyPrincipal) sc.getUserPrincipal();
      ...
   }
}

where MyPrincipal obviously extends Principal. What I would rather do is:

@RequestScoped
public class SomeResource {
   private final MyPrincipal p;

   @Inject
   public SomeResource(MyPrincipal p) {
      this.p = p;
   }

   public Response someResourceMethod() {
      ...
   }
}

http://code.google.com/p/google-guice/wiki/InjectOnlyDirectDependencies
has a great explanation of why I care: Injecting a SecurityContext
just to get a MyPrincipal (which I annoyingly have to cast every time)
is really a way of injecting a dependency indirectly.

I have my own ContainerRequestFilter, by the way, which creates a
MySecurityContext.

Even being able to avoid the cast would be helpful, I suppose.

Any fellow guice-heads have any thoughts on this?