1

I am trying to send an auth request to a servlet hosted by glassfish server 4, receiving back a message in plain text.

The servlet is configured for a BASIC authentication with CONFIDENTIAL transport (https) (The authentication and the servlet answer work by visiting the page with a web browser)

Here is the jquery script using ajax:

$.ajax
({
    type: "GET",
    url: "https://192.168.146.128:8181/path_to_servlet",
    dataType: 'text',
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
    },
    async: false,
    success: function (data){
        alert(data);
    }
});

and the servlet code:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text");
    PrintWriter out = response.getWriter();
    out.println("hello");
    out.close();

}

The problem is that the request don't get any answer of any type (tryied on IE, chrome and firefox with the same result).

What should I do? Is this the right way to authenticate? And do I need to send the header authorization request with every further request?

4

1 回答 1

0

jQuery .ajax 对象允许“用户名”和“密码”属性,不要尝试硬编码您的授权标头。

根据 HTTP 规范,您发送对数据的请求,如果它是安全的,您会收到拒绝访问响应,并使用 Authorization 标头回复该响应。

如果在您手动访问它时它不起作用,那么您的服务器可能配置错误,向客户端发送一个不允许 Authorization 标头的 Access-Control-Allow-Headers 标头。如果它在您手动执行(不使用 Ajax)时有效,则可能是跨域问题,也许您可​​以检查您使用的浏览器的错误控制台或开发工具,以检查请求的响应或抛出的任何警告/错误.

于 2013-07-17T12:11:38.060 回答