Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a header to HTTP request using a filter in JAX-RS?

I'm modifying aHttpRequest on my WebFilter by adding a single header to request using a HttpServletRequestWrapper implementation class:

HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(request);
requestWrapper.addHeader(OAuth.OAUTH_ACCESS_TOKEN, accessTokenWord);
chain.doFilter(requestWrapper, response);

After doFilter(requestWrapper, response) is performed, JAX-RS leads request to its resource, which has a @RequestScoped field:

@Inject
protected HttpServletRequest request;

However, it doesn't contain any expected header:

@PostConstruct
protected void initialize_resources() throws IllegalStateException {

    this.currentUser = null;
    String accessToken = this.request.getHeader(OAuth.OAUTH_ACCESS_TOKEN);
    AccessToken accessToken = this.memcachedResources.getMemcachedAccessTokenRepository()
                                  .get(accessToken);

    if (accessToken != null && StringUtils.isNotEmpty(accessToken.getUser_id())) {
        this.currentUser = this.em.find(User.class, accessToken.getUser_id());
        this.currentClient = accessToken.getClientId();    
    }
}

So, this.request.getHeader(OAuth.OAUTH_ACCESS_TOKEN) is null.

How can I solve that?

like image 794
Jordi Avatar asked Jan 08 '16 11:01

Jordi


1 Answers

Refer to this question for details on how to add HTTP headers to the request using a servlet filter. If you intend to use a JAX-RS filter, keep reading.


JAX-RS filters

Once you are working with JAX-RS, you'd better using a ContainerRequestFilter like the following to add a header to the request:

@Provider
public class MyContainerRequestFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        requestContext.getHeaders().add("header", "value");
    }
}

Observe the following:

  • The ContainerRequestContext#getHeaders() returns a mutable multivalued map which contains the request headers.

  • The @Provider annotation marks an implementation of an extension interface that should be discoverable by JAX-RS runtime during a provider scanning phase.

For more details about JAX-RS filters, have a look at the Jersey documentation. The JAX-RS filters can be applied globally or can be name-bound to a subset of endpoints.

Getting the headers values

In your REST endpoints, you can inject HttpHeaders:

@Context
HttpHeaders httpHeaders;

Then use the HttpHeaders API to get the header values:

  • HttpHeaders#getHeaderString(String)
  • HttpHeaders#getRequestHeaders()
  • HttpHeaders#getHeaderString(String)
like image 69
cassiomolin Avatar answered Oct 16 '22 08:10

cassiomolin