Luracast Restler 身份验证

发布于 2024-12-11 17:20:36 字数 397 浏览 0 评论 0原文

我正在使用 Luracast Restler,并且尝试通过实现 iAuthenticate 接口来实现一些身份验证。

问题是,我的身份验证代码需要查询我的数据库以检索用户私钥。此私钥将始终在 url 请求中提供(经过哈希处理)。

我只想为每个请求打开一个数据库连接,因此我需要将数据库连接变量传递给实现 iAuthenticate 的类以及处理所有请求的其他类。但我不知道如何将变量传递给实现 iAuthenticate 的类。

是否可以?

作为参考,这里是luracast 示例

请提前谢谢。

I’m using Luracast restler and i’m trying to implement some authentication by implementing iAuthenticate interface.

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).

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. But i can’t figure out how can i pass variables to my class that implements iAuthenticate.

Is it possible?

For reference, here are the luracast examples

thks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

私野 2024-12-18 17:20:36

对 API 和身份验证类使用单一数据库连接

创建一个名为 config.php 的 php 文件,并将所有数据库信息以及数据库连接和选择放在一起。

例如,

<?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);

在身份验证类和 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');
    }
}

您的 API 类可以有一个受保护的方法来查询同一数据库,它可以是使用相同连接返回数据的不同表。为了简单起见,我在这里使用同一张表。

<?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;
    }
}

使用 require_once 确保 php 文件在第一次遇到时仅包含一次。即使我们停止使用后者的 auth 类,我们的 api 仍将继续运行

假设使用以下 SQL 来创建我们的数据库表

--
-- 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');

的 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();

以及具有以下结果

如果您打开 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"
  }
]

Using Single DB Connection for your API and Authentication Classes

Create a php file called config.php and place all your db information along with db connection and selection.

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)

<?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. 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. Even if we stop using the auth class latter our api will keep functioning

Assuming that following SQL is used to create our db table

--
-- 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

<?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 :)

[
  {
    "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"
  }
]
婴鹅 2024-12-18 17:20:36

想通了!

echo mysql_affected_rows();

该行导致输出为 text/html 格式。评论出来后我就可以走了。

Figured it out!

echo mysql_affected_rows();

This line was causing the output to be in text/html format. Commented that out and I was good to go.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文