从java调用RestAPI:没有找到AuthenticationProvider UsernamePasswordAuthenticationToken

时间:2017-12-06 16:33:11

标签: java spring rest httpclient

我只是想使用下面的代码调用rest api

SSLConnectionSocketFactory sslsf;
CredentialsProvider credentialsProvider;
HttpClient httpClient;

final static Logger LOGGER = Logger.getLogger(Constructor.class);

public Constructor() {
    try{
    sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(), NoopHostnameVerifier.INSTANCE);

    credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            ConfigData.getInstance().getSAEUsername(), ConfigData.getInstance().getSAEPassword()));
    httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(credentialsProvider)
            .build();
    }
    catch (Exception e) {
    }
}

public String callAPI() {
    String jsonResponse = "";
    try {
        String s = "111.11.11.11";   
        //String s1 = "username"; // this works fine
        String s1 = "domain\username"; //AuthenticationProvider found Error
        String s2 =  "password";    
        String endpoint = "https://" + s + ":3600/Xxxxxxx/Yyyyyy/Ccccccc";
        HttpGet request = new HttpGet(endpoint);
        request.addHeader("content-type", "application/json");
        request.addHeader("accept", "application/json");//

        byte[] credentials = Base64.encodeBase64(
                (s1 + ":" + s2)
                        .getBytes(StandardCharsets.UTF_8));
        String s3 = new String(credentials, StandardCharsets.UTF_8);
        request.addHeader("Authorization", "Basic " + s3);
        HttpResponse response = httpClient.execute(request);
        jsonResponse = EntityUtils.toString(response.getEntity());
        LOGGER.info("Response: " + jsonResponse);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return jsonResponse;
}

如果用户名只是"用户名" (例如:admin)我得到了正确的回复但是如果用户名是域名的一部分,例如"域\用户名"(例如:DAAK \ admin)那么我在回复时会收到以下错误:

<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
<title>Error 401 </title>
</head>
<body>
<h2>HTTP ERROR: 401</h2>
<p>Problem accessing /Xxxxxxx/Yyyyyy/Ccccccc. Reason:
<pre>    No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken</pre></p>
<hr /><i><small>Powered by Jetty://</small></i>
</body>
</html>

我不知道Srings框架。这有一只简单的狐狸吗?

1 个答案:

答案 0 :(得分:0)

基本身份验证仅包含用户名:密码,您不能在此使用域名。

为什么需要提供域名?