rails 如何将带有 http 身份验证的 http 请求发送到 php 文件

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

我有一个 php 文件 test.php,它创建了 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>";
            }

现在我想访问那个 test.php 并从 rails 平台向那里发送一个获取请求,我试过这个:

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

它不起作用,说未经授权。 我可以在 PHP 和 Rails 中进行更改,我只需要一种在两者之间发出 http 请求的安全方法。

这有效

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

感谢 MarcB