Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 - FOSUserBundle - how to integrate in API

I work on a new Symfony 2 project. I'm learning this framework at the same time. For the user management, I use the bundle FOSUserBundle. My project works very well, I can login, register, logout and all other commands available.

The thing is that I want to make smartphone app which will use the API of my Symfony app. In the app, the user will have to sign in, or to sign up. Is it possible to use FOSUserBundle methods for API too?

I studied another bundle for making an API, it's FOSRestBundle. If there are not solution, do you think that I will have to create my own users method like :

    /api/login
    /api/register 

Then, inside this method, I redirect to FOSUserBundle methods? I'm just wondering what is the best, and the cleanest way to login, and register with FOSUserBundle from smartphone, so by using API

like image 913
manonthemoon Avatar asked Oct 24 '13 18:10

manonthemoon


2 Answers

I have this problem too. I found the best solution is this

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class YourController extends Controller{
//Other Methods..

public function loginAction(Request $request){
    try{
        $token = $this->get('security.authentication.manager')->authenticate(new UsernamePasswordToken('username', 'password', 'firewall'));
        $this->get('security.context')->setToken($token);
    }
    catch(BadCredentialsException $e){
        return new Response("Bad credentials", 403);
    }
    return new Response("success");
}
}
like image 79
thewbb Avatar answered Nov 15 '22 08:11

thewbb


I used the FOSRestBundle.

This bundle is very powerful and simple to implement. The documentation is pretty complete.

The github link of FOSRestBundle here

Hope that it helps

like image 24
manonthemoon Avatar answered Nov 15 '22 09:11

manonthemoon