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

时间:2013-08-16 01:49:30

标签: jquery ajax django api cross-domain

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

我试试:

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

我的服务器配置响应是:

response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "POST"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-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

回复标题

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"

我想服务器配置很好,因为我可以从 Advanced REST Client (Chrome扩展程序)访问API

有什么建议吗?

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

    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

发送OPTION方法

6 个答案:

答案 0 :(得分:63)

Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decodinghttp://en.wikipedia.org/wiki/Basic_access_authentication,以下是如何使用标头执行Basic auth而不是将用户名和密码放在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))))
  }
});

答案 1 :(得分:43)

您可以在网址中包含用户和密码:

http://user:passwd@www.server.com/index.html

请参阅此网址,了解更多信息

HTTP Basic Authentication credentials passed in URL and encryption

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

希望这会有所帮助...

答案 2 :(得分:29)

NodeJS回答:

如果您想使用NodeJS执行此操作:使用Authorization标头创建GET到JSON端点并返回Promise

第一

npm install --save request request-promise

see on 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
});

答案 3 :(得分:5)

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

btoa是一个函数,它将一个字符串作为参数并生成一个Base64编码的ASCII字符串。它由97% of browsers支持。

示例:

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

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

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

This security.stackexchange.com回答很好地概述了一些缺点。

答案 4 :(得分:3)

无需使用用户和密码作为网址的一部分

你可以试试这个

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

String USER_PASS = new String(encodedBytes);

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

答案 5 :(得分:0)

PHP - curl

$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...

PHP - 在 WordPress 中发布

$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
  'headers' => array(
    'Authorization' => 'Basic ' . base64_encode("$username:$password")
  )
));
...