我最近使用 FOSUser FOSOAuthServer 和 FOSRest Bundles 设置了一个 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 令牌。
一旦我有了这个令牌,我就可以将它添加到任何请求的标头中
Authorization: Bearer OAuth_TOKEN
验证用户后,您可以随时在任何 api 调用中检查他们的角色(如果需要)。类似于以下内容:
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 不同
我在构建我的 api 时使用这篇文章作为参考:http ://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/