Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 FOSUserBundle with rest login and registration

I have gone through lots of stackoveflow question and articles, but can't find a suitable answer.

I'm using fosuserbundle, hwiouthbundle and lexikjwt bundle.

I'm developing an api based on symfony which will be consumed by an android app and angular app.

Now I need the register and login system with fosuserbundle facebook login with hwiouthbundle and api protection with lexikjwt bundle.

I have implemented fosuserbundle and hwiouthbundke and both working without even writing user controller. But I need this with rest not with form. But I can't out type : rest in router.

Now how can I login, register user with fosuserbundle with rest? I don't want to use fosouth server. Just need registration and login with api not rest from web.

like image 727
Ahmad Sajid Avatar asked Jan 31 '16 22:01

Ahmad Sajid


1 Answers

So, if you want register user manually using FOSUserBundle, create a controller and add a register method :

// Acme/AppBundle/Controller/SecurityController

public function registerAction(Request $request)
{
    $userManager = $this->get('fos_user.user_manager');
    $entityManager = $this->get('doctrine')->getManager();
    $data = $request->request->all();

    // Do a check for existing user with userManager->findByUsername

    $user = $userManager->createUser();
    $user->setUsername($data['username']);
    // ...
    $user->setPlainPassword($data['password']);
    $user->setEnabled(true);

    $userManager->updateUser($user);

    return $this->generateToken($user, 201);
}

And, the generateToken method

protected function generateToken($user, $statusCode = 200)
{
    // Generate the token
    $token = $this->get('lexik_jwt_authentication.jwt_manager')->create($user)

    $response = array(
        'token' => $token,
        'user'  => $user // Assuming $user is serialized, else you can call getters manually
    );

    return new JsonResponse($response, $statusCode); // Return a 201 Created with the JWT.
}

And the route

security_register:
    path: /api/register
    defaults: { _controller: AcmeAppBundle:Security:registerAction }
    methods: POST

Configure the firewall same as login

// app/config/security.yml

firewalls:
    // ...
    register:
        pattern: ^/api/register
        anonymous: true
        stateless: true
    // ...

access_control:
    // ...
    - { path: ^/api/register, role: IS_AUTHENTICATED_ANONYMOUSLY }

For login, juste use the check_path of your FOSUser login firewall.

For more information about the token generation, see JWTManager. Hope this help you.

EDIT

If you want a full example of LexikJWTAuthenticationBundle + FOSUserBundle + FOSRestBundle implementation see my symfony-rest-api

like image 150
chalasr Avatar answered Nov 14 '22 22:11

chalasr