What is HTTP Basic authentication? Look directly at http://en.wikipedia.org/wiki/Basic_authentication_scheme .
when you visit a URL that requires HTTP Basic authentication, if you do not provide a username and password, the server returns 401 if you open it directly in the browser, The browser will prompt you to enter your username and password (Google Chrome won't, bug?). )。 You can try clicking this URL to see the effect:http://api.minicloud.com.cn/statuses/friends_timeline.xml
There are two ways to add HTTP Basic authentication authentication information to the request when sending the request:
- One is to add authorization to the request header:
Authorization: "Basic user name and password base64 encrypted string"
- The second is to add the user name and password in the URL:
HTTP/Username:[email protected]Api.minicloud.com.cn/statuses/friends_timeline.xml
Here's a look at the implementation code for the first various languages that add authorization headers to the request.
1.. NET
stringUsername="username";stringpassword="Password";//Note The format here, for "Username:password"stringUsernamepassword = Username +":"+password; CredentialCache Mycache=NewCredentialCache (); Mycache. ADD (NewUri (URL),"Basic",Newnetworkcredential (username, password)); Myreq.credentials=Mycache;myreq.headers.add ("Authorization","Basic"+ convert.tobase64string (Newasciiencoding (). GetBytes (Usernamepassword)); WebResponse WR=Myreq.getresponse (); Stream Receivestream=WR. GetResponseStream (); StreamReader Reader=NewStreamReader (Receivestream, Encoding.UTF8);stringContent = Reader. ReadToEnd ();
You can of course use HttpWebRequest or other classes to send requests.
2, Python's
ImportUrllib2ImportSYSImportReImportBase64 fromUrlparseImportUrlparse theURL='Http://api.minicloud.com.cn/statuses/friends_timeline.xml'username='Qleelulu'Password='XXXXXX' #Do you believe this is a code? base64string=base64.encodestring ('%s:%s'% (username, password)) [:-1]#Note that the last one here will automatically add a \ nAuthheader ="Basic%s"%Base64stringreq.add_header ("Authorization", Authheader)Try: Handle=Urllib2.urlopen (req)exceptIOError, E:#Here we shouldn ' t fail if the Username/password are right Print "It looks like the username or password is wrong."Sys.exit (1) thepage= Handle.read ()
3, PHP's
<? PHP $fp Fsockopen ("www.mydomain.com"); fputs ($fp, "Get/downloads http/1.0"); fputs ($fp, "Host:www.mydomain.com"); fputs ($fpbase64_encode("User:pass"). ""); Fpassthru ($fp);? >
4, flash of the AS3
Import Mx.rpc.events.faultevent;import Mx.rpc.events.resultevent;import mx.utils.base64encoder;import Mx.rpc.http.HTTPService; Urlrequestdefaults.authenticate=false;//set default to False, or the validation box will pop up if the user is more error-proofPrivate varResult:xml;Privatefunction Initapp ():void{ varBase64enc:base64encoder =NewBase64encoder; Base64enc.encode ("User:password");//user name and password require BASE64 encoding varUser:string =base64enc.tostring (); varHttp:httpservice =NewHttpservice; Http.addeventlistener (Resultevent.result,resulthandler);//Listen for return eventsHttp.addeventlistener (Faultevent.fault,faulthandler);//Listen for failed eventsHttp.resultformat ="e4x";//return FormatHttp.url ="Http://api.digu.com/statuses/friends_timeline.xml"http.headers the API for muttering Web= {"Authorization":"Basic"+user}; Http.send ();}Privatefunction Resulthandler (e:resultevent):void{result=XML (E.result); Test.dataprovider= Result.status;//binding Data}Privatefunction Faulthandler (e:resultevent):void{ //processing failed}
5, Ruby on Rails
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 was 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 EndEnd
6. javascript
// need Base64 see: http://www.cnblogs.com/pingming/p/4165063.html
functionmake_base_auth (user, password) {varTok = user + ': ' +Pass; varhash =Base64.encode (Tok); return"Basic" +Hash;} varAuth = Make_basic_auth (' Qleelulu ', ' MyPassword ');varurl = ' http://example.com '; //original JavaScriptXML =NewXMLHttpRequest (); Xml.setrequestheader (' Authorization ', auth); Xml.open (' GET ', URL)//ExtJSExt.Ajax.request ({url:url, method:' GET ', headers: {Authorization:auth}}); //JQuery$.ajax ({url:url, method:' GET ', Beforesend:function(req) {Req.setrequestheader (' Authorization ', auth); }});
Alert, HTTP Basic authentication is not possible with JavaScript for cross-domain and POST requests (note: For Chrome plugins that allow access to cross-domain resources through AJAX, it is possible)
Access to the implementation of various development languages that require HTTP Basic authentication Certified Resources