在不同的方法参数上使用身份验证(Restler 3)

时间:2014-01-30 00:04:31

标签: php authentication basic-authentication http-authentication restler

如果参数具有特定值,我想限制对方法的访问。让我们以此类为例:

Simple.php:     

class Simple
{
    function item($name)
    {
        if($name == "somerestricted")
        {
            // Here should be an authentication check (or somewhere else), hopefully, using an iAuthenticate class
            // Later, there will be a check using a database to determine if authentication will be required
            // So user/password may vary
            if($authenticated)
            {
                // Proceed
            }
            else
            {
                // ???
            }
        }
        else
        {
            echo "Hi!";
        }
    }
}

使用此身份验证类:

BasicAuthentication.php:     

class BasicAuthentication implements iAuthenticate
{
    const REALM = 'Restricted API';
    function __isAllowed()
    {
        if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']))
        {
            $user = $_SERVER['PHP_AUTH_USER'];
            $pass = $_SERVER['PHP_AUTH_PW'];
            if($user == 'laterfetched' && $pass == 'fromdatabase')
            {
                return true;
            }
        }
        header('WWW-Authenticate: Basic realm="'.self::REALM.'"');
        throw new RestException(401, 'Basic Authentication Required');
    }
}

Index.php(网关):     addAuthenticationClass( 'BasicAuthentication');     $ R-> addAPIClass( '简单');     $ R->手柄();

simple/item方法现在可以公开访问。但是,如果我将item转换为protected函数,每个请求都需要进行身份验证。这不是我想要做的。只有simple/item/somerestricted才需要身份验证。

那么有没有办法将iAuthenticate限制为特定的参数值?如果没有,我怎么能解决这个问题?

用户名和密码在生产使用中会有所不同(取决于给定的参数)。

我发现了以下相关问题:Restler 3.0 Basic AuthenticationLuracast Restler Authentication

我正在使用Restler rc4。

1 个答案:

答案 0 :(得分:2)

你已经制作了一个混合api,它是公开的,如果用户通过身份验证会增强结果

一种方法如下所示。它在Restler中使用隐藏属性

class Simple
{
    /**
     * @var \Luracast\Restler\Restler
     */
    public $restler;
    /**
     * @access hybrid
     */
    function item($name)
    {
        if ($name == "somerestricted") {
            if ($this->restler->_authenticated) {
                // Proceed
            } else {
                // ???
            }
        } else {
            echo "Hi!";
        }
    }
}

另一种(推荐)方式是使用iUseAuthentication接口

use Luracast\Restler\iUseAuthentication;

class Simple implements iUseAuthentication
{
    protected $authenticated;

    /**
     * @access hybrid
     */
    function item($name)
    {
        if ($name == "somerestricted") {
            if ($this->authenticated) {
                // Proceed
            } else {
                // ???
            }
        } else {
            echo "Hi!";
        }
    }

    public function __setAuthenticationStatus($isAuthenticated = false)
    {
        $this->authenticated = $isAuthenticated;
    }
}