3

在我的symfony2项目中,我使用FOSUSerBundle在网站上登录,注册等。正如我所料,工作正常。 但是现在我想构建一个REST API,以便Android应用程序可以充当客户端并处理数据。 我发现FOSRestBundle在symfony2项目中构建REST API。我想使用FOSOAuthServerBundle来处理用于访问api的令牌。 用户应该通过API登录,然后他可以使用api提供的其他方法。FOSRestBundle,FOSOAuthServerBundle,FOSUserBundler - 如何整合它们?

我看了很多博客和其他文档,但是找不到,如何构建REST Api。 我设置了每个Bundle,并生成了一个带有公共ID和安全代码的客户端。在网站上我可以使用登录。

但是我需要在mein REST API控制器中使用令牌认证来定义哪些步骤/方法?

谢谢!

回答

0

在这个link,你会发现一个很好的例子来开发你的第一个REST api。

祝你好运。

0

我最近使用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/

+0

代理部分实际上是我发现的唯一一段代码,它显示了如何在只保留用户名和密码的情况下使用oauth,同时保持客户端id和客户端的秘密不被公开。 – Tek

+0

是的,看起来像一个非常简单的概念,没有人实现。保持客户秘密。 –