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)); } } }
/** * @Route("/checkIn", name="loginCheck") * @Template() */ public function checkInAction() { if (isset($_GET['connectData'])) { //Jeżeli są dane, to loguje $wykop = $this->get('WykopApi'); $connect_data = $wykop->handleConnectData(); $session = new Session(); $session->set('token', $connect_data['token']); $session->set('sign', $connect_data['sign']); $profile = $wykop->doRequest('profile/index/' . $connect_data['login']); if (!$wykop->isValid()) { throw new Exception($this->api->getError()); } else { $answer = $wykop->doRequest('user/login', array('login' => $profile['login'], 'accountkey' => $session->get('token'))); if (!$wykop->isValid()) { throw new Exception($this->api->getError()); } $roles = ['ROLE_USER_WYKOP']; if ($profile['login'] === 'anonim1133') { $roles[] = 'ROLE_ADMIN'; } $token = new UsernamePasswordToken($profile['login'], $answer['userkey'], 'wykop', $roles); $token->setAttribute('wykop_login', $profile['login']); $token->setAttribute('wykop_sex', $profile['sex']); $token->setAttribute('wykop_group', $profile['author_group']); $token->setAttribute('wykop_avatar', $profile['avatar_med']); $token->setAttribute('wykop_login_date', new \DateTime('now')); $this->get('security.token_storage')->setToken($token); $session->set('_security_main', serialize($token)); } } return $this->redirect('/'); }
/** * @test */ public function handleReturnResponse() { $token = new Token('someuser', 'somedigest', 'someproviderkey'); $token->setAttribute('nonce', 'somenonce'); $token->setAttribute('created', '2010-12-12 20:00:00'); $response = new Response(); $this->authenticationManager->expects($this->once())->method('authenticate')->with($token)->will($this->returnValue($response)); $this->responseEvent->expects($this->once())->method('setResponse')->with($response); $this->request->headers->add(array('X-WSSE' => 'UsernameToken Username="******", PasswordDigest="somedigest", Nonce="somenonce", Created="2010-12-12 20:00:00"')); $listener = new Listener($this->securityContext, $this->authenticationManager, 'someproviderkey', $this->authenticationEntryPoint); $listener->handle($this->responseEvent); }
/** * Set client id for ria client view and add ROLE_CLIENT_VIEW to ria * * @param User $ria * @param int $clientId * @throws \InvalidArgumentException */ public function setClientForRiaClientView(User $ria, $clientId) { $this->checkIsRiaUser($ria); $previousRoles = $this->securityContext->getToken()->getRoles(); $previousRoles[] = 'ROLE_CLIENT_VIEW'; //$ria->addRole('ROLE_CLIENT_VIEW'); //$token = new UsernamePasswordToken($ria, null, 'main', $ria->getRoles()); $token = new UsernamePasswordToken($ria, null, 'main', $previousRoles); $token->setAttribute('ria.client_view.client_id', $clientId); $this->securityContext->setToken($token); }
/** * Todo parece indicar que es en este lugar donde la magia pasa * @param TokenInterface $token * @return \Agenlad\Controller\ldapLogin\UsernamePasswordToken * @throws AuthenticationException */ public function authenticate(TokenInterface $token) { // TODO: La carga de este usuario debe suceder donde nuestro proveedor de usuarios, cosa que pasa por el momento // pero que tiene mucho trabajo por afinar $usuario = $this->userProvider->loadUserByUsername($token->getUsername()); $credenciales = $token->getCredentials(); if ($this->logueo($token->getUsername(), $credenciales)) { # La autenticacion es un éxito. Creamos un token autenticado $authenticatedToken = new UsernamePasswordToken($usuario->getUsername(), $credenciales, 'LdapAS', $usuario->getRoles()); // A continuación, llenamos el token con información sobre el usuario: // Resulta que en lugar de $user->getUsername debería ser $user, para mandar todo el objeto a // guardarse en el token, // TODO: Por el momento no encuentro la manera de registrar la // clase ldapUser como un ¿Proveedor valido? $authenticatedToken->setAttribute('dnUser', $usuario->getDnUser()); $authenticatedToken->setAttribute('credencial', $credenciales); $authenticatedToken->setAttribute('dominio', $usuario->getDominio()); return $authenticatedToken; } else { throw new AuthenticationException('La autenticacion contra LDAP ha fallado'); } }
/** * {@inheritdoc} */ protected function attemptAuthentication(Request $request) { $this->logger->info("adminListener attempting authentication!"); if ($this->options['post_only'] && 'post' !== strtolower($request->getMethod())) { if (null !== $this->logger) { $this->logger->debug(sprintf('Authentication method not supported: %s.', $request->getMethod())); } return null; } $username = trim($request->get($this->options['username_parameter'])); $password = $request->get($this->options['password_parameter']); $user = $request->get($this->options['user_parameter']); $token = new UsernamePasswordToken($username, $password, $this->providerKey); if (null !== $user) { $token->setAttribute('desired_user', $user); } return $this->authenticationManager->authenticate($token); }
function it_should_call_a_login_success_event() { $credentials = $this->credentials; $credentials['ldap_domain'] = ''; $user = new LdapUser(new LdapObject(['username' => 'foo'])); $token = new UsernamePasswordToken($user, $credentials['password'], 'ldap-tools', $user->getRoles()); $token->setAttribute('ldap_domain', ''); $this->connection->execute(new AuthenticationOperation('foo', 'bar'))->shouldBeCalled()->willReturn(new AuthenticationResponse(true)); $this->checkCredentials($credentials, $user)->shouldReturn(true); $this->dispatcher->dispatch('ldap_tools_bundle.login.success', new LdapLoginEvent($user, $token))->shouldBeCalled(); }
/** * {@inheritdoc} */ public function checkCredentials($credentials, UserInterface $user) { $domain = $this->ldap->getDomainContext(); try { $this->switchDomainIfNeeded($credentials); /** @var \LdapTools\Operation\AuthenticationResponse $response */ $response = $this->ldap->getConnection()->execute(new AuthenticationOperation($user->getUsername(), $credentials['password'])); if (!$response->isAuthenticated()) { $this->userChecker->checkLdapErrorCode($user, $response->getErrorCode(), $this->ldap->getConnection()->getConfig()->getLdapType()); throw new CustomUserMessageAuthenticationException($response->getErrorMessage(), [], $response->getErrorCode()); } // No way to get the token from the Guard, need to create one to pass... $token = new UsernamePasswordToken($user, $credentials['password'], 'ldap-tools', $user->getRoles()); $token->setAttribute('ldap_domain', isset($credentials['ldap_domain']) ? $credentials['ldap_domain'] : ''); $this->dispatcher->dispatch(LdapLoginEvent::SUCCESS, new LdapLoginEvent($user, $token)); } catch (\Exception $e) { $this->hideOrThrow($e); } finally { $this->domain = $this->ldap->getDomainContext(); $this->switchDomainBackIfNeeded($domain); } return true; }
/** * @test * @depends validateDigestWithNonceDirExpectedException * @depends validateDigestWithNonceDir * @depends validateDigestWithoutNonceDir * @depends validateDigestExpireTime */ public function authenticate() { $this->user->expects($this->once())->method('getPassword')->will($this->returnValue('somesecret')); $this->user->expects($this->once())->method('getSalt')->will($this->returnValue('somesalt')); $this->user->expects($this->once())->method('getRoles')->will($this->returnValue(array())); $this->userProvider->expects($this->once())->method('loadUserByUsername')->will($this->returnValue($this->user)); $encoder = new MessageDigestPasswordEncoder('sha1', true, 1); $time = date(DATE_ISO8601); $digest = $encoder->encodePassword(sprintf('%s%s%s', 'somenonce', $time, 'somesecret'), 'somesalt'); $expected = new Token($this->user, $digest, $this->providerKey); $time = date(DATE_ISO8601); $digest = $encoder->encodePassword(sprintf('%s%s%s', 'somenonce', $time, 'somesecret'), 'somesalt'); $token = new Token($this->user, $digest, $this->providerKey); $token->setAttribute('nonce', base64_encode('somenonce')); $token->setAttribute('created', $time); $provider = new CustomProvider($this->userProvider, $this->providerKey, $this->encoder, $this->nonceCache); $result = $provider->authenticate($token); $this->assertEquals($expected, $result); }
/** * Add the domain name for the login request to the token if specified. * * @param Request $request * @param UsernamePasswordToken $token */ protected function addDomainToTokenIfPresent(Request $request, UsernamePasswordToken $token) { if ($this->options['post_only'] && $request->request->has($this->options['domain_parameter'])) { $token->setAttribute('ldap_domain', trim($this->getParameterFromBag($request->request, $this->options['domain_parameter']))); } elseif ($domain = trim($this->getParameterFromRequest($request, $this->options['domain_parameter']))) { $token->setAttribute('ldap_domain', $domain); } }