以編程方式設置Jetty服務器,我嘗試通過ajax和xmlHttpRequest訪問它。未經授權,電話正常工作,但是,我得到401未經授權。 任何建議。Jetty,預檢和ajax
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()});
}
//...
}
我想這會對你有用[1](http://docs.codehaus.org/display/JETTY/How+to+Configure+Security+with+Embedded+Jetty)。我還可以看到你從javascript輸入的憑證是「var auth = base64encode('name','pwd');」。這意味着'name'的憑證是'pwd',它應該出現在具有相關角色的碼頭 – nibin012 2011-08-03 09:25:48
爲什麼您直接在客戶端代碼上設置「Authorization」請求標頭?爲什麼不在open()方法中使用XmlHttpRequest支持進行身份驗證? 此外,不知道您的base64encode函數是否將auth變量格式化爲「name:pwd」。 – 2012-06-08 16:04:37
看起來你正在做一個異步請求,但試圖同步讀取響應?這只是您發佈此問題時所做的簡化嗎?如果不是,則需要爲'xmlhttp'對象的'onreadystatechange'屬性指定一個回調函數。 – 2012-08-07 01:13:24