我正在尝试使用摘要认证连接到我的机器上的Tomcat Web服务器。我正在使用tomcat的内存域。以下是服务器的配置方式:
1)在server.xml中:
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开发人员,我想问一下是否有人对我的实现有什么想法或发现错误。
提前感谢您!