Beispiel #1
0
 public final function logInUser($firewallName, UserInterface $user, Response $response = null)
 {
     $this->userChecker->checkPostAuth($user);
     $token = $this->createToken($firewallName, $user);
     $request = null;
     if ($this->container->has('request_stack')) {
         $request = $this->container->get('request_stack')->getCurrentRequest();
     } elseif (method_exists($this->container, 'isScopeActive') && $this->container->isScopeActive('request')) {
         // BC for SF <2.4
         $request = $this->container->get('request');
     }
     if (null !== $request) {
         $this->sessionStrategy->onAuthentication($request, $token);
         if (null !== $response) {
             $rememberMeServices = null;
             if ($this->container->has('security.authentication.rememberme.services.persistent.' . $firewallName)) {
                 $rememberMeServices = $this->container->get('security.authentication.rememberme.services.persistent.' . $firewallName);
             } elseif ($this->container->has('security.authentication.rememberme.services.simplehash.' . $firewallName)) {
                 $rememberMeServices = $this->container->get('security.authentication.rememberme.services.simplehash.' . $firewallName);
             }
             if ($rememberMeServices instanceof RememberMeServicesInterface) {
                 $rememberMeServices->loginSuccess($request, $response, $token);
             }
         }
     }
     $this->tokenStorage->setToken($token);
 }
 /**
  * @param ClientEvent $event
  *
  * @throws StorageException
  * @throws \Exception
  */
 public function onClientConnect(ClientEvent $event)
 {
     $conn = $event->getConnection();
     if (true === $this->originChecker && 1 === count($this->firewalls) && 'ws_firewall' === $this->firewalls[0]) {
         $this->logger->warning(sprintf('User firewall is not configured, we have set %s by default', $this->firewalls[0]));
     }
     $loggerContext = array('connection_id' => $conn->resourceId, 'session_id' => $conn->WAMP->sessionId);
     $token = null;
     if (isset($conn->Session) && $conn->Session) {
         foreach ($this->firewalls as $firewall) {
             if (false !== ($serializedToken = $conn->Session->get('_security_' . $firewall, false))) {
                 /** @var TokenInterface $token */
                 $token = unserialize($serializedToken);
                 break;
             }
         }
     }
     if (null === $token) {
         $token = new AnonymousToken($this->firewalls[0], 'anon-' . $conn->WAMP->sessionId);
     }
     $this->securityContext->setToken($token);
     $user = $token->getUser();
     $username = $user instanceof UserInterface ? $user->getUsername() : $user;
     try {
         $identifier = $this->clientStorage->getStorageId($conn, $username);
         $loggerContext['storage_id'] = $identifier;
         $this->clientStorage->addClient($identifier, $user);
         $conn->WAMP->clientStorageId = $identifier;
         $this->logger->info(sprintf('%s connected [%]', $username, $user instanceof UserInterface ? implode(', ', $user->getRoles()) : array()), $loggerContext);
     } catch (StorageException $e) {
         $this->logger->error($e->getMessage(), $loggerContext);
         throw $e;
     }
 }
Beispiel #3
0
 /**
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$request->headers->has('cookie')) {
         return;
     }
     if (strstr($request->headers->get('cookie'), 'SimpleSAMLAuthToken') === false) {
         return;
     }
     if (!$request->query->has('csrf-token')) {
         $this->logger->notice('Ssp Firewall: Auth Token cookie but no CSRF Token');
         return;
     }
     $csrfToken = $request->query->getAlnum('csrf-token');
     if (!$this->csrfProvider->isCsrfTokenValid('api', $csrfToken)) {
         $this->logger->notice('Ssp Firewall: Invalid CSRF token for api use: ' . $csrfToken);
         return;
     }
     try {
         $authToken = $this->authenticationManager->authenticate(new SspToken());
         $this->securityContext->setToken($authToken);
     } catch (AuthenticationException $failed) {
         $this->logger->warning('Ssp Firewall: failed:' . $failed->getMessage());
         $token = $this->securityContext->getToken();
         if ($token instanceof SspToken) {
             $this->securityContext->setToken(null);
         }
         return;
     }
 }
Beispiel #4
0
 /**
  * {@inheritDoc}
  */
 public function login(UserInterface $user, $firewallName = 'main')
 {
     $this->userChecker->checkPreAuth($user);
     $token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles());
     $this->securityContext->setToken($token);
     $this->eventDispatcher->dispatch(UserEvents::SECURITY_IMPLICIT_LOGIN, new UserEvent($user));
 }
 /**
  * Handles basic authentication.
  *
  * @param GetResponseEvent $event A GetResponseEvent instance
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (false === ($username = $request->headers->get('PHP_AUTH_USER', false))) {
         return;
     }
     if (null !== ($token = $this->securityContext->getToken())) {
         if ($token instanceof OrganizationContextTokenInterface && $token->isAuthenticated() && $token->getUsername() === $username) {
             return;
         }
     }
     $this->logProcess($username);
     try {
         $organizationId = $request->headers->get('PHP_AUTH_ORGANIZATION');
         if ($organizationId) {
             $authToken = new UsernamePasswordOrganizationToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey, $this->manager->getOrganizationById($organizationId));
         } else {
             $authToken = new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey);
         }
         $this->securityContext->setToken($this->authenticationManager->authenticate($authToken));
     } catch (AuthenticationException $failed) {
         $token = $this->securityContext->getToken();
         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
             $this->securityContext->setToken(null);
         }
         $this->logError($username, $failed->getMessage());
         if ($this->ignoreFailure) {
             return;
         }
         $event->setResponse($this->authenticationEntryPoint->start($request, $failed));
     }
 }
Beispiel #6
0
 /**
  * {@inheritdoc}
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if ($this->securityContext->getToken() !== null) {
         return;
     }
     if ($request->getRequestUri() == '/app_dev.php/api/login' || $request->getRequestUri() == '/api/login') {
         return;
     }
     //Try to reach token from HTTP headers
     if ($request->headers->has('X-Auth-Token')) {
         $tokenId = $request->headers->get('X-Auth-Token');
     } else {
         $tokenId = $request->get('token');
     }
     //by token
     if (isset($tokenId)) {
         $user = $this->userProvider->findUserByToken($tokenId);
         if (!$user) {
             throw new BadCredentialsException();
         }
         try {
             $token = new ApiToken([], $this->providerId, $this->key);
             $token->setUser($user);
             $authenticatedToken = $this->authenticationManager->authenticate($token);
             $this->securityContext->setToken($authenticatedToken);
         } catch (AuthenticationException $e) {
             //log something
         }
     }
 }
 /**
  * This interface must be implemented by firewall listeners.
  *
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $apiKey = $request->headers->get('Authorization', $request->query->get('api_key'));
     if (!$apiKey) {
         if (true === $this->forceApiKey) {
             $response = new Response();
             $response->setStatusCode(401);
             $event->setResponse($response);
         }
         return;
     }
     $token = new ApiKeyUserToken();
     $token->setApiKey($apiKey);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $token = $this->securityContext->getToken();
         if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
             $this->securityContext->setToken(null);
         }
         $message = $failed->getMessage();
     }
     if ($this->isJsonRequest($request)) {
         $response = new JsonResponse(array('error' => $message));
     } else {
         $response = new Response();
         $response->setContent($message);
     }
     $response->setStatusCode(401);
     $event->setResponse($response);
 }
 /**
  * This interface must be implemented by firewall listeners.
  *
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$this->keyExtractor->hasKey($request)) {
         $response = new Response();
         $response->setStatusCode(401);
         $event->setResponse($response);
         return;
     }
     $apiKey = $this->keyExtractor->extractKey($request);
     $token = new ApiKeyUserToken();
     $token->setApiKey($apiKey);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $token = $this->securityContext->getToken();
         if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
             $this->securityContext->setToken(null);
         }
         $message = $failed->getMessage();
     }
     $response = new Response();
     $response->setContent($message);
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
     if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
         // Deny authentication with a '403 Forbidden' HTTP response
         $response = new Response();
         $response->setStatusCode(403);
         $event->setResponse($response);
         return;
     }
     $token = new WsseUserToken();
     $token->setUser($matches[1]);
     $token->digest = $matches[2];
     $token->nonce = $matches[3];
     $token->created = $matches[4];
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         // ... you might log something here
         $failedMessage = 'WSSE Login failed for ' . $token->getUsername() . '. Why ? ' . $failed->getMessage();
         $this->logger->err($failedMessage);
         //To deny the authentication clear the token. This will redirect to the login page.
         //Make sure to only clear your token, not those of other authentication listeners.
         $this->securityContext->setToken(null);
         // Deny authentication with a '403 Forbidden' HTTP response
         $response = new Response();
         $response->setStatusCode(403);
         $response->setContent($failedMessage);
         $event->setResponse($response);
         return;
     }
 }
 /**
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event The event.
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (null === ($oauthToken = $this->serverService->getBearerToken($event->getRequest(), true))) {
         //if it's null, then we try to regular authentication...
         $token = $this->handleCookie($event);
         if ($token) {
             $this->securityContext->setToken($token);
             return;
         }
     }
     $token = new OAuthToken();
     $token->setToken($oauthToken);
     $returnValue = $this->authenticationManager->authenticate($token);
     try {
         $returnValue = $this->authenticationManager->authenticate($token);
         if ($returnValue instanceof TokenInterface) {
             return $this->securityContext->setToken($returnValue);
         }
         if ($returnValue instanceof Response) {
             return $event->setResponse($returnValue);
         }
     } catch (AuthenticationException $e) {
         if (null !== ($p = $e->getPrevious())) {
             $event->setResponse($p->getHttpResponse());
         }
     }
 }
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     //find out if the current request contains any information by which the user might be authenticated
     if (!$request->headers->has('X-WSSE')) {
         return;
     }
     $ae_message = null;
     $this->wsseHeader = $request->headers->get('X-WSSE');
     $wsseHeaderInfo = $this->parseHeader();
     if ($wsseHeaderInfo !== false) {
         $token = new Token($wsseHeaderInfo['Username'], $wsseHeaderInfo['PasswordDigest'], $this->providerKey);
         $token->setAttribute('nonce', $wsseHeaderInfo['Nonce']);
         $token->setAttribute('created', $wsseHeaderInfo['Created']);
         try {
             $returnValue = $this->authenticationManager->authenticate($token);
             if ($returnValue instanceof TokenInterface) {
                 return $this->tokenStorage->setToken($returnValue);
             } else {
                 if ($returnValue instanceof Response) {
                     return $event->setResponse($returnValue);
                 }
             }
         } catch (AuthenticationException $ae) {
             $event->setResponse($this->authenticationEntryPoint->start($request, $ae));
         }
     }
 }
 /**
  * Handles the authentication for user.
  *
  * @param GetResponseEvent $event The response event.
  *
  * @throws AuthenticationException When the request is not authenticated.
  *
  * @return void
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
     if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
         return;
     }
     $token = new WsseUserToken($this->providerKey);
     $token->setUser($matches[1]);
     $token->setDigest($matches[2]);
     $token->setNonce($matches[3]);
     $token->setCreated($matches[4]);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $failedMessage = 'WSSE Login failed for ' . $token->getUsername() . '.  Because: ' . $failed->getMessage();
         $token = $this->securityContext->getToken();
         if ($token instanceof WsseUserToken && $this->providerKey === $token->getProviderKey()) {
             $this->securityContext->setToken(null);
         }
         // deny authentication with a '403 Forbidden' HTTP response
         $response = new Response();
         $response->setStatusCode(403);
         $event->setResponse($response);
         return;
     }
     // by default deny authorization
     $response = new Response();
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
 /**
  * Checks if a Wordpress user is authenticated and authenticate him into Symfony security context
  *
  * @param Request $request
  */
 protected function checkAuthentication(Request $request)
 {
     $session = $request->getSession();
     if ($session->has('token')) {
         $token = $session->get('token');
         $this->securityContext->setToken($token);
     }
 }
 /**
  * @param GetResponseForExceptionEvent $event
  */
 public function onAccessDeniedException(GetResponseForExceptionEvent $event)
 {
     if ($event->getException() instanceof AccessDeniedHttpException) {
         $this->session->invalidate();
         $this->session->set(SecurityContextInterface::ACCESS_DENIED_ERROR, ['message' => 'You are not allowed']);
         $this->securityContext->setToken(null);
         $route = $this->router->generate('oro_distribution_security_login');
         $event->setResponse(new RedirectResponse($route));
     }
 }
