401格式错误的HTTP基本授权标头:通过RestTemplate执行api时出错

时间:2019-04-08 15:09:53

标签: java spring jenkins

我正在尝试执行api。该API触发了Jenkins的构建。我正在编码我的用户名和密码,然后将其设置为标题。但这给了我以下错误

  

org.springframework.web.client.HttpClientErrorException:401格式错误   HTTP基本授权标头。

api在此卷曲下运行良好:

curl -kX POST --header 'Content-Type: application/json' --header 'Accept: application/json' 'https://XYZ' --user "username:password"

Jave节目:

TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();

SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

requestFactory.setHttpClient(httpClient);
String encodeBytes = Base64.getEncoder().encodeToString(("username" + "password").getBytes());
ManagementController.restTemplate = new RestTemplate(requestFactory);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + encodeBytes);
headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(deployURL,HttpMethod.POST, entity, String.class);
String message=response.getBody();
return modelAndView;

谢谢!

2 个答案:

答案 0 :(得分:0)

  

客户端[edit]

     

当用户代理想要将身份验证凭据发送到服务器时,它可以使用 Authorization 字段。

     

授权字段的结构如下:[6]

     
      
  1. 用户名和密码用单个冒号(:)组合。这意味着用户名本身不能包含冒号。
  2.   
  3. 结果字符串被编码为一个八位字节序列。只要与US-ASCII兼容,默认情况下未指定用于此编码的字符集,但是服务器可以通过发送 charset 参数来建议使用UTF-8。{{3 }}
  4.   
  5. 结果字符串使用[7]的变体进行编码。
  6.   
  7. 然后将授权方法和空格(例如“ Basic”)添加到编码字符串中。
  8.   
     

例如,如果浏览器使用Aladdin作为用户名,使用OpenSesame作为密码,则该字段的值为Aladdin:OpenSesame或QWxhZGRpbjpPcGVuU2VzYW11l的base64编码。然后,授权标头将显示为:

     

One vs Rest

     

-Base64

我认为您忘了在用户名和密码之间加一个冒号:

Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l

答案 1 :(得分:0)

使用此方法并在标题中传递用户名和密码

private HttpHeaders createHeaders(final String username, final String password) {
        return new HttpHeaders() {
            {
                if (!StringUtils.isBlank(username)) {
                    String auth = username + ":" + password;
                    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
                    String authHeader = "Basic " + new String(encodedAuth);
                    set("Authorization", authHeader);
                }
            }
        };
    }