码头,预检和ajax

时间:2010-10-26 13:46:00

标签: java javascript ajax jetty

以编程方式设置Jetty服务器,我尝试通过ajax和xmlHttpRequest访问。没有授权,通话工作正常但是,我得到401 Unauthorized。 任何建议。

Javascript调用看起来像这样(缩短):

var auth = base64encode('name','pwd');
try{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "http://127.0.0.1:5563/ajax/index.html", true);
    xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xmlhttp.setRequestHeader('Authorization', auth);
    xmlhttp.withCredentials = 'true';
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML; 
    $('#textResult').val(xmlDoc);
}
catch(e){
    $('#textResult').val('CATCH: ' + e);
}

服务器代码看起来像这样(甚至更短)

class CallObject extends HttpServlet {
    //...
    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response)
    throws IOException
    {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods",
                       "GET, POST, HEAD, OPTIONS");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Headers",
                       "X-Requested-With, authorization");
    }
//...
}

class WebServer{
//...
    SecurityHandler sh = null;
    if (logins != null && logins.length > 0){
        String role = "user";
        sh = new SecurityHandler();
        Constraint constraint = new Constraint();
        constraint.setName(Constraint.__BASIC_AUTH);
        constraint.setRoles(new String[]{role});
        constraint.setAuthenticate(true);
        ConstraintMapping cm = new ConstraintMapping();
        cm.setConstraint(constraint);
        cm.setPathSpec("/*");
        HashUserRealm hur = new HashUserRealm();
        hur.setName("eMark Web Server");
        for (int i = 0; i < logins.length; i++) {
            String user_name = logins[i][0];
            String password = logins[i][1];
            hur.put(user_name, password);
            hur.addUserToRole(user_name, role);
        }
        sh.setUserRealm(hur);
        sh.setConstraintMappings(new ConstraintMapping[]{cm});
        _server.setHandlers(
            new Handler[]{sh, _contexts, new DefaultHandler()});
    }
//...
}

2 个答案:

答案 0 :(得分:1)

您的base64encode函数对这两个参数有何作用? Authorization标头的值必须是字符串username:password的base64编码值。 (注意冒号。)

注意:对于相同来源的XMLHttpRequests,您可以提供用户名和密码作为open方法的参数。

答案 1 :(得分:0)

Authorization标头应如下所示:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

“Basic”之后出现的文本是base64编码:

检查此链接以获取更多信息: http://en.wikipedia.org/wiki/Basic_access_authentication