我试图通过浏览器创建一个基本的身份验证,但我真的无法到达那里。
如果这个脚本不在这里,浏览器将接管身份验证,但我想告诉浏览器用户即将进行身份验证。
地址应该是这样的:
http://username:password@server.in.local/
我有一个表格:
<form name="cookieform" id="login" method="post">
<input type="text" name="username" id="username" class="text"/>
<input type="password" name="password" id="password" class="text"/>
<input type="submit" name="sub" value="Submit" class="page"/>
</form>
还有一个脚本:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{"username": "' + username + '", "password" : "' + password + '"}',
success: function (){
alert('Thanks for your comment!');
}
});
根据SharkAlley的回答,它也适用于nginx。
我正在寻找一种解决方案,通过jQuery从nginx后面的服务器获取数据,并受到Base Auth的限制。这对我来说很管用:
server {
server_name example.com;
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
# Not necessary
# add_header Access-Control-Allow-Credentials "true";
# add_header Content-Length 0;
# add_header Content-Type text/plain;
return 200;
}
auth_basic "Restricted";
auth_basic_user_file /var/.htpasswd;
proxy_pass http://127.0.0.1:8100;
}
}
JavaScript代码是:
var auth = btoa('username:password');
$.ajax({
type: 'GET',
url: 'http://example.com',
headers: {
"Authorization": "Basic " + auth
},
success : function(data) {
},
});
我觉得有用的文章:
这个话题的答案
http://enable-cors.org/server_nginx.html
http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method/
使用beforeSend回调函数添加一个带有认证信息的HTTP头,如下所示:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth(username, password));
},
success: function (){
alert('Thanks for your comment!');
}
});