首页 > 解决方案 > 如何为摘要身份验证发出 nonce 或领域请求?

问题描述

对于我的项目,我想连接到提供的Shopware API因为我对 REST 服务没有那么丰富的经验,所以我从Github克隆了一个现有的 HTTPClient(使用 Apache 组件) 。我必须补充一点,Shopware 提供 DigestAuth 作为身份验证方法。

代码:

public RestApiHttpClient(URL apiEndpoint, String username, String password) {
    this.apiEndpoint = apiEndpoint;

    BasicHttpContext context = new BasicHttpContext();
    this.localContext = HttpClientContext.adapt(context);
    HttpHost target = new HttpHost(this.apiEndpoint.getHost(), -1, this.apiEndpoint.getProtocol());
    this.localContext.setTargetHost(target);


    TargetAuthenticationStrategy authStrat = new TargetAuthenticationStrategy();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope aScope = new AuthScope(target.getHostName(), target.getPort());
    credsProvider.setCredentials(aScope, creds);

    BasicAuthCache authCache = new BasicAuthCache();+

    // Digest Authentication
    DigestScheme digestAuth = new DigestScheme(Charset.forName("UTF-8"));
    authCache.put(target, digestAuth);
    this.localContext.setAuthCache(authCache);
    this.localContext.setCredentialsProvider(credsProvider);


    ArrayList<Header> defHeaders = new ArrayList<>();
    defHeaders.add(new BasicHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()));
    this.httpclient = HttpClients.custom()
            .useSystemProperties()
            .setTargetAuthenticationStrategy(authStrat)
            .disableRedirectHandling()
            .disableContentCompression()
            .setDefaultHeaders(defHeaders)
            .setDefaultCredentialsProvider(credsProvider)
            .build();
    }

所以如果我测试这个脚本,我会得到这个错误:

Dez 07, 2018 9:00:55 AM org.apache.http.impl.auth.HttpAuthenticator generateAuthResponse
SCHWERWIEGEND: DIGEST [complete=false, nonce=null, nc=0] authentication error: missing realm in challenge
{"success":false,"message":"Invalid or missing auth"}

我尝试覆盖参数(首先只有领域,而不是领域和随机数,而不是每个参数)但没有成功:

digestAuth.overrideParamter("realm", "Shopware REST-API");
digestAuth.overrideParamter("nonce", "somerandomnumber");
// or create random number;
digestAuth.overrideParamter("nonce", Long.toString(new Random().nextLong(), 36));
digestAuth.overrideParamter("qop", "auth");
digestAuth.overrideParamter("nc", "0");
digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());

我猜 DigestAuth 需要的是来自服务器的 nonce 值或整个标头,但我找不到存储这些值的方法。也试过这个,没有成功。

有任何想法吗?先感谢您!

标签: javaapache-commons-httpclientdigest-authenticationnonce

解决方案


推荐阅读