如何确定给定401响应的认证要求?

问题描述 投票:0回答:2

我在客户端使用以下代码来获取受保护网站的响应,只要服务器端没有身份验证请求,该网站就可以正常工作。

    final String targetURL   = "http://************";
    final String username    = "********";
    final String password    = "******";
    final int connectTimeout = 30000;

    final String username_password         = username + ":" + password;
    final byte[] usernamepassword          = (byte[])username_password.getBytes();
    final String encoded_username_password = java.util.Base64.getEncoder().encodeToString(usernamepassword);

    final URL url = new URL(targetURL);
    final URLConnection connection = url.openConnection();

    connection.setConnectTimeout(connectTimeout);
    connection.setRequestProperty("Authorization", "Basic " + encoded_username_password);
    connection.setRequestProperty("Accept", "text/html");

    // response headers
    final Map<String, List<String>> headerFields = connection.getHeaderFields();

    for (final Map.Entry<String, List<String>> entry : headerFields.entrySet()) {
        System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
    }

但是,当我尝试连接特定的(受保护的)Web服务器时,使用401 http状态代码拒绝连接。

键:null,值:[HTTP / 1.1 401未经授权]密钥:WWW-Authenticate,值:[Digest realm =“登录到********”,qop =“ auth”,nonce =“ *******”,opaque =“”]键:连接,值:[关闭]键:内容长度,值:[0]

是否可以从上面记录的响应中推断出我所缺少的内容?

[我的意思是,上面的代码段是一个众所周知的Java 模板,到处都有很多具有相同结构的示例,因此该问题似乎与作为[[setRequestProperty()方法的参数而发出的参数有关。

这是我使用

Mozilla >> Web Developer >> Debug

(其中某些字段对我隐藏了)的请求标头的内容:

主机:xxx.xxx.xxx.xxx

User-Agent

:Mozilla / 5.0(Windows NT 10.0; Win64; x64; rv:76.0)Gecko / 20100101 Firefox / 76.0

Accept

:text / html,application / xhtml + xml,application / xml; q = 0.9,image / webp,/
; q = 0.8

Accept-Language:pt-BR,pt; q = 0.8,en-US; q = 0.5,en; q = 0.3

Accept-Encoding

:gzip,deflate

Connection

:保持活动状态>>

升级不安全请求

:1

Pragma

:无缓存

Cache-Control

:无缓存

Authorization

:摘要用户名=“”,领域=“登录到xxxxxxx”,nonce =“ xxx-xxx-xxx-xxx-xxx”,uri =“ xxxxxxx”,响应=“ xxxxx”,qop = auth,nc = 00000001,cnonce =“ b2b43c8d9631354d”
我正在客户端使用以下代码来获取受保护网站的响应,只要服务器端没有身份验证请求,该网站就可以正常工作:final String ...
java http url basic-authentication http-status-code-401
2个回答
0
投票
我不确定您的问题。我的猜测是您希望根据参数和url过滤请求,以便选择服务内容还是拒绝并返回401。

0
投票
仅因为您未通过其服务器的身份验证,
© www.soinside.com 2019 - 2024. All rights reserved.