我在 Apache Tomcat 7 中托管了具有基本身份验证的 Web 服务器。我有 Tomcat 用户“tomcat”,角色为“tomcat”,密码为“tomcat”。以下分别是我在客户端的 web.xml 文件和脚本片段。
Web.xml
<?xml version="1.0" encoding="ASCII"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>testservice</display-name>
<servlet>
<description>JAX-RS Tools Generated - Do not modify</description>
<servlet-name>testservice</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>testservice</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>testservice</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>tomcat</role-name>
</auth-constraint>
<user-data-constraint>
<!-- transport-guarantee can be CONFIDENTIAL, INTEGRAL, or NONE -->
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
客户端脚本:
<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$.ajax({
type: "GET",
beforeSend: function (request)
{
request.setRequestHeader("Authorization", "Basic dG9tY2F0OnRvbWNhdA==");
},
url: "http://localhost:1222/testservice/rest/test/users",
dataType:"jsonp",
success: function(res) {
alert(res);
},
error: function(err) {
alert(err);
}
});
</script>
我很确定 Web 服务和基本身份验证没有问题。但是从客户端脚本中,没有发送身份验证标头。我也试过header:("Authorization","Basic dG9tY2F0OnRvbWNhdA==")
。但是请求发送时没有身份验证标头。任何帮助将不胜感激。