Pergunta

Problem Definition

I'm converting a legacy app to use a REST api where each method requires getting data from a session variable (I know it's not truly a REST application, but it's legacy code).

I'd like to keep the code DRY, so I tried setting the session variable in the constructor, but the HttpServletRequest isn't ready during construction. I'd like to set the User variable in one place. What is the proper way to do this?

Code Sample

@Path("/someResource")
public class SomeResource {
  @Context
  HttpServletRequest currentRequest;

  private User user = null;

  public SomeResource() {
    // This doesn't work
    // HttpSession session = currentRequest.getSession();
    // user = (User) session.getAttribute("user");
  }

  @GET
  @Produces ( ... )
  @PermitAll
  @Path( ... )
  public findById read(...) {
    HttpSession session = currentRequest.getSession();
    User user = (User) session.getAttribute("user");
    ...
  }

  @GET
  @Produces ( ... )
  @PermitAll
  @Path( ... )
  public findByName read(...) {
    HttpSession session = currentRequest.getSession();
    User user = (User) session.getAttribute("user");
    ...
  }

  @GET
  @Produces ( ... )
  @PermitAll
  @Path( ... )
  public someResource findAll (...) {
    HttpSession session = currentRequest.getSession();
    User user = (User) session.getAttribute("user");
    ...
  }

  ... many other paths, etc... each checking the user session variable.
}
Foi útil?

Solução

"Security information of a request is available by injecting a JAX-RS SecurityContext instance using @Context annotation. The injected security context instance provides the equivalent of the functionality available on HttpServletRequest API"

https://jersey.java.net/documentation/latest/security.html#d0e10543

Hope that helps

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top