Beispiel #15
0
 /**
  * Register new User into the web.
  * Creates new token given a user, with related Role set.
  *
  * @param AbstractUserInterface $user        User to register
  * @param string                $providerKey Provider key
  *
  * @return $this self Object
  */
 public function register(AbstractUserInterface $user, $providerKey)
 {
     if (!$this->securityContext instanceof SecurityContextInterface) {
         return $this;
     }
     $token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
     $this->securityContext->setToken($token);
     $event = new AbstractUserRegisterEvent($user);
     $this->eventDispatcher->dispatch(ElcodiUserEvents::ABSTRACTUSER_REGISTER, $event);
     return $this;
 }
Beispiel #16
0
 /**
  * {@inheritDoc}
  */
 public function login(UserInterface $user, $firewallName = 'main')
 {
     $this->userChecker->checkPreAuth($user);
     $this->userChecker->checkPostAuth($user);
     $token = $this->createToken($user, $firewallName);
     if (!$token->isAuthenticated()) {
         throw new AuthenticationException('Unauthenticated token');
     }
     $this->securityContext->setToken($token);
     $this->eventDispatcher->dispatch(UserEvents::SECURITY_IMPLICIT_LOGIN, new UserEvent($user));
 }
Beispiel #17
0
 /**
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $token = new ApiUnauthenticatedUserToken($this->getRequestService()->parse($event->getRequest()));
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
     } catch (AuthenticationException $e) {
         $response = new JsonResponse(['code' => $e->getCode(), 'message' => $e->getMessage()], $e->getCode() > 0 ? $e->getCode() : 403);
         $event->setResponse($response);
     }
 }
 /**
  * @param \Symfony\Component\HttpFoundation\Request $request
  * @throws \AerialShip\SamlSPBundle\Error\SSOSessionException
  * @return \Symfony\Component\HttpFoundation\Response|SamlSpInfo|null
  */
 public function manage(Request $request)
 {
     /** @var SamlSpToken $token */
     $token = $this->securityContext->getToken();
     $samlSpInfo = $token->getSamlSpInfo();
     $ssoState = $this->ssoStore->getOneByNameIDSessionIndex($token->getProviderKey(), $samlSpInfo->getAuthenticationServiceID(), $samlSpInfo->getNameID()->getValue(), $samlSpInfo->getAuthnStatement()->getSessionIndex());
     if ($ssoState == null || $ssoState->getNameID() != $samlSpInfo->getNameID()->getValue()) {
         $this->securityContext->setToken(new AnonymousToken($this->providerKey, 'anon.'));
         $ex = new SSOSessionException('SSO session has expired');
         $ex->setToken($token);
         throw $ex;
     }
     return null;
 }
 /**
  * Tries to retrieve a valid eZ user if authenticated user doesn't come from the repository (foreign user provider).
  * Will dispatch an event allowing listeners to return a valid eZ user for current authenticated user.
  * Will by default let the repository load the anonymous user.
  *
  * @param \Symfony\Component\Security\Http\Event\InteractiveLoginEvent $event
  */
 public function onInteractiveLogin(BaseInteractiveLoginEvent $event)
 {
     $token = $event->getAuthenticationToken();
     $originalUser = $token->getUser();
     if ($originalUser instanceof eZUser || !$originalUser instanceof UserInterface) {
         return;
     }
     /*
      * 1. Send the event.
      * 2. If no eZ user is returned, load Anonymous user.
      * 3. Inject eZ user in repository.
      * 4. Create the UserWrapped user object (implementing eZ UserInterface) with loaded eZ user.
      * 5. Create new token with UserWrapped user
      * 6. Inject the new token in security context
      */
     $subLoginEvent = new InteractiveLoginEvent($event->getRequest(), $token);
     $this->eventDispatcher->dispatch(MVCEvents::INTERACTIVE_LOGIN, $subLoginEvent);
     if ($subLoginEvent->hasAPIUser()) {
         $apiUser = $subLoginEvent->getAPIUser();
     } else {
         $apiUser = $this->repository->getUserService()->loadUser($this->configResolver->getParameter("anonymous_user_id"));
     }
     $this->repository->setCurrentUser($apiUser);
     $providerKey = method_exists($token, 'getProviderKey') ? $token->getProviderKey() : __CLASS__;
     $interactiveToken = new InteractiveLoginToken($this->getUser($originalUser, $apiUser), get_class($token), $token->getCredentials(), $providerKey, $token->getRoles());
     $interactiveToken->setAttributes($token->getAttributes());
     $this->securityContext->setToken($interactiveToken);
 }
    /**
     * If user is logged-in in legacy_mode (e.g. legacy admin interface),
     * will inject currently logged-in user in the repository.
     *
     * @param GetResponseEvent $event
     */
    public function onKernelRequest( GetResponseEvent $event )
    {
        /** @var \eZ\Publish\Core\MVC\ConfigResolverInterface $configResolver */
        $request = $event->getRequest();
        $session = $request->getSession();
        if (
            $event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST
            || !$this->configResolver->getParameter( 'legacy_mode' )
            || !( $session->isStarted() && $session->has( 'eZUserLoggedInID' ) )
        )
        {
            return;
        }

        try
        {
            $apiUser = $this->repository->getUserService()->loadUser( $session->get( 'eZUserLoggedInID' ) );
            $this->repository->setCurrentUser( $apiUser );

            $token = $this->securityContext->getToken();
            if ( $token instanceof TokenInterface )
            {
                $token->setUser( new User( $apiUser ) );
                $token->setAuthenticated( true );
            }
        }
        catch ( NotFoundException $e )
        {
            // Invalid user ID, the user may have been removed => invalidate the token and the session.
            $this->securityContext->setToken( null );
            $session->invalidate();
        }
    }
