使用当前httpclient(4.x)的RestTemplate基本身份验证或摘要身份验证 [英] RestTemplate basic or digest Authentication with the current httpclient (4.x)

本文介绍了使用当前httpclient(4.x)的RestTemplate基本身份验证或摘要身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 RestTemplate httpclient(4.x)进行摘要(或基本)身份验证.

I'm trying to do Digest mostly (or Basic) Authentication using RestTemplate and httpclient (4.x).

由于我找不到如何实际执行此操作的任何相关示例,因此我尝试了多种方法来钩挂各种httpclient工件,但没有运气-本质上,没有在以下位置发送 Authentication 标头全部.

Since I couldn't find any relevant examples of how to actually do this, I have attempted various ways to hook the various httpclient artifacts, with no luck - essentially, no Authentication header is sent at all.

我当前的实现是:

DefaultHttpClient newHttpClient = new DefaultHttpClient();
Credentials credentials = new UsernamePasswordCredentials( username, password );
AuthScope authScope = new AuthScope( host, port, AuthScope.ANY_REALM );
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials( authScope, credentials );
newHttpClient.setCredentialsProvider( credentialsProvider );

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( newHttpClient );
restTemplate.setRequestFactory( requestFactory );

我在做错什么吗?是否在任何地方都有可行的示例? 任何帮助表示赞赏. 谢谢.

Is there something I'm doing wrong? Is there also a working example for this anywhere? Any help is appreciated. Thanks.

推荐答案

尝试实现自己的RequestFactory来实现抢占式身份验证.

Try implementing your own RequestFactory in order to achieve preemptive authentication.

public class PreEmptiveAuthHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {

public PreEmptiveAuthHttpRequestFactory(DefaultHttpClient client) {
    super(client);
}

@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());
    authCache.put(targetHost, basicAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    return localcontext;
}
}

然后使用它:

HttpComponentsClientHttpRequestFactory requestFactory = new PreEmptiveAuthHttpRequestFactory( newHttpClient );

希望有帮助

如何设置用户名和密码(摘自@bifur的评论)

how to set the username and password (Copied from @bifur's comment)

您可以使用UserNamePasswordCredentials

UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getUsername(),getPassword()); 
client.getCredentialsProvider().setCredentials(new AuthScope(getHost(), getPort(), AuthScope.ANY_REALM), credentials); 

只需在以前的工厂中使用客户端

And just use the client in the previous factory

HttpComponentsClientHttpRequestFactory requestFactory = new PreEmptiveAuthHttpRequestFactory(client);

这篇关于使用当前httpclient(4.x)的RestTemplate基本身份验证或摘要身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