开发者

basic http auth via ajax and php

I'm trying to make a http basic auth via ajax.

    $.ajax({
        url: 'secure/index.php',
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Authorization", "Basic " + Base64.encode("user" + ":" + "password") //May need to use "Authorization" instead
        },
        success: function(result) {
         开发者_JS百科   alert(result);
        },
        error:function (xhr, ajaxOptions, throwBnError){
            alert(xhr);
            alert(thrownError);
        }  

Ok. The problem is that I don't use any .htaccess file to do the HTTP auth.

I have a simple PHP file where this make the authentication:

header('WWW-Authenticate: Basic realm="Secret page"');
header('HTTP/1.0 401 Unauthorized');

And my ajax request does not want to work..

What am I doing wrong?


I had a similar problem before; try adding this function to your php authentication file

function http_auth_get($url,$username,$password){
$cred = sprintf('Authorization: Basic %s',
base64_encode("$username:$password") );
$opts = array(
    'http'=>array(
            'method'=>'GET',
            'header'=>$cred
        )
);
$ctx = stream_context_create($opts);
$handle = @fopen($url, 'r', false,$ctx);

 if (!$handle) {         
      die($http_response_header[0]);
 }

return stream_get_contents($handle);
}

you can use the function as follows:

$return = http_auth_get(http://example.com,user,pass);

how you use the $return variable depends on what you are trying to access


Have you tried using the username and password fields in .ajax?

$.ajax({
    url: "http://mydomain/mypage.php",
    username: u,
    password: p,
    error: function () {
    }
}).done(function(html) {
        //Do Stuff
});

This works for me almost all of the time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