Javascript 通过 jQuery 和 Ajax 使用基本身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5507234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use basic authentication with jQuery and Ajax
提问by Patrioticcow
I am trying to create a basic authentication through the browser, but I can't really get there.
我正在尝试通过浏览器创建基本身份验证,但我无法真正到达那里。
If this script won't be here the browser authentication will take over, but I want to tell the browser that the user is about to make the authentication.
如果此脚本不在此处,浏览器身份验证将接管,但我想告诉浏览器用户即将进行身份验证。
The address should be something like:
地址应该是这样的:
http://username:[email protected]/
I have a form:
我有一个表格:
<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>
And a script:
还有一个脚本:
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!');
}
});
回答by ggarber
Use jQuery's beforeSend
callback to add an HTTP header with the authentication information:
使用 jQuery 的beforeSend
回调添加带有身份验证信息的 HTTP 标头:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
回答by jmanning2k
How things change in a year. In addition to the header attribute in place of xhr.setRequestHeader
, current jQuery (1.7.2+) includes a username and password attribute with the $.ajax
call.
一年之内情况如何变化。除了代替 的 header 属性之外xhr.setRequestHeader
,当前的 jQuery (1.7.2+) 在$.ajax
调用中还包含用户名和密码属性。
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
username: username,
password: password,
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
EDIT from comments and other answers: To be clear - in order to preemptively send authentication without a 401 Unauthorized
response, instead of setRequestHeader
(pre -1.7) use 'headers'
:
从评论和其他答案中编辑:要明确 - 为了在没有401 Unauthorized
响应的情况下抢先发送身份验证,而不是setRequestHeader
(-1.7 之前)使用'headers'
:
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
headers: {
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
},
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
回答by Adrian Toman
Use the beforeSend callbackto add a HTTP header with the authentication information like so:
使用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!');
}
});
回答by AsemRadhwi
Or, simply use the headers property introduced in 1.5:
或者,只需使用 1.5 中引入的 headers 属性:
headers: {"Authorization": "Basic xxxx"}
Reference: jQuery Ajax API
回答by Paul Odeon
The examples above are a bit confusing, and this is probably the best way:
上面的例子有点混乱,这可能是最好的方法:
$.ajaxSetup({
headers: {
'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
}
});
I took the above from a combination of Rico and Yossi's answer.
我从 Rico 和 Yossi 的回答中综合了上述内容。
回答by SharkAlley
As others have suggested, you can set the username and password directly in the Ajax call:
正如其他人所建议的,您可以直接在 Ajax 调用中设置用户名和密码:
$.ajax({
username: username,
password: password,
// ... other parameters.
});
ORuse the headers property if you would rather not store your credentials in plain text:
或者,如果您不想以纯文本形式存储凭据,请使用 headers 属性:
$.ajax({
headers: {"Authorization": "Basic xxxx"},
// ... other parameters.
});
Whichever way you send it, the server has to be very polite. For Apache, your .htaccess file should look something like this:
无论您以哪种方式发送,服务器都必须非常有礼貌。对于 Apache,您的 .htaccess 文件应如下所示:
<LimitExcept OPTIONS>
AuthUserFile /path/to/.htpasswd
AuthType Basic
AuthName "Whatever"
Require valid-user
</LimitExcept>
Header always set Access-Control-Allow-Headers Authorization
Header always set Access-Control-Allow-Credentials true
SetEnvIf Origin "^(.*?)$" origin_is=$.ajaxSetup({
headers: {
'Authorization': "Basic XXXXX"
}
});
Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is
Explanation:
解释:
For some cross domain requests, the browser sends a preflight OPTIONSrequest that is missing your authentication headers. Wrap your authentication directives inside the LimitExcepttag to respond properly to the preflight.
对于某些跨域请求,浏览器会发送缺少身份验证标头的预检OPTIONS请求。将您的身份验证指令包装在LimitExcept标签内以正确响应预检。
Then send a few headers to tell the browser that it is allowed to authenticate, and the Access-Control-Allow-Originto grant permission for the cross-site request.
然后发送一些标头告诉浏览器允许进行身份验证,并发送 Access-Control-Allow-Origin来授予跨站点请求的权限。
In some cases, the * wildcard doesn't workas a value for Access-Control-Allow-Origin: You need to return the exact domain of the callee. Use SetEnvIf to capture this value.
在某些情况下,* 通配符不能作为 Access-Control-Allow-Origin 的值:您需要返回被调用者的确切域。使用 SetEnvIf 来捕获这个值。
回答by Yossi Shasho
Use the jQuery ajaxSetupfunction, that can set up default values for all ajax requests.
使用jQuery ajaxSetup函数,可以为所有 ajax 请求设置默认值。
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
headers: {
"Authorization": "Basic " + btoa(uName+":"+passwrd);
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
回答by arnebert
JSONPdoes not work with basic authentication so the jQuery beforeSend callback won't work with JSONP/Script.
JSONP不适用于基本身份验证,因此 jQuery beforeSend 回调不适用于 JSONP/Script。
I managed to work around this limitation by adding the user and password to the request (e.g. user:[email protected]). This works with pretty much any browser except Internet Explorerwhere authentication through URLs is not supported (the call will simply not be executed).
我设法通过向请求添加用户和密码来解决这个限制(例如 user:[email protected])。这适用于除 Internet Explorer 之外的几乎所有浏览器,其中不支持通过 URL 进行身份验证(调用将不会被执行)。
回答by GSB
There are 3 ways to achieve this as shown below
有3种方法可以实现这一点,如下所示
Method 1:
方法一:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName+":"+passwrd));
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 2:
方法二:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
username:uName,
password:passwrd,
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 3:
方法三:
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;
}
}
回答by Maks
According to SharkAlley answer it works with nginx too.
根据 SharkAlley 的回答,它也适用于 nginx。
I was search for a solution to get data by jQuery from a server behind nginx and restricted by Base Auth. This works for me:
我正在寻找一种解决方案,通过 jQuery 从 nginx 后面的服务器获取数据,并受 Base Auth 限制。这对我有用:
var auth = btoa('username:password');
$.ajax({
type: 'GET',
url: 'http://example.com',
headers: {
"Authorization": "Basic " + auth
},
success : function(data) {
},
});
And the JavaScript code is:
JavaScript 代码是:
##代码##Article that I find useful:
我觉得有用的文章: