Sending GET request with Authentication headers using restTemplate

前端 未结 6 1414
执念已碎
执念已碎 2021-01-31 01:20

I need to retrieve a resources from my server by sending a GET request with the some Authorization headers using RestTemplate.

After going over the docs I noticed that

6条回答
  •  耶瑟儿~
    2021-01-31 01:31

    All of these answers appear to be incomplete and/or kludges. Looking at the RestTemplate interface, it sure looks like it is intended to have a ClientHttpRequestFactory injected into it, and then that requestFactory will be used to create the request, including any customizations of headers, body, and request params.

    You either need a universal ClientHttpRequestFactory to inject into a single shared RestTemplate or else you need to get a new template instance via new RestTemplate(myHttpRequestFactory).

    Unfortunately, it looks somewhat non-trivial to create such a factory, even when you just want to set a single Authorization header, which is pretty frustrating considering what a common requirement that likely is, but at least it allows easy use if, for example, your Authorization header can be created from data contained in a Spring-Security Authorization object, then you can create a factory that sets the outgoing AuthorizationHeader on every request by doing SecurityContextHolder.getContext().getAuthorization() and then populating the header, with null checks as appropriate. Now all outbound rest calls made with that RestTemplate will have the correct Authorization header.

    Without more emphasis placed on the HttpClientFactory mechanism, providing simple-to-overload base classes for common cases like adding a single header to requests, most of the nice convenience methods of RestTemplate end up being a waste of time, since they can only rarely be used.

    I'd like to see something simple like this made available

    @Configuration
    public class MyConfig {
      @Bean
      public RestTemplate getRestTemplate() {
        return new RestTemplate(new AbstractHeaderRewritingHttpClientFactory() {
            @Override
            public HttpHeaders modifyHeaders(HttpHeaders headers) {
              headers.addHeader("Authorization", computeAuthString());
              return headers;
            }
            public String computeAuthString() {
              // do something better than this, but you get the idea
              return SecurityContextHolder.getContext().getAuthorization().getCredential();
            }
        });
      }
    }
    

    At the moment, the interface of the available ClientHttpRequestFactory's are harder to interact with than that. Even better would be an abstract wrapper for existing factory implementations which makes them look like a simpler object like AbstractHeaderRewritingRequestFactory for the purposes of replacing just that one piece of functionality. Right now, they are very general purpose such that even writing those wrappers is a complex piece of research.

提交回复
热议问题