Symfony 2 FOSUserBundle with registration and balance registration

I have looked through many questions and articles about downloading, but cannot find a suitable answer.

I use the package fosuserbundle, hwiouthbundle and lexikjwt.

I am developing a symfony-based api that will be used by the android and angular app.

Now I need a registration and login system with fosuserbundle facebook login with hwiouthbundle and api protection with the lexikjwt package.

I implemented fosuserbundle and hwiouthbundke, and both work without writing a user controller. But I need this with rest, not with form. But I can not choose the type: rest in the router.

Now, how can I log in, register a user with fosuserbundle with rest? I do not want to use the fosouth server. Just need registration and login with api, and not rest from the Internet.

+5
source share
1 answer

So, if you want to manually register a user using FOSUserBundle, create a controller and add a registration 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 in the same way as login

 // app/config/security.yml firewalls: // ... register: pattern: ^/api/register anonymous: true stateless: true // ... access_control: // ... - { path: ^/api/register, role: IS_AUTHENTICATED_ANONYMOUSLY } 

To login, use the check_path your check_path login firewall.

For more information on marker generation, see the JWTManager . Hope this helps you.

EDIT

If you need a complete example implementation of LexikJWTAuthenticationBundle + FOSUserBundle + FOSRestBundle, see my symfony-rest-api

+12
source

Source: https://habr.com/ru/post/1241951/


All Articles