如何提出摘要身份验证的现时或领域请求?

时间:2018-12-08 12:56:31

标签: java apache-commons-httpclient digest-authentication nonce

对于我的项目,我想连接到提供的Shopware API,因为我对REST Services并不熟悉,所以我从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需要是现时值或来自服务器的整个标头,但是我找不到存储这些值的方法。还尝试了this,但没有成功。

有什么想法吗?预先谢谢你!

0 个答案:

没有答案