【问题标题】:Rest service pass through via spring休息服务通过弹簧传递
【发布时间】:2013-01-13 18:02:37
【问题描述】:

我已经构建了 Spring 应用程序,由于某些安全性,我有一个使用休息服务并通过我的 Spring 应用程序公开相同服务的要求

即对于我使用的其余服务,我提供了只有我的应用程序应该知道的安全凭证,并通过我的 Spring 应用程序公开相同的服务。

我可以为我使用的每个带有相应身份验证的休息服务编写包装休息服务,并公开这些包装服务,这些服务可以使用我的 Spring 应用程序身份验证凭据进行身份验证

但这是很多工作,我实际上正在做的是使用 web 服务并通过一些身份验证映射公开相同的服务。在春季是否可以选择通过其余服务

【问题讨论】:

    标签: spring model-view-controller rest


    【解决方案1】:

    为什么不为每个 HTTP 请求类型公开一个 REST 服务,并根据路径中的信息对其进行路由?例如(未经测试,可能无法按原样工作,但您了解基本概念):

    @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
    

    如果您需要与不同的主机通信,您只需添加另一个路径变量,作为存储不同目标基本 URL 的映射的键。您可以从控制器添加任何您想要的身份验证,或者通过 Spring Security 中的自定义身份验证。

    您的问题在细节上有点轻,因此您的具体情况可能会使事情复杂化,但基本方法应该可行。

    【讨论】:

    • 非常感谢这就是我正在寻找的,而不是字符串是返回 JSON 或 XML 的方法,我的 API 必须支持它们并且我都调用的 API 也支持它们。所以我只需要根据我的 API 上的请求类型传递相同的输出
    • 我还没有测试过上述内容,但我的想法是通过将响应作为字符串处理,您只需通过远程服务返回的任何表示。
    • 我可以确认这工作正常 - 我正在通过 JSON
    • produces = {MediaType.APPLICATION_JSON_VALUE}produces = {MediaType.APPLICATION_XML_VALUE}添加到@RequestMapping指定返回给客户端的内容类型。
    猜你喜欢
    • 2013-10-02
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    相关资源
    最近更新 更多