具有Authorization标头的JavaScript重定向URL [英] JavaScript redirect URL with Authorization header
问题描述
我设法成功调用了Apache中受基本身份验证(htpasswd等)保护的目录后面的URL. Ajax GET请求正常工作并返回受保护的内容:
I managed to successfully invoke a URL behind a directory in Apache that is protected with Basic Authentication (htpasswd, etc.). The Ajax GET request works normally and returns the protected content:
var encoded = Base64.encode(username + ':' + password);
$.ajax({
url: "/app/test",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + encoded);
},
success: function() {
window.location.href = '/app/test.html';
}
});
我最初的假设是,一旦Web会话成功授权了请求,便可以在不询问用户凭据的情况下在成功"块中进行重定向.调用此代码块时,用户已在非保护环境中输入了用户名和密码.但是,在调用重定向时,浏览器将弹出登录名/密码窗口.
My original assumption was that once the web session had successfully authorized a request, it would make possible the redirection in the 'success' block without asking user credentials. When this code block is invoked, the user had entered username and password, in a non-protected environment. However, when the redirect is invoked, the browser will popup the the login/password window.
关于我可以如何使用用户预先提供的基本授权对会话进行预授权的任何建议?
Any suggestions on how I could pre-authorize a session with the Basic Authorization which would have been provided by the users?
推荐答案
使用AJAX请求登录通常可以正常工作,因为成功的AJAX请求会设置会话cookie,该会话cookie将透明地在所有后续请求中发送.
Logging with AJAX request usually works because a successful AJAX request sets session cookies that will be sent in all subsequent requests transparently.
也许您的cookie被设置了,但是由于某些原因却没有被透明设置:您可以使用xhr.getAllResponseHeaders()/xhr.getResponseHeader()进行检查,然后再使用document.cookie对其进行设置.
Maybe your cookies are set but for some reason are not set transparently: you can check with xhr.getAllResponseHeaders() / xhr.getResponseHeader() and after that set them with document.cookie.
如果没有会话cookie,则此行为通常会失败.
If no session cookies, then this behaviour usually fails.
您可以尝试使用url中的用户名+密码进行重定向(不建议使用,因为用户名+密码之后可能会在浏览器地址的URL栏中显示):
You can try to redirect with the username+password in the url (not recommended because username+password probably will be visible in the browser address url bar afterwards):
window.location.href =
window.location.protocol + "//" +
username + ":" + password + "@" +
window.location.hostname +
(window.location.port ? ":" + window.location.port : "") +
'/app/test.html';
另外,您应该测试一下以延迟重定向...,因为它可能正在工作,但是您需要给浏览器一些额外的时间,您是否尝试过:
Also you should test to delay the redirection... because maybe it's working but you need to give some extra time to the browser, did you try:
var encoded = Base64.encode(username + ':' + password);
$.ajax({
url: "/app/test",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + encoded);
},
success: function() {
setTimeout(function() {
window.location.href = '/app/test.html';
}, 333);
}
});
这篇关于具有Authorization标头的JavaScript重定向URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!