dsoihsnz85757 2015-10-26 15:05
浏览 87
已采纳

rails如何使用http身份验证将http请求发送到php文件

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.

  • 写回答

1条回答 默认 最新

  • duanbiao4035 2015-10-26 15:24
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 代写个MATLAB代码,有偿
  • ¥15 ansys electronics 2021 R1安装报错,错误代码2,如图
  • ¥30 搭建面包板由NE555N和SN74LS90N组成的计时电路时出了问题
  • ¥15 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误