我有一个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平台发送get请求,我试过这个:
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请求。
答案 0 :(得分:0)
这有效
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