Luracast Restler 身份验证 [英] Luracast Restler Authentication

查看:24
本文介绍了Luracast Restler 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Luracast restler,我正在尝试通过实现 iAuthenticate 接口来实现一些身份验证.

问题是,我的身份验证代码需要查询我的数据库以检索用户私钥.此私钥将始终在 url 请求中提供(散列).

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

有可能吗?

作为参考,这里是 luracast 示例

提前谢谢.

解决方案

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

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

例如

在身份验证类和 API 类上使用 require_once 包含此函数,例如(为简单起见,我没有在此处加密密码)

 0){self::$currentUser = $user;返回真;}}header('WWW-Authenticate: Basic realm="'.self::REALM.'"');throw new RestException(401, '需要基本身份验证');}}

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

使用 require_once 确保 php 文件在第一次遇到时只包含一次.即使我们稍后停止使用 auth 类,我们的 api 也会继续运行

假设下面的 SQL 用于创建我们的数据库表

---- 数据库:`mysql_db`————-- 表`login`的表结构——如果不存在登录",则创建表(`id` int(11) NOT NULL AUTO_INCREMENT,`logged` 日期时间默认为 NULL,`user` varchar(10) 默认为空,`pass` varchar(10) 默认为空,主键(`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;——-- 转储表`login`的数据——插入`login`(`id`、`logged`、`user`、`pass`)值(1, '2011-11-01 22:50:05', 'arul', 'mypass'),(2, '2011-11-01 23:43:25', 'paulo', 'hispass');

以及带有以下内容的 index.php

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

结果

如果您在浏览器中打开 index.php/restricted 并输入正确的用户名和密码组合,您将看到以下结果:)

<预><代码>[{"id": "1","记录": "2011-11-01 22:50:05","user": "arul",通行证":我的通行证"},{"id": "2","记录": "2011-11-01 23:43:25",用户":保罗","pass": "hispass"}]

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.

解决方案

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"
  }
]

这篇关于Luracast Restler 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