訪問需要HTTP Basic Authentication認證的資源的各種語言的實現
阿新 • • 發佈:2019-01-03
無聊想呼叫下嘀咕的api的時候,發現需要HTTP Basic Authentication,就看了下。
在你訪問一個需要HTTP Basic Authentication的URL的時候,如果你沒有提供使用者名稱和密碼,伺服器就會返回401,如果你直接在瀏覽器中開啟,瀏覽器會提示你輸入使用者名稱 和密碼(google瀏覽器不會,bug?)。你可以嘗試點選這個url看看效果:http://api.minicloud.com.cn/statuses/friends_timeline.xml
要在傳送請求的時候新增HTTP Basic Authentication認證資訊到請求中,有兩種方法:
下面來看下對於第一種在請求中新增Authorization頭部的各種語言的實現程式碼。
先看.NET的吧:
Java程式碼- string username="username";
- string password="password";
- //注意這裡的格式哦,為 "username:password"
- string usernamePassword = username + ":" + password;
- CredentialCache mycache = new CredentialCache();
-
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
- myReq.Credentials = mycache;
- myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
- WebResponse wr = myReq.GetResponse();
- Stream receiveStream = wr.GetResponseStream();
-
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
- string content = reader.ReadToEnd();
你當然也可以使用HttpWebRequest或者其他的類來發送請求。
然後是Python的:
Java程式碼- import urllib2
- import sys
- import re
- import base64
- from urlparse import urlparse
- theurl = 'http://api.minicloud.com.cn/statuses/friends_timeline.xml'
- username = 'qleelulu'
- password = 'XXXXXX' # 你信這是密碼嗎?
- base64string = base64.encodestring(
- '%s:%s' % (username, password))[:-1] #注意哦,這裡最後會自動新增一個\n
- authheader = "Basic %s" % base64string
- req.add_header("Authorization", authheader)
- try:
- handle = urllib2.urlopen(req)
- except IOError, e:
- # here we shouldn't fail if the username/password is right
- print "It looks like the username or password is wrong."
- sys.exit(1)
- thepage = handle.read()
再來是PHP的:
Java程式碼- <?php
- $fp = fsockopen("www.mydomain.com",80);
- fputs($fp,"GET /downloads HTTP/1.0");
- fputs($fp,"Host: www.mydomain.com");
- fputs($fp,"Authorization: Basic " . base64_encode("user:pass") . "");
- fpassthru($fp);
- ?>
還有flash的AS3的:
Java程式碼- import mx.rpc.events.FaultEvent;
- import mx.rpc.events.ResultEvent;
- import mx.utils.Base64Encoder;
- import mx.rpc.http.HTTPService;
- URLRequestDefaults.authenticate = false;//設預設為false,否則使用者較驗錯誤時會彈出驗證框
- private var result:XML;
- private function initApp():void
- {
- var base64enc:Base64Encoder = new Base64Encoder;
- base64enc.encode("user:password"); //使用者名稱和密碼需要Base64編碼
- var user:String = base64enc.toString();
- var http:HTTPService = new HTTPService;
- http.addEventListener(ResultEvent.RESULT,resultHandler);//監聽返回事件
- http.addEventListener(FaultEvent.FAULT,faultHandler); //監聽失敗事件
- http.resultFormat = "e4x";//返回格式
- http.url = "http://api.digu.com/statuses/friends_timeline.xml"; 以嘀咕網的API為列
- http.headers = {"Authorization":"Basic " + user};
- http.send();
- }
- private function resultHandler(e:ResultEvent):void
- {
- result = XML(e.result);
- test.dataProvider = result.status;//繫結資料
- }
- private function faultHandler(e:ResultEvent):void
- {
- //處理失敗
- }
還有Ruby On Rails的:
Java程式碼- class DocumentsController < ActionController
- before_filter :verify_access
- def show
- @document = @user.documents.find(params[:id])
- end
- # Use basic authentication in my realm to get a user object.
- # Since this is a security filter - return false if the user is not
- # authenticated.
- def verify_access
- authenticate_or_request_with_http_basic("Documents Realm") do |username, password|
- @user = User.authenticate(username, password)
- end
- end
- end
JavaScript的:
Java程式碼- //需要Base64見:http://www.webtoolkit.info/javascript-base64.html
- function make_base_auth(user, password) {
- var tok = user + ':' + pass;
- var hash = Base64.encode(tok);
- return "Basic " + hash;
- }
- var auth = make_basic_auth('QLeelulu','mypassword');
- var url = 'http://example.com';
- // 原始JavaScript
- xml = new XMLHttpRequest();
- xml.setRequestHeader('Authorization', auth);
- xml.open('GET',url)
- // ExtJS
- Ext.Ajax.request({
- url : url,
- method : 'GET',
- headers : { Authorization : auth }
- });
- // jQuery
- $.ajax({
- url : url,
- method : 'GET',
- beforeSend : function(req) {
- req.setRequestHeader('Authorization', auth);
- }
- });
這裡提醒下,HTTP Basic Authentication對於跨域又要傳送post請求的用JavaScript是實現不了的(注:對於Chrome外掛這類允許通過AJAX訪問跨域資源的,是可以的)。