Navigator Voyager
Navigator Voyager

Reputation: 255

Rest service pass through via spring

I have built spring application, i have one requirement to consume a rest service and just expose the same via my spring application because of some security

i.e for the rest service i consume i have provide security credentials that only my application should know and expose the same service via my spring application.

I could write wrapper rest service for every rest service i consume with corresponding authentication and expose these wrapper services which can be authenticated with my spring application Auth credentials

But this is lot of work what i am essentially doing is consuming webservice and expose the same with some auth mapping. In spring is there a option to pass through the rest services

Upvotes: 9

Views: 7625

Answers (1)

ach
ach

Reputation: 6234

Why not just expose a REST service for each HTTP request type, and route it based on information in the path? For example (untested, probably won't work as is, but you get the basic idea):

@Autowired
RestTemplate restTemplate;

@Value("${rest.proxy.target.base.url}")
String targetBaseUrl;

@RequestMapping(value = "/restProxy/{restUrlPath}", method = RequestMethod.GET)
public @ResponseBody String restProxyGet(@PathVariable("restUrlPath") String restUrlPath) {
    return restTemplate.getForObject(targetBaseUrl+ "/" + restUrlPath, String.class);
}

@RequestMapping(value = "/restProxy/{restUrlPath}", method = RequestMethod.POST)
public @ResponseBody String restProxyPost(@PathVariable("restUrlPath") String restUrlPath, @RequestBody String body) {
    return restTemplate.postForObject(targetBaseUrl + "/" + restUrlPath, body, String.class);
}

//Can also add additional methods for PUT, DELETE, etc. if desired

If you need to communicate with different hosts you can just add another path variable that acts as a key to a map that stores the different target base URLs. You can add whatever authentication you want from the controller, or via custom authentication in Spring Security.

Your question is somewhat light on details so your specific scenario may complicate things, but the basic approach should work.

Upvotes: 6

Related Questions