Beispiel #21
0
 /**
  * @param $email
  * @return string
  */
 public function change_pass($email, $hash)
 {
     $author = $this->em->getRepository('Yasoon\\Site\\Entity\\AuthorEntity')->findOneByEmail($email);
     if ($hash == md5($author->getNewpass())) {
         $authorId = $author->getId();
         $author->setPassword(md5($author->getNewpass()));
         $author->setNewpass(NULL);
         $author = $this->em->merge($author);
         $this->em->flush();
         // Сразу авторизуем чела
         $token = new UsernamePasswordToken((string) $author->getId(), $author->getPassword(), "secured_area", ['ROLE_USER']);
         $this->securityContext->setToken($token);
         /** @var Session $session */
         $session = $this->container->get('request')->getSession();
         $session->set('_security_secured_area', serialize($token));
         $this->container->get('request')->setSession($session);
         //            $statEntity = new AuthorChangedPassEntity();
         //            $statEntity->setAuthorId($authorId);
         //            $statEntity->setLastDate(new \DateTime());
         //
         //            $this->em->persist($statEntity);
         //            $this->em->flush();
         return true;
     } else {
         return false;
     }
 }
 public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
 {
     $targetPath = $this->failureDefault;
     $token = $exception->getToken();
     $this->logger->debug('Authentication failure handled by ' . __CLASS__, [$exception, $exception->getPrevious(), $token]);
     if ($exception instanceof BadCredentialsException && $exception->getPrevious() instanceof UsernameNotFoundException && $token instanceof Token && $token->getRoles()[0]->getRole() == ThirdPartyAuthentication::IDENTIFIED) {
         $this->logger->info('Autoregister');
         // create new user, persist and authenticate
         $user = $this->repository->create($token->getUserUniqueIdentifier(), $token->getProviderKey(), $token->getAttribute('nickname'));
         $newToken = new Token($token->getFirewallName(), $token->getProviderKey(), $token->getUserUniqueIdentifier(), $user->getRoles());
         $this->repository->persist($user);
         $newToken->setUser($user);
         $this->security->setToken($newToken);
         return $this->successLoginHandler->onAuthenticationSuccess($request, $newToken);
     }
     $request->getSession()->set(SecurityContextInterface::AUTHENTICATION_ERROR, $exception);
     return $this->httpUtils->createRedirectResponse($request, $targetPath);
 }
