Spring Boot & Jersey - AuthenticationFilter - No session in endpoint

时间:2017-08-05 11:11:44

标签: java spring hibernate spring-boot jersey-2.0

I have an Authorization filter in Jersey that authenticates and retrieves the User object from DB. I pass this user object via a custom SecurityContext to the endpoint.

@Transactional
public class AuthenticationFilter implements ContainerRequestFilter {
 requestContext.setSecurityContext(new SecurityContext() {
            @Override
            public Principal getUserPrincipal() {
                return new UserInfo(userService.findById(1));
            }
        });
     ...}

I retrieve the object at the endpoint with a SecurityContext.

@Transactional
 public Response endpoint(@Context SecurityContext securityContext){
             UserInfo userInfo = (UserInfo) securityContext.getUserPrincipal();
        }

I then try to initialize a lazy loaded collection of children with:

 Hibernate.initialize(userInfo.getUser().getChildren());

I still get the error

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: user.children, could not initialize proxy - no Session

I've tried with and without @Transactional on some/all methods involved to no avail.

The children must be lazy loaded due to performance reasons. I do not want to retrieve them with each authentication. The easy alternative here is to return an attribute to the SecurityContext, but that would be doing 2 database calls for the same user object in almost every endpoint that makes use of the user object.

0 个答案:

没有答案