Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetty, preflight and ajax

Having a Jetty server set up programmatically which I try to access via ajax and xmlHttpRequest. Without authorization, the call works fine but with, I get 401 Unauthorized. Any suggestions.

Javascript call looks like this (shortened):

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);
}

Server code looks like this (even shorter)

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()});
    }
//...
}
like image 669
Jorgen Avatar asked Oct 26 '10 13:10

Jorgen


1 Answers

What does your base64encode function do with the two parameters? The Authorization header's value must be the base64 encoded value of the string username:password. (Note the colon.)

Note: for same origin XMLHttpRequests, you can provide the username and password as a parameter to the open method.

like image 185
marekful Avatar answered Oct 21 '22 22:10

marekful