Beispiel #23
0
 /**
  * This interface must be implemented by firewall listeners.
  *
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $requestToken = $request->headers->get($this->options['header_name'], '');
     if (!empty($requestToken)) {
         try {
             $decoded = $this->encode->decode($requestToken);
             $token = new JWTToken();
             $token->setTokenContext($decoded);
             $authToken = $this->authenticationManager->authenticate($token);
             $this->securityContext->setToken($authToken);
             return;
         } catch (HttpEncodingException $e) {
         } catch (\UnexpectedValueException $e) {
         }
     }
     $response = new Response();
     $response->setStatusCode(Response::HTTP_UNAUTHORIZED);
     $event->setResponse($response);
 }
 /**
  * {@inheritdoc}
  */
 public function handle(GetResponseEvent $event)
 {
     if (!($requestToken = $this->getRequestToken($event->getRequest()))) {
         return;
     }
     $token = new JWTUserToken();
     $token->setRawToken($requestToken);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->tokenStorage->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         if ($this->config['throw_exceptions']) {
             throw $failed;
         }
         $response = new Response();
         $response->setStatusCode(401);
         $event->setResponse($response);
     }
 }
 protected function getToken(ConnectionInterface $connection)
 {
     $token = null;
     if (isset($connection->Session) && $connection->Session) {
         foreach ($this->firewalls as $firewall) {
             if (false !== ($serializedToken = $connection->Session->get('_security_' . $firewall, false))) {
                 /** @var TokenInterface $token */
                 $token = unserialize($serializedToken);
                 break;
             }
         }
     }
     if (null === $token) {
         $token = new AnonymousToken($this->firewalls[0], 'anon-' . $connection->WAMP->sessionId);
     }
     if ($this->securityContext->getToken() !== $token) {
         $this->securityContext->setToken($token);
     }
     return $token;
 }
