Authentication for a Symfony2 api (for mobile app use)

后端 未结 3 1867
遇见更好的自我
遇见更好的自我 2020-12-24 13:38

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 authenticate

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 14:05

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

    I had the same problem, what i did:

    • in your app/config/security.yml, add:
    security:
        ...
        firewalls:
            rest_webservice:
                pattern: /webservice/rest/.*
                stateless: true
                http_basic:
                    provider: provider_name
        ...
    
    • Now you can make a request to your webservice:
    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());
        }
    }
    

提交回复
热议问题