我使用FOSOAuthBundle作为我的REST应用程序
我希望我的大部分路线都需要授权,但是有一些应该是公开的。
我的security.yml中有以下内容:
security:
encoders:
FOS\UserBundle\Model\UserInterface: bcrypt
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
fos_userbundle:
id: fos_user.user_provider.username
firewalls:
oauth_token:
pattern: ^/login
security: false
api:
pattern: ^/
fos_oauth: true
stateless: true
anonymous: false
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: [ IS_AUTHENTICATED_FULLY ] }例如:
我有Entity和Controller的产品
我希望CRUD操作是私有的,但Read除外
因此:POST, PUT, DELETE on /products(/:id)应该是私有的,而GET应该是公开的。
我尝试在access_control中添加以下内容:
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/products$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: [ IS_AUTHENTICATED_FULLY ] }我以为这会打开/products上的所有/products,但我得到了错误:
{
"error": "access_denied",
"error_description": "OAuth2 authentication required"
} 我有许多entities和controllers,我正在尝试将它应用于。
我将如何开放特定的路线(包括method要求)?
发布于 2017-03-01 08:51:05
您可以使用regex创建新的防火墙,并将其设置为这样。您必须把它放在您的api防火墙前面,以便首先匹配这个正则表达式。
api_anonym_area:
pattern: (^/api/products/.*)
methods: [GET]
security: false或者你能做到
api_anonym_area:
pattern: (^/api/products/.*)
methods: [GET]
anonymous: true使用
access_control:
- { path: ^/api/products/.*, role: IS_AUTHENTICATED_ANONYMOUSLY}在第一种情况下,您将没有令牌,在第二种情况下,您将拥有令牌(当您期望通过身份验证或匿名的用户到来时,这是很好的)。
发布于 2016-12-21 08:08:32
要实现这一点,最好的方法是在控制器中编写权限,我认为通过security.yml配置这是不可能的。
你应该删除:
- { path: ^/, roles: [ IS_AUTHENTICATED_FULLY ] }并管理控制器操作中的权限,例如(取自http://symfony.com/doc/current/security.html的symfony文档)
public function updateProduct($id)
{
// The second parameter is used to specify on what object the role is tested.
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
// Old way :
// if (false === $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
// throw $this->createAccessDeniedException('Unable to access this page!');
// }
// ...
}https://stackoverflow.com/questions/41257798
复制相似问题