gpt4 book ai didi

java - Jetty、预检和ajax

转载 作者:太空狗 更新时间:2023-10-29 22:58:38 25 4
gpt4 key购买 nike

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

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()});
}
//...
}

最佳答案

您的base64encode 函数用这两个参数做什么? Authorization header 的值必须是字符串 username:password 的 base64 编码值。 (注意冒号。)

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

关于java - Jetty、预检和ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4024275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com