3

I'm trying to setup authorization for graphql-java-demo so I have to extract a cookie from a request to make it work for graphql's queries (which are http requests):

String cookie = request.getHeader("Cookie");

and I get a request by adding

@Autowired
private HttpServletRequest request;

to my service class:

@Service
@Transactional
@Configuration
@WebListener
public class ServiceImpl extends RequestContextListener implements MyService  {
    @Autowired
    NetworkService networkService;

    // I had it previously when using just request.getHeader("Cookie");
    // @Autowired
    // private HttpServletRequest request;

    @Override
    public Optional<Foo> foo() {
        String responseContent = networkService.send(..., getCookie());
        ...
    }

    // https://stackoverflow.com/questions/24025924/java-lang-illegalstateexception-no-thread-bound-request-found-exception-in-asp
    private Optional<String> getCookie() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes != null) { // it's always null
            HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
            return Optional.ofNullable(request.getHeader("Cookie"));
        }
        return Optional.empty();
    }
}

The problem is that when I launch graphql's subscription (that basically starts a websocket connection) I receive:

java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

I saw some similar questions that say I should modify web.xml that I don't have in my project but I did try to add (using the accepted answer from that question):

@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}

but the following line still returns null for me:

RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

So how can I access request using websocket connection in spring boot?

James Larkin
  • 541
  • 5
  • 18

0 Answers0