FOSRestBundle在我的项目中完美运行但没有验证。现在,我的目标是通过身份验证发出请求。
为此,我在security.yml
中添加了此防火墙firewalls:
# ...
rest_api:
pattern: ^/api/
stateless: true
http_basic:
provider: fos_userbundle
# ...
access_control:
# ...
- { path: ^/api/, role: IS_AUTHENTICATED_FULLY }
为了检查这个,我使用了这个shell命令:
curl -i http://localhost/tuto/web/app_dev.php/api/test/1
结果是:
HTTP/1.1 302 Found
Date: Fri, 11 Apr 2014 13:56:08 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: PHP/5.4.9-4ubuntu2.4
Set-Cookie: PHPSESSID=4dtr168vmj1eg523a07kbkjkh1; path=/
Cache-Control: no-cache
Location: http://localhost/tuto/web/app_dev.php/login
Vary: Accept-Language
X-Debug-Token: 220df7
Transfer-Encoding: chunked
Content-Type: application/json
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="1;url=http://localhost/tuto/web/app_dev.php/login" />
<title>Redirecting to http://localhost/tuto/web/app_dev.php/login</title>
</head>
<body>
Redirecting to <a href="http://localhost/tuto/web/app_dev.php/login">http://localhost/tuto/web/app_dev.php/login</a>.
</body>
</html>
如您所见,返回的代码是302 FOUND,因为当我使用FOSUserBundle时,URL被重定向到http://localhost/tuto/web/app_dev.php/login
。
这很奇怪,因为我定义了我的action()方法如下:
/**
* @Rest\View
* @Rest\Get("/api/test/{id}",
* requirements={"id" = "\d+"},
* defaults={"id" = 1}
* )
*/
public function getAction($id) {
$user = $this->get('security.context')->getToken()->getUser();
if(!($user instanceof \Minn\UserBundle\Entity\User)){
throw new \Symfony\Component\Security\Core\Exception\AccessDeniedException();
}
$repo = $this->getDoctrine()->
getManager()->
getRepository("MinnAdsAPIBundle:Test");
$entity = $repo->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find test entity!');
}
return array('test' => $entity);
}
那么,有没有想法修复我的action()方法?
感谢。
顺便问一下,用authentification检查我的动作的shell命令是什么?
我尝试了这个命令curl -i http://localhost/tuto/web/app_dev.php/api/test/1 --user user:password
,但我仍然有302个FOUND。
答案 0 :(得分:1)
我再次找到了解决方案......
只需修改config.yml,如下所示:
fos_rest:
# ...
access_denied_listener:
# all requests using the 'json' format will return a 403 on an access denied violation
json: true
# ...
现在,我收到403错误代码。
希望它能帮助别人。