Beispiel #26
0
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$request->headers->has('Authentication')) {
         $event->setResponse($this->createForbiddenResponse());
         return;
     }
     $authenticationToken = $request->headers->get('Authentication');
     $userAgent = $request->headers->get('user-agent');
     $token = new ApiToken();
     $token->authenticationToken = $authenticationToken;
     $token->userAgent = $userAgent;
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $e) {
         $event->setResponse($this->createForbiddenResponse());
     }
     $event->setResponse($this->createForbiddenResponse());
 }
Beispiel #27
0
 /**
  * @param GetResponseEvent $event The event.
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (false === $request->attributes->get('oauth_request_parameters')) {
         return;
     }
     $token = new OAuthToken();
     $token->setRequestParameters($request->attributes->get('oauth_request_parameters'));
     $token->setRequestMethod($request->attributes->get('oauth_request_method'));
     $token->setRequestUrl($request->attributes->get('oauth_request_url'));
     try {
         $returnValue = $this->authenticationManager->authenticate($token);
         if ($returnValue instanceof TokenInterface) {
             return $this->securityContext->setToken($returnValue);
         } elseif ($returnValue instanceof Response) {
             return $event->setResponse($returnValue);
         }
     } catch (AuthenticationException $e) {
         throw $e;
     }
     throw new HttpException(401);
 }
 /**
  * @param ConsoleCommandEvent $event
  */
 public function onConsoleCommand(ConsoleCommandEvent $event)
 {
     $command = $event->getCommand();
     $input = $event->getInput();
     $definition = $command->getApplication()->getDefinition();
     $definition->addOption(new InputOption(self::OPTION_USER, null, InputOption::VALUE_REQUIRED, 'ID, username or email of the user that should be used as current user'));
     $definition->addOption(new InputOption(self::OPTION_ORGANIZATION, null, InputOption::VALUE_REQUIRED, 'ID or name of the organization that should be used as current organization'));
     $user = $input->getParameterOption('--' . self::OPTION_USER);
     $organization = $input->getParameterOption('--' . self::OPTION_ORGANIZATION);
     if (!$user && !$organization) {
         return;
     }
     $token = $this->securityContext->getToken();
     if (!$token) {
         $token = new ConsoleToken();
         $this->securityContext->setToken($token);
     }
     $this->setUser($user, $token);
     if ($token instanceof OrganizationContextTokenInterface) {
         $this->setOrganization($organization, $token);
     }
 }
