0

I'm attempting to re-create a REST call I use in Ready-API from java but having issues.

If I make a GET request in ReadyAPI with and I use the AUTH tab in the UI, and set it to Basic, with a username and password and I check "USE GLOBAL PREFERENCE" it works without issue. However if I select "Authenticate pre-emptively" it fails.

Also in readyAPI if I insert an Authorization header with the base64 encoded string, instead of using the "Auth" tab, it also fails. This works for other servers I attempt to talk to, but not this one.

I'm trying to find out why it fails with the Authorization Header. As I'm attempting to make the same call from java with restTemplate.

Something like:

    String plainCreds = username + ":" + password;
    byte[] plainCredsBytes = StringUtils.getBytesUtf8(plainCreds);
    String base64Creds = Base64.encodeBase64String(plainCredsBytes);

    httpHeaders = new HttpHeaders();
    httpHeaders.add(HttpHeaders.AUTHORIZATION, "Basic " + base64Creds);

What is ReadyAPI doing differently when using the Auth Tab with "Use Global Preferences" that makes it succeed? How can I do this in Java?

4

2 回答 2

0

我知道这是一个老问题,但我希望这对某人有所帮助。

我有同样的情况,我在这里找到了解决方案:https ://www.baeldung.com/resttemplate-digest-authentication

基本上,您必须创建自己的RestTemplatebean,因此授权是通过摘要而不是基本的:

@Bean(name = "myRestTemplate")
public RestTemplate myRestTemplate(
        final String username,
        final String password) {
    CloseableHttpClient client = HttpClientBuilder.create().
            setDefaultCredentialsProvider(provider(username,password)).useSystemProperties().build();

    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);

    return new RestTemplate(requestFactory);
}

private CredentialsProvider provider(String username, String password) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(AuthScope.ANY, credentials);
    return provider;
}

那么当你想使用bean时

private String getQueryOutput(String query) {
    HttpHeaders httpHeaders = new HttpHeaders();

    httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    ResponseEntity<String> resp = restTemplate.exchange(
            "https://myURL/to/accept/post",
            HttpMethod.POST,
            new HttpEntity<>(query, httpHeaders),
            String.class);

    return resp.getBody();
}
于 2021-11-17T11:27:56.637 回答
0

“基本”的身份验证方案需要通过适当的方案名称大写:

httpHeaders.add(HttpHeaders.AUTHORIZATION, "Basic " + base64Creds);

https://www.rfc-editor.org/rfc/rfc7617 第 2 节“基本”身份验证方案

于 2017-12-21T00:45:29.523 回答