Symfony 2 FOSUserBundle with rest login and registration

落花浮王杯 提交于 2019-12-02 21:19:49

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!