Sending basic authentication information via form

隐身守侯 提交于 2019-11-28 07:36:14

After a fair bit of research I found a way that works in both Chrome and IE, that is all that I've tested it in, but the logic of the code does not suggest it should break anywhere. It is based upon this article:

http://www.peej.co.uk/articles/http-auth-with-html-forms.html

Which is rather in depth but the crux of it is this - on the form submit you make an AJAX request into the basic authenticated folder. AJAX requests can accept username and password information for basic auth, and once the browser has authed once it's authorised in that realm, i.e. it will stay logged in. The previous article does it in pure javascript, so to add something other than simply explaining the link here's a (hopefully fairly transparent) implementation using jQuery:

  $(document).ready(function()
  {
    $('#loginForm').submit(function()
    {
      var username = $('#usernameInput').val();
      var password = $('#passwordInput').val();

      $.ajax(
        {
          'password' : password,
          'username' : username,
          'url'      : 'http://www.website.com/basic-auth-file.php',
          'type'     : 'GET',
          'success'  : function(){ window.location = 'http://www.website.com/basic-auth-file.php'; },
          'error'    : function(){ alert('Bad Login Details');},
        }
      );

      return false;
    });
  });

This achieved what I wanted, and is relatively simple to understand, however I would implore anyone who wanted this to go out and didn't know about basic auth to go out and do the research!

You can replace it with a form. http://www.dur.ac.uk/vm.boatclub/password/index.php uses basic access authentication.

basic access authentication

What you could do is perform basic authentication via curl

<?php 
// HTTP authentication 
$url = "http://www.dur.ac.uk/vm.boatclub/password/index.php"; 
$ch = curl_init();     
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
curl_setopt($ch, CURLOPT_URL, $url);  
curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword");  
$result = curl_exec($ch);  
curl_close($ch);  
//echo $result; 
?> 

Option 1

Proxy everything just echo'ing $result

Option 2

Read headers from $result and if status code != 200 then wrong login information has been entered. User should enter form again. If status code == 200 right credentials have been entered and you should do http basic authentication by sending headers.

header("Authorization: Basic " . base64_encode($username . ":" . $password);

You should not echo any data($result) before sending header else you will get an error

Some quick links:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!