小编典典

使用Apache HttpClient 4的抢占式基本身份验证

java

是否有比此处描述的更简单的方法来设置HTTP客户端以进行抢占式基本身份验证?
在以前的版本(3.x)中,它曾经是一个简单的方法调用(例如httpClient.getParams().setAuthenticationPreemptive(true))。
我要避免的主要事情是将BasicHttpContext添加到我执行的每个方法中。


阅读 660

收藏
2020-03-12

共2个答案

小编典典

不每次都传递上下文很难做到这一点,但是你可以使用请求拦截器来做到这一点。这是我们使用的一些代码(从JIRA iirc中找到):

// Pre-emptive authentication to speed things up
BasicHttpContext localContext = new BasicHttpContext();

BasicScheme basicAuth = new BasicScheme();
localContext.setAttribute("preemptive-auth", basicAuth);

httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

(...)

static class PreemptiveAuthInterceptor implements HttpRequestInterceptor {

    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
        AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

        // If no auth scheme avaialble yet, try to initialize it
        // preemptively
        if (authState.getAuthScheme() == null) {
            AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
            CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (authScheme != null) {
                Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (creds == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.setAuthScheme(authScheme);
                authState.setCredentials(creds);
            }
        }

    }

}
2020-03-12
小编典典

如果您希望强制HttpClient 4通过单个请求进行身份验证,则可以使用以下方法:

String username = ...
String password = ...
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

HttpRequest request = ...
request.addHeader(new BasicScheme().authenticate(creds, request));
2020-11-19