public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { // 检查 user provider if (!$userProvider instanceof HybridUserProvider) { throw new \InvalidArgumentException(sprintf('The user provider must be an instance of HybridUserProvider (%s was given).', get_class($userProvider))); } $credential = $token->getCredentials(); $user = $token->getUser(); if ($user instanceof HybridUser) { return new PreAuthenticatedToken($user, $credential, $providerKey, $user->getRoles()); } if ($credential['type'] === 'sso') { // 检查 SSO token $username = $userProvider->getUsernameForToken($credential['token']); if (!$username) { throw new AuthenticationException('统一身份登录会话无效,可能会话已过期。'); } } else { if ($token->getCredentials()['type'] === 'internal') { $username = $userProvider->getUsernameForInternalUser($credential['user'], $credential['pass']); if (!$username) { throw new AuthenticationException('用户名或密码错误。'); } } else { throw new AccessDeniedException('不支持的登录认证类型。'); } } $user = $userProvider->loadUserByUsername($username); return new PreAuthenticatedToken($user, $credential, $providerKey, $user->getRoles()); }
/** * @param TokenInterface $token * @param UserProviderInterface $userProvider * @param string $providerKey * * @return PreAuthenticatedToken */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { if (!($user = $token->getUser()) instanceof UserInterface) { $user = $this->userProvider->loadUserByUsername($token->getCredentials()); } return new PreAuthenticatedToken($user, $token->getCredentials(), $providerKey, $user->getRoles()); }
public function authenticate(TokenInterface $token) { $user = $this->userProvider->loadUserByUsername($token->getUsername()); if ($user && $this->validateDigest($token->getCredentials(), $token->getAttribute('nonce'), $token->getAttribute('created'), $this->getSecret($user), $this->getSalt($user))) { $authenticatedToken = new Token($user, $token->getCredentials(), $this->providerKey, $user->getRoles()); return $authenticatedToken; } throw new AuthenticationException('WSSE authentication failed.'); }
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { $user = $userProvider->loadUserByUsername($token->getUsername()); $this->userChecker->checkPreAuth($user); if (!$this->encoder->isPasswordValid($user, $token->getCredentials())) { throw new BadCredentialsException('The presented password is invalid.'); } $this->userChecker->checkPostAuth($user); return new UsernamePasswordToken($user, $token->getCredentials(), $providerKey, $user->getRoles()); }
/** * {@inheritdoc} */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { if (is_subclass_of($token->getUser(), $this->userClass)) { return new PreAuthenticatedToken($token->getUser(), $token->getCredentials(), $providerKey, $token->getUser()->getRoles()); } $ssoToken = $this->tokenRepository->find($token->getCredentials()); if (!$ssoToken) { throw new AuthenticationException(); } $user = $userProvider->loadUserByUsername($ssoToken->getUsername()); return new PreAuthenticatedToken($user, $token->getCredentials(), $providerKey, $user->getRoles()); }
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { if (!$userProvider instanceof RedmineUserProvider) { throw new \InvalidArgumentException(sprintf('The user provider must be an instance of RedmineUserProvider (%s was given).', get_class($userProvider))); } $apiKey = $token->getCredentials(); $user = $userProvider->getUserForUsernamePassword($token->getUsername(), $token->getCredentials()); if (!$user) { throw new AuthenticationException('Invalid credentials'); } return new UsernamePasswordToken($user, $apiKey, $providerKey, $user->getRoles()); }
/** * Attempts to authenticate a TokenInterface object. * * @param TokenInterface $token The TokenInterface instance to authenticate * * @return TokenInterface An authenticated TokenInterface instance, never null * * @throws AuthenticationException if the authentication fails */ public function authenticate(TokenInterface $token) { if (!$token instanceof JWTToken) { throw new AuthenticationException(sprintf('%s works only for JWTToken', __CLASS__)); } if (!$token->getCredentials()) { throw new AuthenticationException('JWTToken must contain a token in order to authenticate.'); } $decodedToken = $this->JWTDecoder->decode($token->getCredentials()); $user = $this->userConverter->buildUserFromToken($decodedToken); $token->setUser($user); return $token; }
public function authenticate(TokenInterface $token) { $user = $this->userProvider->loadUserByUsername($token->getUser(), $token->getCredentials()); $newToken = new UserToken($token->getUser(), $token->getCredentials(), "main", $user->getRoles()); $encoder = $this->encoder->getEncoder($user); // compute the encoded password $encodedPassword = $encoder->encodePassword($token->getCredentials(), $user->salt); $newToken = new UserToken($token->getUser(), $token->getCredentials(), "secured_area", $user->getRoles()); $username = $newToken->getUser(); if (empty($username) || $user->getPassword() != $encodedPassword) { throw new BadCredentialsException('Bad credentials :)'); } return $newToken; }
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { if (!$userProvider instanceof EntityUserProvider) { throw new \InvalidArgumentException(sprintf('The user provider must be an instance of EntityUserProvider (%s was given).', get_class($userProvider))); } try { $jwt = $token->getCredentials(); $username = $this->jwtManager->getUserIdFromToken($jwt); $issuedAt = $this->jwtManager->getIssuedAtFromToken($jwt); } catch (\UnexpectedValueException $e) { throw new BadCredentialsException('Invalid JSON Web Token: ' . $e->getMessage()); } catch (\Exception $e) { throw new BadCredentialsException('Invalid JSON Web Token'); } $user = $userProvider->loadUserByUsername($username); $authentication = $user->getAuthentication(); if ($authentication) { $tokenNotValidBefore = $authentication->getInvalidateTokenIssuedBefore(); if ($tokenNotValidBefore) { if ($tokenNotValidBefore > $issuedAt) { throw new BadCredentialsException('Invalid JSON Web Token: Not issued before ' . $tokenNotValidBefore->format('c')); } } } $authenticatedToken = new PreAuthenticatedToken($user, $jwt, $providerKey); $authenticatedToken->setAuthenticated(true); return $authenticatedToken; }
/** * {@inheritdoc} */ public function authenticate(TokenInterface $token, UserProviderInterface $userProvider) { $this->googleClient->authenticate($token->getCredentials()); $this->gtoken = json_decode($this->googleClient->getAccessToken()); $attributes = $this->googleClient->verifyIdToken($this->gtoken->id_token)->getAttributes(); return $attributes["payload"]["sub"]; }
/** * {@inheritDoc} */ public function authenticate(TokenInterface $token) { $resourceOwner = $this->resourceOwnerMap->getResourceOwnerByName($token->getResourceOwnerName()); $userResponse = $resourceOwner->getUserInformation($token->getCredentials()); try { $user = $this->userProvider->loadUserByOAuthUserResponse($userResponse); } catch (OAuthAwareExceptionInterface $e) { $e->setAccessToken($token->getCredentials()); $e->setResourceOwnerName($token->getResourceOwnerName()); throw $e; } $token = new OAuthToken($token->getCredentials(), $user->getRoles()); $token->setUser($user); $token->setAuthenticated(true); return $token; }
/** * Attempts to authenticate a GrantToken * * @param GrantToken $token * * @return GrantToken * * @throws AuthenticationException */ public function authenticate(TokenInterface $token) { $credentials = $token->getCredentials(); $clientId = $credentials['client_id']; /** @var ClientInterface $client */ $client = $this->clientRepository->find($clientId); // Verify client id if (!$client) { throw new AuthenticationException("Client with id {$clientId} does not exist"); } // Verify client secret $clientSecret = $credentials['client_secret']; if (!$client->getSecret() === $clientSecret) { throw new AuthenticationException("Invalid client secret"); } // Verify grant type if (!in_array($token->getGrantType(), $client->getAllowedGrantTypes())) { throw new AuthenticationException("Grant type not allowed"); } if ($client->getUser() === null) { throw new AuthenticationException("Client is not associated with any user"); } $token->setUser($client->getUser()); $token->setClient($client); return $token; }
/** * Attempts to authenticate a TokenInterface object. * * @param TokenInterface $token The TokenInterface instance to authenticate * * @throws AuthenticationException if the authentication fails * @return TokenInterface An authenticated TokenInterface instance, never null * */ public function authenticate(TokenInterface $token) { if (!$token instanceof JWTToken) { throw new AuthenticationException(sprintf('%s works only for JWTToken', __CLASS__)); } if (!$token->getCredentials()) { throw new AuthenticationException('JWTToken must contain a token in order to authenticate.'); } try { $user = $this->userBuilder->buildUserFromToken($token->getCredentials()); } catch (JWTDecodeUnexpectedValueException $e) { throw new AuthenticationException('Failed to decode the JWT'); } $token->setUser($user); return $token; }
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { try { $this->resourceServer->isValidRequest(true); } catch (AccessDeniedException $e) { throw new AuthenticationException(sprintf('OAuth token "%s" does not exist or is expired.', $token->getCredentials())); } $userIdentifier = $this->resourceServer->getAccessToken()->getSession()->getOwnerId(); try { $user = $userProvider->loadUserByUsername($userIdentifier); } catch (UsernameNotFoundException $e) { $e->setUsername($userIdentifier); throw $e; } return new PreAuthenticatedToken($user, $token->getCredentials(), $providerKey, $user->getRoles()); }
/** * {@inheritdoc} */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { if (!$userProvider instanceof UserManager) { throw new \InvalidArgumentException(sprintf('The user provider must be an instance of UserManager (%s was given).', get_class($userProvider))); } $user = $token->getUser(); if ($user instanceof AbstractUser) { return new SauthToken($user, $token->getCredentials(), $providerKey, $user->getRoles()); } $service = $this->oauth->getService($token->getServiceId()); $userId = $service->authenticate($token, $userProvider); if (!$userId) { throw new AuthenticationException(sprintf('Authentication Problem.')); } $credentials = $userProvider->getCredentials($token->getServiceId(), $userId); if ($credentials) { $user = $credentials->getUser(); } else { $username = $service->getUsername($userId); $user = $userProvider->loadUserByUsername($username); if (!$user) { if ($this->allowRegistration === false) { throw new AccessDeniedException("We couldn't find a user matching these credentials. New registrations are currently closed."); } $user = $userProvider->createNew($username); } $userProvider->saveCredentials($user, $token->getServiceId(), $userId, $service->getUserTokens()); } return new SauthToken($user, $token->getCredentials(), $providerKey, $user->getRoles()); }
/** * @param string $providerKey */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { $credentials = $token->getCredentials(); if (abs(time() - (int) $credentials[self::TIMESTAMP]) > 60) { throw new AuthenticationException('API credentials invalid. The timestamp is more than 60 seconds old.'); } $user = $this->em->find("OverwatchUserBundle:User", $credentials[self::USER_ID]); if ($user === null || $user->isLocked()) { throw new AuthenticationException('API credentials invalid. User not found.'); } $apiToken = hash_hmac("sha256", "timestamp=" . $credentials[self::TIMESTAMP], $user->getApiKey()); if ($apiToken !== $credentials[self::TOKEN]) { throw new AuthenticationException("API credentials invalid. Token verification failed."); } return new PreAuthenticatedToken($user, $token->getCredentials(), $providerKey, $user->getRoles()); }
/** * Attempts to authenticate a GrantToken * * @param GrantToken $token * * @return GrantToken * * @throws AuthenticationException */ public function authenticate(TokenInterface $token) { $credentials = $token->getCredentials(); $clientId = $credentials['client_id']; /** @var ClientInterface $client */ $client = $this->clientRepository->find($clientId); // Verify client id if (!$client) { throw new AuthenticationException("Client with id {$clientId} does not exist"); } // Verify client secret $clientSecret = $credentials['client_secret']; if (!$client->getSecret() === $clientSecret) { throw new AuthenticationException("Invalid client secret"); } // Verify grant type if (!in_array($token->getGrantType(), $client->getAllowedGrantTypes())) { throw new AuthenticationException("Grant type not allowed"); } // Verify refresh_token $refreshToken = $this->refreshTokenRepository->findOneBy(["token" => $credentials['refresh_token'], "client" => $client]); if ($refreshToken === null) { throw new AuthenticationException("Invalid token"); } // Verify expiry date if ($refreshToken->isExpired()) { throw new AuthenticationException("Token has expired"); } $user = $refreshToken->getUser(); $token->setUser($user); $token->setClient($client); return $token; }
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { $secret = $token->getCredentials(); $userData = $this->session->getFlashBag()->get('arcanys_sso_auth.user_data'); if ($userData) { // TODO create mapping config in the future $username = reset($userData['uid']); $email = reset($userData['email']); $firstname = reset($userData['firstname']); $lastname = reset($userData['lastname']); $token = reset($userData['token']); $roles = $userData['rights']; if (!$roles) { $roles = ['ROLE_USER']; } } else { $this->saml2->login(); exit; } if (!$username) { throw new AuthenticationException("Failed to authenticate from SSO"); } $user = $userProvider->loadUserByUsername(['username' => $username, 'email' => $email, 'firstname' => $firstname, 'lastname' => $lastname, 'token' => $token, 'roles' => $roles]); return new PreAuthenticatedToken($user, $secret, $providerKey, $user->getRoles($roles)); }
/** * @inheritdoc */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { try { $user = $userProvider->loadUserByUsername($token->getUsername()); } catch (UsernameNotFoundException $e) { throw new CustomUserMessageAuthenticationException('Invalid username or password'); } $username = $token->getUsername(); $password = $token->getCredentials(); $sessionCreationResult = null; try { $sessionCreationResult = $this->userSessionRepository->createSessionIdByCredentials($username, $password); } catch (\InvalidArgumentException $e) { throw new CustomUserMessageAuthenticationException('Invalid username or password'); } catch (RepositoryInfrastructureException $e) { throw new CustomUserMessageAuthenticationException('Cannot connect to Revive service'); } $passwordValid = $sessionCreationResult !== null && UserSessionCreationAuthenticationResult::isSuccess($sessionCreationResult->getSessionCreationAuthenticationResult()); if ($passwordValid) { $sessionId = $sessionCreationResult->getSessionId(); $roles = []; $roles[] = 'USER'; if (UserSessionCreationAuthorizationSessionCreationResult::isSuccess($sessionCreationResult->getSessionCreationAuthorizationSessionCreation())) { $roles[] = 'ADMIN'; } $token = new ReviveAuthenticationToken($user, $sessionId, $providerKey, $roles); return $token; } throw new CustomUserMessageAuthenticationException('Invalid username or password'); }
/** * @param TokenInterface $token * @return BlockCypherUserToken */ public function authenticate(TokenInterface $token) { // if (!$userProvider instanceof ApiKeyUserProvider) { // throw new \InvalidArgumentException( // sprintf( // 'The user provider must be an instance of ApiKeyUserProvider (%s was given).', // get_class($userProvider) // ) // ); // } //$blockCypherToken = null; $blockCypherToken = $token->getCredentials(); $username = $blockCypherToken; // DEBUG //var_dump($blockCypherToken); //die(); /** @var User $user */ $user = $this->userProvider->loadUserByUsername($username); // DEBUG //var_dump($user); //die(); if ($user) { $blockCypherToken = $user->getBlockCypherToken(); } if ($user && $this->validateBlockCypherToken($blockCypherToken)) { $authenticatedToken = new BlockCypherUserToken($user, $blockCypherToken, 'blockcypher', $user->getRoles()); //$authenticatedToken->setUser($user); return $authenticatedToken; } throw new AuthenticationException('BlockCypher token empty or invalid.'); }
/** * Attempt to authenticate the provided token using the provided user provider. * @param TokenInterface $token * @param UserProviderInterface $userProvider * @param string $providerKey * @return UsernamePasswordToken * @throws BadCredentialsException */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { if (($user = $userProvider->loadUserByUsername($token->getUsername())) && $user->getPassword() == $token->getCredentials()) { return new UsernamePasswordToken($user, $user->getPassword(), $providerKey, $user->getRoles()); } throw new BadCredentialsException('The presented password is invalid.'); }
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { $apiToken = $token->getCredentials(); if ($user = $this->userProvider->loadUserByToken($apiToken)) { return new PreAuthenticatedToken($user, $apiToken, $providerKey, $user->getRoles()); } throw new AuthenticationException('Wrong API token or token has expired'); }
/** * @param TokenInterface $token * @param UserProviderInterface $userProvider * @param $providerKey * @return UsernamePasswordToken */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { try { if ($userProvider instanceof IsidoreApiUserProvider) { $user = $userProvider->loadUser($token->getUsername(), $token->getCredentials()); } else { $user = $userProvider->loadUserByUsername($token->getUsername()); } } catch (UsernameNotFoundException $e) { throw new CustomUserMessageAuthenticationException("Identifiant ou mot de passe incorrect. Veuillez réessayer."); } $passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials()); if ($passwordValid) { return new UsernamePasswordToken($user, $user->getPassword(), $providerKey, $user->getRoles()); } throw new CustomUserMessageAuthenticationException("Identifiant ou mot de passe incorrect. Veuillez réessayer."); }
/** * Function used for user authentication based on token object * * @param \Symfony\Component\Security\Core\Authentication\Token\TokenInterface $token * @param \Symfony\Component\Security\Core\User\UserProviderInterface $userProvider * @param type $providerKey * @return \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken * @throws BadCredentialsException */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { $passwordValid = false; // Loda user object try { $user = $userProvider->loadUserByUsername($token->getUsername()); } catch (UsernameNotFoundException $e) { throw new BadCredentialsException('Invalid username or password', 0, $e); } // Check if ldap extension is enabled and user's ldap flag is set. if (null !== $this->ldapManager && $user->isLdapEnabled()) { try { $this->ldapManager->bind($token->getUsername(), $token->getCredentials()); $passwordValid = (bool) $this->ldapManager->getBoundUser(); if (null !== $this->logger && !$token->isAuthenticated()) { $this->logger->info("[LdapAuthenticator] Ldap authentication successful.", array('user' => $this->ldapManager->getBoundUser())); } } catch (\Zend\Ldap\Exception\LdapException $e) { throw new BadCredentialsException('Invalid username or password', 0, $e); } } else { $currentUser = $token->getUser(); if ($currentUser instanceof UserInterface) { if ($currentUser->getPassword() !== $user->getPassword()) { throw new BadCredentialsException('The credentials were changed from another session.'); } else { $passwordValid = true; } } else { if ("" === ($presentedPassword = $token->getCredentials())) { throw new BadCredentialsException('Invalid username or password.'); } if (!($passwordValid = $this->encoderFactory->getEncoder($user)->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt()))) { throw new BadCredentialsException('Invalid username or password.'); } } if (null !== $this->logger && !$token->isAuthenticated()) { $this->logger->info("[LdapAuthenticator] Local authentication successful.", array('user' => $user->getUsername())); } } // Set the authenticated token if ($passwordValid) { return new UsernamePasswordToken($user, $user->getPassword(), $providerKey, $user->getRoles()); } throw new BadCredentialsException('Invalid username or password'); }
/** * @param TokenInterface $token * @param JWTUserProviderInterface $userProvider * @param $providerKey * * @return PreAuthenticatedToken * * @throws \Symfony\Component\Security\Core\Exception\AuthenticationException */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { // The user provider should implement JWTUserProviderInterface if (!$userProvider instanceof JWTUserProviderInterface) { throw new InvalidArgumentException('Argument must implement interface Auth0\\JWTAuthBundle\\Security\\Core\\JWTUserProviderInterface'); } if ($token->getCredentials() === null) { $user = $userProvider->getAnonymousUser(); } else { // Get the user for the injected UserProvider $user = $userProvider->loadUserByJWT($token->getCredentials()); if (!$user) { throw new AuthenticationException(sprintf('Invalid JWT.')); } } return new PreAuthenticatedToken($user, $token, $providerKey, $user->getRoles()); }
/** * {@inheritDoc} */ public function authenticate(TokenInterface $token) { $username = $this->oauthProvider->getUsername($token->getCredentials()); $user = $this->userProvider->loadUserByUsername($username); $token = new OAuthToken($token->getCredentials(), $user->getRoles()); $token->setUser($user); $token->setAuthenticated(true); return $token; }
public function authenticate(TokenInterface $token) { $user = $this->userProvider->loadUserByUsername($token->getCredentials()); if ($user) { $token->setUser($user); return $token; } throw new AuthenticationException('Unable to get user for this token'); }
private function authenticatedToken(TokenInterface $token, UserInterface $user = null) { if (!$token instanceof OAuth2Token) { throw new Exception("token should be instance of OAuth2Token"); } $authenticatedToken = new OAuth2Token($token->getClient(), $user, $token->getCredentials(), $this->providerKey, $this->getRoles($token, $user)); $authenticatedToken->setAttributes($token->getAttributes()); return $authenticatedToken; }
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { $sessionKey = $token->getCredentials(); $user = $this->userProvider->getUserForSessionKey($sessionKey); if (!$user) { return new AnonymousToken($providerKey, 'anon.'); } return new PreAuthenticatedToken($user, $sessionKey, $providerKey, $user->getRoles()); }
/** * {@inheritdoc} */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { $apiKey = $token->getCredentials(); if (!$apiKey) { throw new AuthenticationException(sprintf('API key "%s" does not exist', $apiKey)); } $user = $this->userProvider->loadUserByUsername($apiKey); return new PreAuthenticatedToken($user, $apiKey, $providerKey, $user->getRoles()); }