gpt4 book ai didi

java - 使用 HttpUrlConnection 的 HTTP 摘要认证

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:14:38 24 4
gpt4 key购买 nike

我正在尝试使用摘要式身份验证连接到我机器上的 Tomcat Web 服务器。我正在使用 tomcat 的内存领域。以下是服务器的配置方式:

1) 在 server.xml 中:

<Realm className="org.apache.catalina.realm.MemoryRealm" digest="MD5" />

2) 在 tomcat-users.xml 中

<user username="testuser" password="81dc9bdb52d04dc20036dbd8313ed055" roles="test"/>

3) 在我的 web 项目的 web.xml 中:

<auth-method>DIGEST</auth-method>

如您所见,我已将摘要方法指定为“MD5”,并且已使用 Tomcat 的 digest.sh 对密码进行了加密。

这是我在客户端的代码:

private static void testGet() throws IOException {

// Create a URL
URL test = new URL("http://localhost:8080/TestWebProject/TestServlet");

// Open a connection to the URL
HttpURLConnection conn = (HttpURLConnection) test.openConnection();

MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}

// Digest password using the MD5 algorithm
String password = "1234";
md5.update(password.getBytes());
String digestedPass = digest2HexString(md5.digest());

// Set header "Authorization"
String credentials = "testuser:" + digestedPass;
conn.setRequestProperty("Authorization", "Digest " + credentials);

// Print status code and message
System.out.println("Test HTTP GET method:");
System.out.println("Status code: " + conn.getResponseCode());
System.out.println("Message: " + conn.getResponseMessage());
System.out.println();

}

private static String digest2HexString(byte[] digest)
{
String digestString="";
int low, hi ;

for(int i=0; i < digest.length; i++)
{
low = ( digest[i] & 0x0f ) ;
hi = ( (digest[i] & 0xf0)>>4 ) ;
digestString += Integer.toHexString(hi);
digestString += Integer.toHexString(low);
}
return digestString ;
}

我认为我的客户端代码没问题,服务器的配置也没有问题。尽管服务器不断向我发送状态代码 401 和消息“未经授权”。由于我不是经验丰富的 Java 开发人员,我想问问是否有人知道我的实现或在我的实现中看到错误。

提前致谢!

最佳答案

Digest 身份验证远比仅发送 username:password 复杂得多(这实际上是 Basic 身份验证......并且 username:password 元组需要进行 Base64 编码! ).

您可以阅读有关摘要的所有信息 here .

如果您不需要使用 HttpUrlConnection,请查看这两个项目:

它们都已经支持开箱即用的 Digest(和其他有用的东西)。

关于java - 使用 HttpUrlConnection 的 HTTP 摘要认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4008545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com