0

I want to programmatically log in an user using the FOSRestBundle (I am not using FOSUserBundle). It seems to work, but when I logged in successfully and try to access an secured endpoint, Symfony throws an AccessDeniedException.

This is my security.yml:

security:
    providers:
        main:
            entity:
                class: DepartureMonitor\RestBundle\Entity\User
                property: email

    role_hierarchy:
        ROLE_EDITOR: [ ROLE_USER ]
        ROLE_VU_ADMIN: [ ROLE_EDITOR, ROLE_USER ]
        ROLE_ADMIN: [ ROLE_VU_ADMIN ]

    encoders:
        DepartureMonitor\RestBundle\Entity\User:
            algorithm: bcrypt
            cost: 13

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        rest:
            pattern: ^/api
            provider: main
            anonymous: true
            form_login:
                login_path: login
                check_path: login_check
            logout: ~

    access_control:
        - { path: ^/api/users/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api/users/password, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api, roles: ROLE_USER }

In my UsersController I have the following action:

/**
 * @Post("/users/login")
 */
public function loginAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $user = $em->getRepository('DepartureMonitorRestBundle:User')->findOneBy(array('email' => $request->request->get('username')));

    if ($user instanceof User) {
        $factory = $this->get('security.encoder_factory');
        $encoder = $factory->getEncoder($user);
        $pw = $encoder->encodePassword($request->request->get('password'), $user->getSalt());

        if($pw === $user->getPassword()) {
            $token = new UsernamePasswordToken($user, $pw, "main", $user->getRoles());
            $this->get('security.context')->setToken($token);

            $event = new \Symfony\Component\Security\Http\Event\InteractiveLoginEvent($request, $token);
            $this->get('event_dispatcher')->dispatch('security.interactive_login', $event);

            if(!($this->getUser() instanceof User)) {
                return $this->view(array('code' => HttpStatusCode::NOT_FOUND, 'message' => $this->get('translator')->trans('error.messages.bad_credentials')), HttpStatusCode::NOT_FOUND);
            }

            $view = $this->view($user, HttpStatusCode::CREATED);
            $view->setSerializationContext(SerializationContext::create()->setGroups(array('login')));
            return $this->handleView($view);
        }
    }

    return $this->view(array('code' => HttpStatusCode::NOT_FOUND, 'message' => $this->get('translator')->trans('error.messages.bad_credentials')), HttpStatusCode::NOT_FOUND);
}

I don't know what the problem here is. Any help is very appreciated.

Johannes Klauß
  • 10,676
  • 16
  • 68
  • 122

0 Answers0