【问题标题】:How to pass user and password to Spring REST service with Spring RESTTemplate如何使用 Spring RESTTemplate 将用户和密码传递给 Spring REST 服务
【发布时间】:2013-06-02 19:38:27
【问题描述】:

如何使用 Spring RESTTemplate 将用户和密码传递给 Spring REST 服务..

我有一个使用 Spring Secuirty 的 Spring MVC 项目,我需要使用 Spring RESTTemplate 编写一个客户端来访问它。我有以下代码,但它不起作用:

public static void main(String[] args)
    {
        LOGGER.debug("Starting REST Client!!!!");


        HttpClient client = new HttpClient();

        UsernamePasswordCredentials credentials =
                new UsernamePasswordCredentials("test","test");

        client.getState().setCredentials(
                new AuthScope("127.0.0.1", 8080, AuthScope.ANY_REALM),
                credentials);

        CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client);

        RestTemplate restTemplate = new RestTemplate(commons);


        String jsonreturn = restTemplate.getForObject("http://127.0.0.1:8080/springmvc-rest-secured-test/json/Regan", String.class);

        LOGGER.debug(jsonreturn);
    }

我在退货时收到了春季登录屏幕,而不是我正在寻找的数据,所以这告诉我我的凭据不起作用..

【问题讨论】:

  • 请发布您的 Spring Security 配置文件。您是否配置了基本身份验证?如果没有,UsernamePasswordCredentials 将不起作用。

标签: spring rest spring-mvc spring-security


【解决方案1】:

如果您从服务器端发布方法签名会有所帮助。你是如何进行身份验证的?这是一个获取示例。 post 将是相同的,但使用 postForObject()

String result = restTemplate.getForObject("http://127.0.0.1:8080/springmvc-rest-secured-test/json/{user}/{password}", String.class, "user", "pass");

【讨论】:

  • 我正在使用基本的 Spring Security。我相信基于形式
  • 开箱即用的 Spring 安全性使用 POST,实际上不是 REST 服务。上面的代码并不正确,它只是正确语法的一个示例。
猜你喜欢
  • 2013-07-24
  • 2013-07-11
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 2015-11-11
  • 2017-04-06
相关资源
最近更新 更多