Jersey Async ContainerRequestFilter

后端 未结 3 1194
挽巷
挽巷 2020-12-16 18:17

I have a Jersey REST API and am using a ContainerRequestFilter to handle authorization. I\'m also using @ManagedAsync on all endpoints so that my A

3条回答
  •  轮回少年
    2020-12-16 18:46

    We use Spring security for authentication/authorization. I worked around the problem using a sub-resource locator with empty path as shown below:

    @Path("/customers")
    public class CustomerResource {
        @Inject
        private CustomerService customerService;
    
        @Path("")
        public CustomerSubResource delegate() {
            final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            return new CustomerSubResource(auth);
        }
    
        public class CustomerSubResource {
            private final Authentication auth;           
    
            public CustomerSubResource(final Authentication auth) {
                this.auth = auth;
            }
    
            @POST
            @Path("")
            @Produces(MediaType.APPLICATION_JSON)
            @Consumes(MediaType.APPLICATION_JSON)
            @ManagedAsync
            public void createCustomer(final Customer customer, @Suspended final AsyncResponse response) {
                // Stash the Spring security context into the Jersey-managed thread
                SecurityContextHolder.getContext().setAuthentication(this.auth);
    
                // Invoke service method requiring pre-authorization
                final Customer newCustomer = customerService.createCustomer(customer);
    
                // Resume the response
                response.resume(newCustomer);
            }
        }
    }
    

提交回复
热议问题