简体   繁体   English

Luracast Restler身份验证

[英]Luracast Restler Authentication

I'm using Luracast restler and i'm trying to implement some authentication by implementing iAuthenticate interface. 我正在使用Luracast restler,我正在尝试通过实现iAuthenticate接口来实现一些身份验证。

The thing is, my authentication code needs to query my database to retrieve the user private key. 问题是,我的身份验证代码需要查询我的数据库以检索用户私钥。 This private key will always be provided in the url request (hashed). 该私钥将始终在url请求中提供(散列)。

I wanted to open just one database connection to each request, so i need to pass the db connection variable to my class that implements iAuthenticate and to the other classes that handle all the requests. 我想打开每个请求的一个数据库连接,所以我需要将db连接变量传递给实现iAuthenticate的类和处理所有请求的其他类。 But i can't figure out how can i pass variables to my class that implements iAuthenticate. 但我无法弄清楚如何将变量传递给实现iAuthenticate的类。

Is it possible? 可能吗?

For reference, here are the luracast examples 作为参考,这里是luracast示例

thks in advance. 事先说。

Using Single DB Connection for your API and Authentication Classes 为您的API和身份验证类使用单个数据库连接

Create a php file called config.php and place all your db information along with db connection and selection. 创建一个名为config.php的php文件,并将所有数据库信息与数据库连接和选择一起放置。

For example 例如

<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'mysql_db');
//initalize connection to use everywhere
//including auth class and api classes
mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME);

Include this function using require_once on both Authentication class and API class, something like (for simplicity I'm not encrypting the password here) 在Authentication类和API类上使用require_once包含此函数,类似于(为简单起见,我不在此处加密密码)

<?php
require_once 'config.php';
class BasicAuthentication implements iAuthenticate{
    const REALM = 'Restricted API';
    public static $currentUser;

    function __isAuthenticated(){
        if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){
            $user = $_SERVER['PHP_AUTH_USER'];
            $pass = $_SERVER['PHP_AUTH_PW'];
            $user = mysql_real_escape_string($user);
            $pass = mysql_real_escape_string($pass);

            mysql_query("UPDATE `login` SET logged=NOW()
                WHERE user='$user' AND pass='$pass'");
            // echo mysql_affected_rows();
            if(mysql_affected_rows()>0){
                self::$currentUser = $user;
                return TRUE;
            }
        }
        header('WWW-Authenticate: Basic realm="'.self::REALM.'"');
        throw new RestException(401, 'Basic Authentication Required');
    }
}

Your API class can have a protected method that query the same db, it can be a different table that return the data using the same connection. 您的API类可以具有查询同一数据库的受保护方法,它可以是使用相同连接返回数据的不同表。 For simplicity sake I use the same table here. 为简单起见,我在这里使用相同的表。

<?php
require_once 'config.php';
class Simple {
    function index() {
        return 'public api result';
    }
    protected function restricted() {
        $query = mysql_query("SELECT * FROM login");
        $result = array();
        while ($row = mysql_fetch_assoc($query)) {
            $result[]=$row;
        }
        return $result;
    }
}

Using require_once makes sure that the php file is included only once on the first encounter. 使用require_once可以确保在第一次遇到时只包含一次php文件。 Even if we stop using the auth class latter our api will keep functioning 即使我们停止使用auth类,我们的api也会继续运行

Assuming that following SQL is used to create our db table 假设使用以下SQL来创建我们的db表

--
-- Database: `mysql_db`
--

--
-- Table structure for table `login`
--

CREATE TABLE IF NOT EXISTS `login` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `logged` datetime DEFAULT NULL,
  `user` varchar(10) DEFAULT NULL,
  `pass` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `login`
--

INSERT INTO `login` (`id`, `logged`, `user`, `pass`) VALUES
(1, '2011-11-01 22:50:05', 'arul', 'mypass'),
(2, '2011-11-01 23:43:25', 'paulo', 'hispass');

And the index.php with the following 和index.php有以下几点

<?php
require_once '../../restler/restler.php';

#set autoloader
#do not use spl_autoload_register with out parameter
#it will disable the autoloading of formats
spl_autoload_register('spl_autoload');

$r = new Restler();

$r->addAPIClass('Simple','');
$r->addAuthenticationClass('BasicAuthentication');
$r->handle();

The Result 结果

if you open index.php/restricted in the browser and key in the right username and password combination, you will see the following as the result :) 如果您在浏览器中打开index.php/restricted并输入正确的用户名和密码组合,您将看到以下结果:)

[
  {
    "id": "1",
    "logged": "2011-11-01 22:50:05",
    "user": "arul",
    "pass": "mypass"
  },
  {
    "id": "2",
    "logged": "2011-11-01 23:43:25",
    "user": "paulo",
    "pass": "hispass"
  }
]

Figured it out! 弄清楚了!

echo mysql_affected_rows();

This line was causing the output to be in text/html format. 这一行导致输出为text / html格式。 Commented that out and I was good to go. 评论说出来,我很高兴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM