public function handle(GetResponseEvent $event) { // getting request $request = $event->getRequest(); // getting attributes $apiClientToken = $request->attributes->get('apiClientToken'); $apiUserToken = $request->attributes->get('apiUserToken'); $apiServerAction = $request->attributes->get('apiAction'); /* @var $apiServerAction ApiServerAction */ // cleaning credentials and interface name $request->attributes->remove('apiClientToken'); $request->attributes->remove('apiUserToken'); // creating token $token = new Token($apiServerAction->getApiServerInterface()); $token->setCredentials([$apiClientToken, $apiUserToken]); try { // authenticating $authenticatedToken = $this->authenticationManager->authenticate($token); $this->tokenStorage->setToken($authenticatedToken); // getting authenticated user $user = $authenticatedToken->getUser(); /* @var $user User */ // setting request attributes $request->attributes->set('apiConnection', $user->getApiConnection()); $request->attributes->set('apiClient', $user->getApiClient()); $request->attributes->set('apiUser', $user->getApiUser()); } catch (\Exception $e) { $event->stopPropagation(); throw new AccessDeniedHttpException(null, $e); } }
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)); } } }
/** * @param GetResponseEvent $event */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); if (empty($request->headers->get("Authorization"))) { return; } $authHeader = $request->headers->get("Authorization"); if (strpos($authHeader, " ") === false) { return; } list($tokenType, $token) = explode(" ", $authHeader, 2); if (strtolower($tokenType) !== "bearer") { return; } // Verify that there is an access_token present /* if(empty($request->get("access_token"))) { return; } $token = $request->get("access_token");*/ $unauthenticatedToken = new OAuthToken(); $unauthenticatedToken->setToken($token); try { $authenticatedToken = $this->authenticationManager->authenticate($unauthenticatedToken); $this->tokenStorage->setToken($authenticatedToken); return; } catch (AuthenticationException $e) { if ($this->logger !== null) { $this->logger->notice("Access token authentication failed"); } } $response = new Response(); $response->setStatusCode(Response::HTTP_FORBIDDEN); $event->setResponse($response); }
/** * 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->tokenStorage->getToken(); if ($token instanceof TokenInterface) { $token->setUser(new User($apiUser)); // Don't embed if we already have a LegacyToken, to avoid nested session storage. if (!$token instanceof LegacyToken) { $this->tokenStorage->setToken(new LegacyToken($token)); } } } catch (NotFoundException $e) { // Invalid user ID, the user may have been removed => invalidate the token and the session. $this->tokenStorage->setToken(null); $session->invalidate(); } }
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 GetResponseEvent $event */ public function handle(GetResponseEvent $event) { if (null !== $this->tokenStorage->getToken()) { return; } $request = $event->getRequest(); $token = new PluginToken($this->providerKey, $request->get('integration', null)); try { $authToken = $this->authenticationManager->authenticate($token); if ($authToken instanceof PluginToken) { $response = $authToken->getResponse(); if ($authToken->isAuthenticated()) { $this->tokenStorage->setToken($authToken); if ('api' != $this->providerKey) { $response = $this->onSuccess($request, $authToken, $response); } } elseif (empty($response)) { throw new AuthenticationException('mautic.user.auth.error.invalidlogin'); } } } catch (AuthenticationException $exception) { if ('api' != $this->providerKey) { $response = $this->onFailure($request, $exception); } } if ($response) { $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->tokenStorage->setToken($authToken); return; } catch (AuthenticationException $failed) { $token = $this->tokenStorage->getToken(); if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) { $this->tokenStorage->setToken(null); } $message = $failed->getMessage(); } $response = new Response(); $response->setContent($message); $response->setStatusCode(403); $event->setResponse($response); }
/** * {@inheritdoc} */ 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)) { $response = new Response(); $response->setStatusCode(Response::HTTP_FORBIDDEN); $event->setResponse($response); return; } $token = new WsseToken(); $token->setUser($matches[1]); $token->digest = $matches[2]; $token->nonce = $matches[3]; $token->created = $matches[4]; try { $authToken = $this->authenticationManager->authenticate($token); $this->tokenStorage->setToken($authToken); return; } catch (AuthenticationException $failed) { //TODO: LOG } // By default deny authorization $response = new Response(); $response->setStatusCode(Response::HTTP_FORBIDDEN); $event->setResponse($response); }
/** * {@InheritDoc} */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); if (!$request->headers->has('x-wsse')) { return; } $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/'; if (1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) { 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->tokenStorage->setToken($authToken); return; } catch (AuthenticationException $e) { throw $e; // 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. // $token = $this->tokenStorage->getToken(); // if ($token instanceof WsseUserToken && $this->providerKey === $token->getProviderKey()) { // $this->tokenStorage->setToken(null); // } // return; } // By default deny authorization $response = new Response(); $response->setStatusCode(Response::HTTP_FORBIDDEN); $event->setResponse($response); }
/** * {@inheritdoc} */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); if (null !== ($authorization = $request->headers->get($this->authenticationHeaderName))) { $headerParts = array_map('trim', explode(' ', $authorization, 2)); if (2 === count($headerParts)) { $credentialParts = explode(':', $headerParts[1]); if (2 === count($credentialParts)) { $token = new HmacUserToken(); $token->setServiceLabel($headerParts[0]); $token->setUser($credentialParts[0]); $token->setSignature($credentialParts[1]); $token->setRequest($request); try { $authenticatedToken = $this->authenticationManager->authenticate($token); // Call setToken() on an instance of SecurityContextInterface or TokenStorageInterface (>=2.6) $this->tokenStorage->setToken($authenticatedToken); // Success return; } catch (AuthenticationException $exception) { } } } } $event->setResponse(new Response(null, 401)); }
/** * @param GetResponseEvent $event * * @return bool */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); switch ($this->getAuthType()) { case self::AUTH_TYPE_HEADER: $requestToken = $request->headers->get($this->getAuthKeyName()); break; case self::AUTH_TYPE_REQUEST: $requestToken = $request->get($this->getAuthKeyName()); break; default: throw new InvalidConfigurationException("Unknown auth type" . $this->getAuthType()); } if (!$requestToken) { throw new AuthenticationException('Empty authentication token'); } $requestTokenData = $this->parseAuthToken($requestToken); $token = new SignedUserToken(); $token->setUser($requestTokenData[0]); $token->setSignature($requestTokenData[1]); $token->setRequest($request); try { $authenticatedToken = $this->authManager->authenticate($token); $this->tokenStorage->setToken($authenticatedToken); return true; } catch (AuthenticationException $failed) { } $response = new Response('', Response::HTTP_FORBIDDEN); $event->setResponse($response); return false; }
/** * This interface must be implemented by firewall listeners. * * @param GetResponseEvent $event */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); if ($request->headers->has(static::AUTH_HEADER)) { $unauthenticatedToken = new ApiUserToken(); $unauthenticatedToken->setAttribute('key', $request->headers->get(static::AUTH_HEADER)); $authenticatedToken = $this->authenticationManager->authenticate($unauthenticatedToken); $this->tokenStorage->setToken($authenticatedToken); } }
/** * @param GetResponseEvent $event */ public function handle(GetResponseEvent $event) { parent::handle($event); $request = $event->getRequest(); $session = $request->getSession(); if ($session->has('requested_logout')) { $session->invalidate(); $this->securityTokenStorage->setToken(null); $event->setResponse($this->authenticationEntryPoint->start($request)); } }
/** * Initializes security context with an instance of a UserInterface * returned by $this->getUser() * * Method will be called automatically from ApplicationTestCase and * WebTestCase from this bundle and their children */ protected function setUpSecurityContext() { if (empty($this->container) || !$this->container instanceof ContainerInterface) { throw new \RuntimeException("Use the trait with a class that has an access to the container (ContainerInterface)."); } $this->tokenStorage = $this->container->get('security.token_storage'); $user = $this->getUser(); if ($user != null && $user instanceof UserInterface) { $this->tokenStorage->setToken(new UsernamePasswordToken($user, null, $this->getFirewallContext(), $user->getRoles())); } }
/** * Checks if a Wordpress user is authenticated and authenticate him into Symfony security context. * * @param Request $request */ protected function checkAuthentication(Request $request) { if (!$request->hasPreviousSession()) { return; } $session = $request->getSession(); if ($session->has('token')) { $token = $session->get('token'); $this->tokenStorage->setToken($token); } }
public function handle(GetResponseEvent $event) { try { $token = new Token(); $authenticatedToken = $this->authenticationManager->authenticate($token); $this->tokenStorage->setToken($authenticatedToken); } catch (\Exception $e) { $event->stopPropagation(); throw new AccessDeniedHttpException(null, $e); } }
public final function loginUser($firewallName, User $user, Response $response = null) { $this->userChecker->checkPostAuth($user); $token = $this->createToken($firewallName, $user); $request = $this->requestStack->getCurrentRequest(); if ($request == $this->requestStack->getMasterRequest()) { $this->sessionStrategy->onAuthentication($request, $token); } //TODO: implement rememberme $this->tokenStorage->setToken($token); }
/** * {@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->tokenStorage->setToken($token); $this->eventDispatcher->dispatch(UserEvents::SECURITY_IMPLICIT_LOGIN, new UserEvent($user)); }
/** * This interface must be implemented by firewall listeners. * * @param GetResponseEvent $event */ public function handle(GetResponseEvent $event) { try { $jwtTokenValue = $this->jwtRetrievalStrategy->getToken($event->getRequest()); } catch (JWTNotFoundException $e) { return; } $jwtToken = new JWTToken(); $jwtToken->setToken($jwtTokenValue); $authToken = $this->authenticationManager->authenticate($jwtToken); $this->tokenStorage->setToken($authToken); }
public function handle(GetResponseEvent $event) { $request = $event->getRequest(); // Check if authentication Token is present if ($request->headers->has('x-wsse')) { // Token parser $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/'; if (preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) { $token = new WsseUserToken(); $token->setUser($matches[1]); $token->digest = $matches[2]; $token->nonce = $matches[3]; $token->created = $matches[4]; try { // Authentication process $authToken = $this->authenticationManager->authenticate($token); $this->tokenStorage->setToken($authToken); return; } catch (AuthenticationException $failed) { $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. // $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); $response->setContent($failedMessage); $event->setResponse($response); return; } catch (NonceExpiredException $expired) { $failedMessage = 'WSSE Nonce Expired for ' . $token->getUsername() . '. Why ? ' . $failed->getMessage(); // $this->logger->err($failedMessage); // Deny authentication with a '403 Forbidden' HTTP response $response = new Response(); $response->setStatusCode(403); $response->setContent($failedMessage); $event->setResponse($response); return; } // By default deny authorization $response = new Response(); $response->setStatusCode(403); $event->setResponse($response); } } // By default deny authentication $response = new Response(); $response->setStatusCode(403); $event->setResponse($response); }
public function changePasswordAction(Request $request) { $this->changePasswordForm->handleRequest($request); if ($this->changePasswordForm->isValid()) { $user = $this->tokenStorage->getToken()->getUser(); $formData = $this->changePasswordForm->getData(); $this->eventDispatcher->dispatch(AdminSecurityEvents::CHANGE_PASSWORD, new ChangePasswordEvent($user, $formData['plainPassword'])); $request->getSession()->invalidate(); $this->tokenStorage->setToken(null); $request->getSession()->getFlashBag()->set('success', 'admin.change_password_message.success'); return new RedirectResponse($this->router->generate('fsi_admin_security_user_login')); } return $this->templating->renderResponse($this->changePasswordActionTemplate, array('form' => $this->changePasswordForm->createView())); }
/** * 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->tokenStorage->setToken($interactiveToken); }
/** * Initialize the SecurityContext from the given $stepExecution * * @param StepExecution $stepExecution */ protected function initSecurityContext(StepExecution $stepExecution) { $username = $stepExecution->getJobExecution()->getUser(); $user = $this->userProvider->loadUserByUsername($username); $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); $this->tokenStorage->setToken($token); }
/** * Restores the original user token. * * @param RunAsUserToken $runAsToken */ private function restoreOriginalToken(RunAsUserToken $runAsToken) { if (null !== $this->logger) { $this->logger->debug('Populating TokenStorage with original Token.'); } $this->tokenStorage->setToken($runAsToken->getOriginalToken()); }
/** * @param GetResponseEvent $event */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); $jwtString = $this->getJwtString($request); if (empty($jwtString)) { return; } $jwt = $this->decoderService->parse(new StringLiteral($jwtString)); $token = new JwtUserToken($jwt); try { $authenticatedToken = $this->authenticationManager->authenticate($token); $this->tokenStorage->setToken($authenticatedToken); } catch (AuthenticationException $e) { $event->setResponse(new Response($e->getMessage(), 401)); } }
/** * This interface must be implemented by firewall listeners. * * @param GetResponseEvent $event */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); $requestToken = $this->getToken($request->headers->get($this->options['header_name'], null)); if (!empty($requestToken)) { try { $decoded = $this->encode->decode($requestToken); $token = new JWTToken(); $token->setTokenContext($decoded); $authToken = $this->authenticationManager->authenticate($token); $this->securityContext->setToken($authToken); } catch (HttpEncodingException $e) { } catch (\UnexpectedValueException $e) { } } }
/** * @param GetResponseEvent $event */ public function handle(GetResponseEvent $event) { $user = $this->userSessionService->getMinimalUserInfo(); if (!is_null($user)) { $token = new UiTIDToken(); $token->setUser((string) $user->getId()); try { $authToken = $this->authenticationManager->authenticate($token); $this->tokenStorage->setToken($authToken); return; } catch (AuthenticationException $exception) { } } $response = new Response('Unauthorized access.', Response::HTTP_UNAUTHORIZED); $event->setResponse($response); }
/** * {@inheritDoc} */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); // Requests require an Authorization header. if (!$request->headers->has('Authorization')) { $event->setResponse($this->entryPoint->start($request)); return; } $token = new HmacToken($request); try { $authToken = $this->authManager->authenticate($token); $this->tokenStorage->setToken($authToken); $request->attributes->set('hmac.key', $authToken->getCredentials()); } catch (AuthenticationException $e) { $event->setResponse($this->entryPoint->start($request, $e)); } }
/** * @param User $user */ public function manualLogin(User $user) { $token = new UsernamePasswordToken($user, null, "main", $user->getGroupRoles()); $this->tokenStorage->setToken($token); //now dispatch the login event $event = new InteractiveLoginEvent($this->requestStack->getMasterRequest(), $token); $this->eventDispatcher->dispatch("security.interactive_login", $event); }
/** * {@inheritdoc} */ public function authenticate(TokenInterface $token) { $provider = new DaoAuthenticationProvider($this->userProvider, $this->userChecker, $this->firewall, $this->encoderFactory); $authenticationProviderManager = new AuthenticationProviderManager([$provider]); $authenticatedToken = $authenticationProviderManager->authenticate($token); $this->tokenStorage->setToken($authenticatedToken); //now the user is logged in $this->session->set("_{$this->firewall}", serialize($authenticatedToken)); //now dispatch the login event $event = new InteractiveLoginEvent($this->request, $authenticatedToken); $this->eventDispatcher->dispatch('security.interactive_login', $event); return $authenticatedToken; }