验证了Symfony2的API(移动应用使用) [英] Authentication for a Symfony2 api (for mobile app use)

查看:972
本文介绍了验证了Symfony2的API(移动应用使用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了REST API为我的Symfony2应用。该API将通过移动应用中使用。大部分的功能​​在当前已验证用户的情况下完成的,例如:

I've developed a REST api for my Symfony2 application. This api will be used by a mobile app. Much of the functionality is done in the context of the currently authenticated user, ie:

$this->container->get('security.context')->getToken()->getUser()

我希望,移动应用将能够张贴到login操作,就像一个传统的Web表单。如果凭据检查出那么Symfony2的做这件事,并设置一个cookie(这是否即使在移动应用程序访问的API的情况下工作吗?)。再后来从手机API请求(希望)与本机的Symfony2 security.context服务容器工作。

I'm hoping that the mobile app will be able to post to the login action just like a traditional web form. If the credentials check out then Symfony2 does it's thing and sets a cookie (does this even work in the context of a mobile app accessing an api?). Then later api requests from that mobile phone will (hopefully) work with the native symfony2 security.context service container.

将这项工作?我需要弄清楚这个授权过程我把API的移动开发者面前。如果可能的话我会很明显希望能够使用本地security.context服务,而不是构建出使用XAUTH或类似的API一个新的身份验证系统的。

Would this work? I need to figure out this authorization process before I take the API to the mobile developers. If possible I'd obviously like to be able to use the native security.context service instead of building out a new auth system for the api that uses xAuth or something similar.

感谢

推荐答案

我觉得你应该这样做无状态(无饼干)。

I think you should do it stateless (without cookie).

我有同样的问题,我做了什么:

I had the same problem, what i did:


  • 在您的应用程序/配置/ security.yml,添加:


security:
    ...
    firewalls:
        rest_webservice:
            pattern: /webservice/rest/.*
            stateless: true
            http_basic:
                provider: provider_name
    ...


  • 现在,你可以要求你的web服务:

  • class AuthTest extends WebTestCase 
    {
        public function testAuthenticatedWithWebservice() 
        {
            $client = $this->createClient();
    
            // not authenticated
            $client->request('GET', '/webservice/rest/url');
            $this->assertEquals(401, $client->getResponse()->getStatusCode());
    
            // authenticated
            $client->request('GET', '/webservice/rest/url', array(), array(), array(
                'PHP_AUTH_USER' => 'username', 
                'PHP_AUTH_PW' => 'password'
            ));
            $this->assertEquals(200, $client->getResponse()->getStatusCode());
        }
    }
    

    这篇关于验证了Symfony2的API(移动应用使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