我最近使用FOSUser FOSOAuthServer和FOSRest Bundle设置了一个API。
在我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:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
oauth_token: # Everyone can access the access token URL.
pattern: ^/login
security: false
api:
pattern:/ # All URLs are protected
fos_oauth: true # OAuth2 protected resource
stateless: true # Do no set session cookies
anonymous: false
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
这允许登录路线匿名访问,而所有其它途径要求身份验证。
我已创建一条登录路由,将请求代理到OAuth客户端。这样,用户根本不知道客户密码:(注意:我已删除的例子中的客户端ID和密码)
/**
* @Post("/login")
*/
public function postLoginAction(Request $request){
$request->request->add(array(
'grant_type' => 'password',
'client_id' => 'clientID_clientRandomID',
'client_secret' => 'clientSecret'
));
return($this->get('fos_oauth_server.controller.token')->tokenAction($request));
}
如果有效的用户名/密码提交这将返回OAuth令牌。
一旦我有这个令牌一旦用户通过验证,你可以随时查询自己的角色,如果需要的话,在任何API调用,我可以把它添加到标头的任何请求
Authorization: Bearer OAuth_TOKEN
。像下面这样:
public function getUserAction()
{
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
$user = $this->getUser();
$view = $this->view($user);
return $this->handleView($view);
}
检查角色的另一种方法可以在security.yml
# app/config/security.yml
security:
# ...
access_control:
- path: "^/api/users/\d+$"
allow_if: "'DELETE' == request.getMethod() and has_role('ROLE_ADMIN')"
做,我发现这个在下面的帖子:RESTFul OAuth with FOSOAuthServer/FOSRest & FOSUser
这是我的事接洽对于Symfony3构建,Symfony2的某些语法(检查用户角色)可能会有所不同。对于Symfony2,我使用这篇文章作为参考,而buil ding my api:http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/
代理部分实际上是我发现的唯一一段代码,它显示了如何在只保留用户名和密码的情况下使用oauth,同时保持客户端id和客户端的秘密不被公开。 – Tek
是的,看起来像一个非常简单的概念,没有人实现。保持客户秘密。 –