기본 인증을 위해 올바른 인증 헤더를 보내는 방법
API에서 데이터를 POST하려고하는데 기본 인증을 통과 할 수 없습니다.
나는 시도한다 :
$.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 Extension) 에서 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 방법 보내기
URL의 일부로 사용자 및 비밀번호를 포함 할 수 있습니다.
http://user:passwd@www.server.com/index.html
자세한 내용은이 URL을 참조하십시오.
URL 및 암호화로 전달 된 HTTP 기본 인증 자격 증명
물론 사용자 이름 암호가 필요합니다 'Basic hashstring
.
도움이 되었기를 바랍니다...
Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding and 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):
$.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))))
}
});
NodeJS answer:
In case you wanted to do it with NodeJS: make a GET to JSON endpoint with Authorization
header and get a Promise
back:
First
npm install --save request request-promise
(see on npm) and then in your .js
file:
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
});
If you are in a browser environment you can also use btoa.
btoa
is a function which takes a string as argument and produces a Base64 encoded ASCII string. Its supported by 97% of browsers.
Example:
> "Basic " + btoa("billy"+":"+"secretpassword")
< "Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ="
You can then add Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ=
to the authorization
header.
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.
This security.stackexchange.com answer gives a good overview of some of the downsides.
no need to use user and password as part of the 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();
'development' 카테고리의 다른 글
잘못된 http_host 헤더 (0) | 2020.09.03 |
---|---|
Photos.app에서 이미지를 업로드하는 모바일 사파리 용 html5 웹 앱? (0) | 2020.09.03 |
HTML 레이블의 "For"속성 관련 (0) | 2020.09.03 |
javax.net.ssl.SSLHandshakeException 오류를 해결하는 방법? (0) | 2020.09.03 |
MemoryCache.Add와 MemoryCache.Set의 차이점은 무엇입니까? (0) | 2020.09.03 |