我正在尝试使用this code snipp from scott应用安全令牌,但我似乎无法在symfony2中解决这个问题,这是我的代码:
<?php
namespace Acme\UserManagementBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class TokenController extends Controller
{
public function randSecureAction($min, $max) {
$range = $max - $min;
if ($range < 0) return $min; // not so random...
$log = log($range, 2);
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd >= $range);
return new Response ($min + $rnd);
}
public function getTokenAction($length=32) {
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
for($i=0;$i<$length;$i++) {
$token .= $codeAlphabet[randSecureAction(0,strlen($codeAlphabet))];
}
return new Response ($token);
}
}
我将此TokenController创建为this之类的服务,因此我可以将其调用到我的DefaultController,现在服务无法调用此控制器内的其他函数,我做错了还是有一个我的代码中的问题是因为里面的函数(getTokenAction)似乎在TokenController类中使用了其他函数(randSecureAction)。
答案 0 :(得分:3)
在getTokenAction
内你有一行:
$token .= $codeAlphabet[randSecureAction(0,strlen($codeAlphabet))];
这是您的问题,您必须使用$this->randSecureAction(...)
。所以试试
$token .= $codeAlphabet[$this->randSecureAction(0,strlen($codeAlphabet))];
答案 1 :(得分:0)
service是一个php 对象。所以你需要把它改成
$this->randSecureAction(0,strlen($codeAlphabet))
也使用Response对象来响应,而不是返回。
并且个人更喜欢在动作函数结束时使用Action字。
所以最终的代码应该是这样的
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class TokenController extends Controller {
public function randSecure($min, $max) {
$range = $max - $min;
if ($range < 0)
return $min; // not so random...
$log = log($range, 2);
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd >= $range);
return $min + $rnd;
}
public function getToken($length = 32) {
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
for ($i = 0; $i < $length; $i++) {
$token .= $codeAlphabet[$this->randSecure(0, strlen($codeAlphabet))];
}
return $token;
}
}
并定义为服务:
<parameters>
<parameter key="acme.controller.token.class">Acme\DemoBundle\Controller\TokenController</parameter>
</parameters>
<services>
<service id="acme.token.controller" class="%acme.controller.token.class%" />
</services>
和用法:
public function helloAction($name) {
$token = $this->get('acme.token.controller')->getToken();
}