Beispiel #29
0
 /**
  * Performs the logout if requested.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event A GetResponseEvent instance
  *
  * @throws RuntimeException if the LogoutSuccessHandlerInterface instance does not return a response
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $response = $this->successHandler->onLogoutSuccess($request);
     if (!$response instanceof Response) {
         throw new \RuntimeException('Logout Success Handler did not return a Response.');
     }
     // handle multiple logout attempts gracefully
     if (null !== ($token = $this->securityContext->getToken())) {
         foreach ($this->handlers as $handler) {
             $handler->logout($request, $response, $token);
         }
     }
     $this->securityContext->setToken(null);
     $event->setResponse($response);
 }
Beispiel #30
0
 /**
  * manually login e.g for Tapatalk Extension
  * mtehod will be generate a cookie
  * @param type $username
  * @param type $password
  * @param \Symfony\Component\HttpFoundation\Request $request
  * @param type $providerKey
  * @param \Symfony\Component\HttpFoundation\Response $redirectResponse
  * @return boolean
  */
 public function login($username, $password, \Symfony\Component\HttpFoundation\Request $request, $providerKey, \Symfony\Component\HttpFoundation\Response $redirectResponse)
 {
     $user = $this->findByUsername($username);
     $encoder = $this->securityFactory->getEncoder($user);
     $password2 = $encoder->encodePassword($password, $user->getSalt());
     if ($user->getPassword() === $password2) {
         $token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken($user, $user->getPassword(), 'symbb', $user->getRoles());
         $this->securityContext->setToken($token);
         $securityKey = 'myKey';
         $random = new \Symfony\Component\Security\Core\Util\SecureRandom();
         $persistenService = new \Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices(array($this), $providerKey, $securityKey, array('path' => '/', 'name' => 'REMEMBERME', 'domain' => null, 'secure' => false, 'httponly' => true, 'lifetime' => 31536000, 'always_remember_me' => true, 'remember_me_parameter' => '_remember_me'), null, $random);
         $persistenService->setTokenProvider(new \Symfony\Component\Security\Core\Authentication\RememberMe\InMemoryTokenProvider());
         $persistenService->loginSuccess($request, $redirectResponse, $token);
         return true;
     }
     return false;
 }