Search code examples
phpruby-on-railshttp-authentication

rails how to send http request with http authentication to a php file


I have a php file test.php which created HTTP Auth.

$valid_passwords = array ("test" => "test123");
        $valid_users = array_keys($valid_passwords);

        $user = $_SERVER['PHP_AUTH_USER'];
        $pass = $_SERVER['PHP_AUTH_PW'];

        $validated = (in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]);

        if (!$validated) {
          header('WWW-Authenticate: Basic realm="My Realm"');
          header('HTTP/1.0 401 Unauthorized');
          die ("Not authorized");
        }

        // If arrives here, is a valid user.
        echo "<p>Welcome $user.</p>";
        echo "<p>Congratulation, you are into the system.</p>";
            }

Now I want to visit that test.php and send a get request there from a rails platform, I have tried this:

url = 'http://url/test.php'
        uri = URI.parse(url)
        http = Net::HTTP.new(uri.host, uri.port)
        request = Net::HTTP::Get.new(uri.path,'Authorization' => "test test123")
        response = http.request(request)
        render :text => response.body

It doesn't work, says unauthorized. I can do changes in PHP as well as Rails, I just need a secure way to make http requests between the two.


Solution

  • This worked

    url = 'http://url'
            uri = URI.parse(url)
            http = Net::HTTP.new(uri.host, uri.port)
            request = Net::HTTP::Get.new(uri.path, 'Content Type' => 'application/json')
            request.basic_auth("test", "test123")
            response = http.request(request)
            render :text => response.body
    

    thanks to MarcB