HTTP Basic authentication certified for various languages backstage

Source: Internet
Author: User
Tags base64 ruby on rails

Access to the implementation of various languages that require HTTP Basic authentication Certified Resources

Bored to invoke the next muttered API, found the need for HTTP Basic authentication, looked at the next.

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 user name and password, the server will return 401, if you open directly in the browser, the browser will prompt you to enter the user name and password (Google browser does not, 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]/statuses/friends_timeline.xml

Here's a look at the implementation code for the first various languages that add authorization headers to the request.

Look first. NET's Bar:

String username= "username";
String password= "password";
Note The format here, for "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 ();

You can of course use HttpWebRequest or other classes to send requests.

Then it's python:

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 ' # Do you believe this is a code?

base64string = base64.encodestring (
'%s:%s '% (username, password)) [: -1] #注意哦, this will automatically add a \ 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 are right
Print "It looks like the username or password is wrong."
Sys.exit (1)
thepage = Handle.read ()

Again, it's PHP:

<?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);
?>

And the AS3 of Flash:

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, otherwise the user will pop up the verification box when the error

private Var Result:xml;
Private Function Initapp (): void
{
var base64enc:base64encoder = new Base64encoder;
Base64enc.encode ("User:password"); User name and password require BASE64 encoding
var user:string = base64enc.tostring ();

var http:httpservice = new Httpservice;
Http.addeventlistener (Resultevent.result,resulthandler);//Listener return Event
Http.addeventlistener (Faultevent.fault,faulthandler); Listen for failed events
Http.resultformat = "e4x";//Return format
Http.url = "Http://api.digu.com/statuses/friends_timeline.xml"; With a muttered Web API as a column
Http.headers = {"Authorization": "Basic" + user};
Http.send ();
}
Private Function Resulthandler (e:resultevent): void
{
result = XML (E.result);
Test.dataprovider = result.status;//binding Data
}
Private Function Faulthandler (e:resultevent): void
{
Processing failed
}

and 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 is a security filter-return false if the user was not
# authenticated.
def verify_access
Authenticate_or_request_with_http_basic ("Documents Realm") do |username, password|
@user = user.authenticate (username, password)
End
End
End

Khan, forget the javascript:

Need Base64 See: 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 ';

Original 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);
}
});

Here's a reminder that HTTP Basic authentication is not possible with JavaScript for cross-domain and POST requests (note: For Chrome plug-ins This class allows access to cross-domain resources through Ajax).

HTTP Basic authentication authentication for various languages for background use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.