jQuery 如何为基本身份验证发送正确的授权标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18264601/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:17:42  来源:igfitidea点击:

How to send a correct authorization header for basic authentication

jqueryajaxdjangoapicross-domain

提问by individuo7

I am trying to POST data from my API but I can't pass the basic authentication.

我正在尝试从我的 API POST 数据,但我无法通过基本身份验证。

I try:

我尝试:

$.ajax({
  type: 'POST',
  url: http://theappurl.com/api/v1/method/,
  data: {},
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic ZWx1c3VhcmlvOnlsYWNsYXZl');
  }
});

My server configuration response is:

我的服务器配置响应是:

response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "POST"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "*"

The headers that I get is:

我得到的标题是:

Request Headers

请求头

OPTIONS /api/v1/token-auth/ HTTP/1.1
Host: theappurl.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://127.0.0.1:8080
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31
Access-Control-Request-Headers: origin, authorization, content-type
Accept: */*
Referer: http://127.0.0.1:8080/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: es,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Response header

响应头

HTTP/1.1 401 Unauthorized
Server: nginx/1.1.19
Date: Fri, 16 Aug 2013 01:29:21 GMT
Content-Type: text/html
Content-Length: 597
Connection: keep-alive
WWW-Authenticate: Basic realm="Restricted"

I guess the server configuration is good because I can access to API from the Advanced REST Client(Chrome Extension)

我猜服务器配置很好,因为我可以从高级 REST 客户端(Chrome 扩展程序)访问 API

Any suggestions?

有什么建议?

PD: The header that I get from Advanced REST client is:

PD:我从 Advanced REST 客户端获得的标头是:

    User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31
    Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
    Authorization: Basic ZWx1c3VhcmlvOnlsYWNsYXZl
    Content-Type: application/x-www-form-urlencoded 
    Accept: */*
    Accept-Encoding: gzip,deflate,sdch
    Accept-Language: es,en;q=0.8
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

and

    Server: nginx/1.1.19 
    Date: Fri, 16 Aug 2013 01:07:18 GMT 
    Content-Type: application/json; charset=utf-8 
    Transfer-Encoding: chunked 
    Connection: keep-alive
    Vary: Accept, Cookie 
    Allow: POST, OPTIONS 
    X-Robots-Tag: noindex

sending OPTION method

发送 OPTION 方法

采纳答案by Dru

You can include the user and password as part of the URL:

您可以将用户和密码包含在 URL 中:

http://user:[email protected]/index.html

see this URL, for more

查看此 URL,了解更多信息

HTTP Basic Authentication credentials passed in URL and encryption

在 URL 和加密中传递的 HTTP 基本身份验证凭据

of course, you'll need the username password, it's not 'Basic hashstring.

当然,您需要用户名密码,而不是'Basic hashstring

hope this helps...

希望这可以帮助...

回答by seanp2k

Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decodingand http://en.wikipedia.org/wiki/Basic_access_authentication, here is how to do Basic auth with a header instead of putting the username and password in the URL. Note that this still doesn't hide the username or password from anyone with access to the network or this JS code (e.g. a user executing it in a browser):

根据https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decodinghttp://en.wikipedia.org/wiki/Basic_access_authentication,这里是如何使用标头进行基本身份验证将用户名和密码放在 URL 中。请注意,这仍然不会对任何有权访问网络或此 JS 代码的人(例如,在浏览器中执行它的用户)隐藏用户名或密码:

$.ajax({
  type: 'POST',
  url: http://theappurl.com/api/v1/method/,
  data: {},
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(unescape(encodeURIComponent(YOUR_USERNAME + ':' + YOUR_PASSWORD))))
  }
});

回答by jakub.g

NodeJS answer:

NodeJS 答案:

In case you wanted to do it with NodeJS: make a GET to JSON endpoint with Authorizationheader and get a Promiseback:

如果你想用 NodeJS 来做这件事:用Authorization头做一个 GET 到 JSON 端点并得到一个Promise返回:

First

第一的

npm install --save request request-promise

(see on npm) and then in your .jsfile:

参见 npm),然后在您的.js文件中:

var requestPromise = require('request-promise');

var user = 'user';
var password = 'password';

var base64encodedData = new Buffer(user + ':' + password).toString('base64');

requestPromise.get({
  uri: 'https://example.org/whatever',
  headers: {
    'Authorization': 'Basic ' + base64encodedData
  },
  json: true
})
.then(function ok(jsonData) {
  console.dir(jsonData);
})
.catch(function fail(error) {
  // handle error
});

回答by fernandohur

If you are in a browser environment you can also use btoa.

如果您在浏览器环境中,也可以使用btoa

btoais a function which takes a string as argument and produces a Base64 encoded ASCII string. Its supported by 97% of browsers.

btoa是一个将字符串作为参数并生成 Base64 编码的 ASCII 字符串的函数。97% 的浏览器都支持它。

Example:

例子:

> "Basic " + btoa("billy"+":"+"secretpassword")
< "Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ="

You can then add Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ=to the authorizationheader.

然后您可以添加Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ=authorization标题。

Note that the usual caveats about HTTP BASIC auth apply, most importantly if you do not send your traffic over https an eavesdropped can simply decode the Base64 encoded string thus obtaining your password.

请注意,有关 HTTP BASIC 身份验证的常见警告适用,最重要的是,如果您不通过 h​​ttps 发送流量,窃听者可以简单地解码 Base64 编码字符串,从而获取您的密码。

This security.stackexchange.comanswer gives a good overview of some of the downsides.

这个 security.stackexchange.com答案很好地概述了一些缺点。

回答by erhanck

no need to use user and password as part of the URL

无需使用用户名和密码作为 URL 的一部分

you can try this

你可以试试这个

byte[] encodedBytes = Base64.encodeBase64("user:passwd".getBytes());

String USER_PASS = new String(encodedBytes);

HttpUriRequest request = RequestBuilder.get(url).addHeader("Authorization", USER_PASS).build();