我的Web服务器托管在具有基本身份验证的Apache Tomcat 7中。我有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==")过 但是请求发送时没有身份验证头。任何帮助将不胜感激。
header:("Authorization","Basic dG9tY2F0OnRvbWNhdA==")
发现通过标头传递身份验证不适用于jsonp数据类型的jQuery ajax。因此尝试了以下方法,效果很好。
$.ajax({ type: "GET", url: "http://tomcat:tomcat@localhost:1222/testservice/rest/test/users", dataType:"jsonp", success: function(res) { alert(res); }, error: function(err) { alert(err); } }); function callbackMethod(data) { alert(data); }