php Symfony-Component-Security-Core-Util-StringUtils类(方法)实例源码

下面列出了php Symfony-Component-Security-Core-Util-StringUtils 类(方法)源码代码实例,从而了解它的用法。

作者:rolas12    项目:weather-homewor   
/**
  * {@inheritdoc}
  */
 public function isTokenValid(CsrfToken $token)
 {
     if (!$this->storage->hasToken($token->getId())) {
         return false;
     }
     return StringUtils::equals($this->storage->getToken($token->getId()), $token->getValue());
 }

作者:euskadi3    项目:OAuth2ServerServiceProvide   
/**
  * {@inheritdoc}
  */
 public function connect(Application $app)
 {
     $controllers = $app['controllers_factory'];
     $controllers->post('/oauth/token', function (Request $request) use($app) {
         $grantType = $request->request->get('grant_type');
         $clientId = $request->server->get('PHP_AUTH_USER', $request->request->get('client_id'));
         $secret = $request->server->get('PHP_AUTH_PW', $request->request->get('client_secret'));
         if (empty($clientId)) {
             throw new OAuthInvalidRequestException('Missing client_id parameter.');
         }
         if (empty($grantType)) {
             throw new OAuthInvalidRequestException('Missing grant_type parameter.');
         }
         $client = $app['oauth2.client.provider']->get($clientId);
         if (empty($client)) {
             throw new OAuthInvalidClientException('Unknown client');
         }
         if (!empty($secret) && !StringUtils::equals($client->getSecret(), $secret)) {
             throw new OAuthUnauthorizedClientException();
         }
         $grantType = $app['oauth2.grant_types']->get($grantType);
         if (!in_array($grantType->getName(), $client->getGrantTypes())) {
             throw new OAuthUnauthorizedClientException();
         }
         return $grantType->handle($request, $client);
     });
     return $controllers;
 }

作者:Dren-    项目:mobi   
/**
  * {@inheritdoc}
  */
 protected function processAutoLoginCookie(array $cookieParts, Request $request)
 {
     if (count($cookieParts) !== 4) {
         throw new AuthenticationException('The cookie is invalid.');
     }
     list($class, $username, $expires, $hash) = $cookieParts;
     if (false === ($username = base64_decode($username, true))) {
         throw new AuthenticationException('$username contains a character from outside the base64 alphabet.');
     }
     try {
         $user = $this->getUserProvider($class)->loadUserByUsername($username);
     } catch (\Exception $e) {
         if (!$e instanceof AuthenticationException) {
             $e = new AuthenticationException($e->getMessage(), $e->getCode(), $e);
         }
         throw $e;
     }
     if (!$user instanceof UserInterface) {
         throw new \RuntimeException(sprintf('The UserProviderInterface implementation must return an instance of UserInterface, but returned "%s".', get_class($user)));
     }
     if (true !== StringUtils::equals($this->generateCookieHash($class, $username, $expires, $user->getPassword()), $hash)) {
         throw new AuthenticationException('The cookie\'s hash is invalid.');
     }
     if ($expires < time()) {
         throw new AuthenticationException('The cookie has expired.');
     }
     return $user;
 }

作者:rastaafar    项目:shar   
function tokensMatch($request)
 {
     $token = $request->session()->token();
     $header = $request->header('x-xsrf-token');
     //in keys case sensitivity is important!!!!
     return StringUtils::equals($token, $request->input('_token')) || $header && StringUtils::equals($token, $header);
 }

作者:alcaly    项目:symfony-wss   
/**
  * {@InheritDoc}
  *
  * @throws NonceExpiredException
  */
 public function validateDigest(WsseUserToken $wsseToken, UserInterface $user)
 {
     $created = $wsseToken->created;
     $nonce = $wsseToken->nonce;
     $digest = $wsseToken->digest;
     $secret = $user->getPassword();
     // Check created time is not too far in the future (leaves 5 minutes margin)
     if (strtotime($created) > time() + 300) {
         throw new WsseAuthenticationException(sprintf('Token created date cannot be in future (%d seconds in the future).', time() - strtotime($created)));
     }
     // Expire timestamp after 5 minutes
     if (strtotime($created) < time() - 300) {
         throw new WsseAuthenticationException(sprintf('Token created date has expired its 300 seconds of validity (%d seconds).', strtotime($created) - time()));
     }
     // Validate that the nonce is *not* used in the last 10 minutes
     // if it has, this could be a replay attack
     if (file_exists($this->cacheDir . '/' . $nonce) && file_get_contents($this->cacheDir . '/' . $nonce) + 600 > time()) {
         throw new NonceExpiredException('Previously used nonce detected.');
     }
     // If cache directory does not exist we create it
     if (!is_dir($this->cacheDir)) {
         mkdir($this->cacheDir, 0777, true);
     }
     file_put_contents($this->cacheDir . '/' . $nonce, time());
     // Validate Secret
     $expected = base64_encode(sha1(base64_decode($nonce) . $created . $secret, true));
     if (!StringUtils::equals($expected, $digest)) {
         throw new WsseAuthenticationException('Token digest is not valid.');
     }
     return true;
 }

作者:amomi    项目:symf-tst-apisecurit   
/**
  * This function is specific to Wsse authentication and is only used to help this example
  *
  * For more information specific to the logic here, see
  * https://github.com/symfony/symfony-docs/pull/3134#issuecomment-27699129
  */
 protected function validateDigest($digest, $nonce, $created, $secret)
 {
     // Check created time is not in the future
     if (strtotime($created) > time()) {
         return false;
     }
     // Expire timestamp after 5 minutes
     if (time() - strtotime($created) > 300) {
         return false;
     }
     // Validate that the nonce is *not* used in the last 5 minutes
     // if it has, this could be a replay attack
     if (file_exists($this->cacheDir . '/' . $nonce) && file_get_contents($this->cacheDir . '/' . $nonce) + 300 > time()) {
         throw new NonceExpiredException('Previously used nonce detected');
     }
     // If cache directory does not exist we create it
     if (!is_dir($this->cacheDir)) {
         mkdir($this->cacheDir, 0777, true);
     }
     file_put_contents($this->cacheDir . '/' . $nonce, time());
     // Validate Secret
     //$expected = base64_encode(sha1(base64_decode($nonce).$created.$secret, true));
     $expected = base64_encode(self::createDigest(base64_decode($nonce), $created, $secret));
     return StringUtils::equals($expected, $digest);
 }

作者:GeorgeShazkh    项目:micros-de-conc   
/**
  * Determine if the session and input CSRF tokens match.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return bool
  */
 protected function tokensMatch($request)
 {
     $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
     if (!$token && ($header = $request->header('X-XSRF-TOKEN'))) {
         $token = $this->encrypter->decrypt($header);
     }
     return StringUtils::equals($request->session()->token(), $token);
 }

作者:artems    项目:veer-cor   
public function handle()
 {
     $token = app('request')->input('_token') ?: app('request')->header('X-CSRF-TOKEN');
     if (!$token && ($header = app('request')->header('X-XSRF-TOKEN'))) {
         $token = app('encrypter')->decrypt($header);
     }
     if (StringUtils::equals(app('request')->session()->token(), $token)) {
         return true;
     }
     return false;
 }

作者:BusinessCookie    项目:CoffeeMachineProjec   
/**
  * {@inheritdoc}
  */
 public function isCsrfTokenValid($intention, $token)
 {
     $expectedToken = $this->generateCsrfToken($intention);
     if (function_exists('hash_equals')) {
         return hash_equals($expectedToken, $token);
     }
     if (class_exists('Symfony\\Component\\Security\\Core\\Util\\StringUtils')) {
         return StringUtils::equals($expectedToken, $token);
     }
     return $token === $expectedToken;
 }

作者:Covert-Infern    项目:evetoo   
/**
  * @Route("/sso_callback", name="sso_callback")
  */
 public function callbackAction(Request $request)
 {
     $state = $request->query->get('state', null);
     $code = $request->query->get('code', null);
     $session = $this->get('session');
     $nonce = $session->get('eve_sso_nonce');
     $session->remove('eve_sso_nonce');
     if (!StringUtils::equals($nonce, $state)) {
         $session->getFlashBag()->add('danger', 'Invalid CSRF Token - Refresh the page.');
         return $this->redirect($this->generateUrl('default'));
     }
     $auth_uri = "https://login.eveonline.com/oauth/token";
     $creds = [trim($this->container->getParameter('eve_client_id')), trim($this->container->getParameter('eve_client_secret'))];
     /*
      * LOOK OUT FOR THE SPACE
      */
     $auth_request = new \GuzzleHttp\Psr7\Request('POST', $auth_uri, ['Content-Type' => 'application/x-www-form-urlencoded', 'Authorization' => 'Basic ' . base64_encode(implode(":", $creds))], "grant_type=authorization_code&code={$code}");
     try {
         $response = $this->tryRequest($auth_request);
     } catch (\Exception $e) {
         $session->getFlashBag()->add('danger', 'There was a problem with your request<i>Try Again - if this persists - Submit an issue ticket using the link in the footer.</i></b>');
         return $this->redirect($this->generateUrl('eve.register'));
     }
     $response_content = json_decode($response->getBody()->getContents());
     $token = $response_content->access_token;
     $verify_uri = "https://login.eveonline.com/oauth/verify";
     $verfiyRequest = new \GuzzleHttp\Psr7\Request('GET', $verify_uri, ['Authorization' => 'Bearer ' . $token]);
     try {
         $charResponse = $this->tryRequest($verfiyRequest);
     } catch (\Exception $e) {
         $session->getFlashBag()->add('danger', 'There was a problem with your request<i>Try Again - if this persists - Submit an issue ticket using the link in the footer.</i></b>');
         return $this->redirect($this->generateUrl('eve.register'));
     }
     $decoded = json_decode($charResponse->getBody()->getContents());
     $cId = $decoded->CharacterID;
     $cName = $decoded->CharacterName;
     $exists = $this->getDoctrine()->getRepository('AppBundle:CorporationMember')->findOneBy(['character_id' => intval($cId)]);
     // character isnt in a corp that is registered by an admin
     if ($exists === null) {
         $session->getFlashBag()->add('warning', 'Sorry we do not support non-alpha tester registrations at this time.<br><b>COME BACK SOON</b> or make a request to add your corproation through a support ticket below.');
         $this->get('logger')->info(sprintf("ATTEMPTED REGISTRATION: char_id = %s char_name = %s", $cId, $cName));
         return $this->redirect($this->generateUrl('eve.register'));
     } else {
         $user = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy(['username' => strtolower(str_replace(' ', '_', trim($exists->getCharacterName())))]);
         if ($user instanceof User) {
             $session->getFlashBag()->add('warning', 'This character is already associated with a user. IF you have forgot your username or password please see the link below');
             return $this->redirect($this->generateUrl('eve.register'));
         }
         // all is well
         $session->set('registration_authorized', ['id' => $cId, 'name' => $cName]);
         return $this->redirect($this->generateUrl('fos_user_registration_register'));
     }
 }

作者:anlutr    项目:l4-cor   
public function filter(Route $route, Request $request)
 {
     $token = $request->input('_token');
     if (!$token) {
         $token = $request->headers->get('X-XSRF-TOKEN');
     }
     if (!$token) {
         $token = $request->cookie('XSRF-TOKEN');
     }
     if (!StringUtils::equals($this->session->token(), $token)) {
         throw new TokenMismatchException();
     }
     if ($this->regenerate) {
         $this->session->regenerateToken();
     }
 }

作者:BusinessCookie    项目:CoffeeMachineProjec   
/**
  * {@inheritdoc}
  */
 protected function processAutoLoginCookie(array $cookieParts, Request $request)
 {
     if (count($cookieParts) !== 2) {
         throw new AuthenticationException('The cookie is invalid.');
     }
     list($series, $tokenValue) = $cookieParts;
     $persistentToken = $this->tokenProvider->loadTokenBySeries($series);
     if (!StringUtils::equals($persistentToken->getTokenValue(), $tokenValue)) {
         throw new CookieTheftException('This token was already used. The account is possibly compromised.');
     }
     if ($persistentToken->getLastUsed()->getTimestamp() + $this->options['lifetime'] < time()) {
         throw new AuthenticationException('The cookie has expired.');
     }
     $tokenValue = base64_encode($this->secureRandom->nextBytes(64));
     $this->tokenProvider->updateToken($series, $tokenValue, new \DateTime());
     $request->attributes->set(self::COOKIE_ATTR_NAME, new Cookie($this->options['name'], $this->encodeCookie(array($series, $tokenValue)), time() + $this->options['lifetime'], $this->options['path'], $this->options['domain'], $this->options['secure'], $this->options['httponly']));
     return $this->getUserProvider($persistentToken->getClass())->loadUserByUsername($persistentToken->getUsername());
 }

作者:euskadi3    项目:OAuth2ServerServiceProvide   
/**
  * {@inheritdoc}
  */
 public function verify($url, $key, $signature = null)
 {
     if (strpos($url, 'sign=') !== false) {
         $params = [];
         parse_str(parse_url($url, PHP_URL_QUERY), $params);
         if (isset($params['sign'])) {
             if (empty($signature)) {
                 $signature = $params['sign'];
             }
             unset($params['sign']);
         }
         $url = http_build_url($url, ['query' => http_build_query($params)], HTTP_URL_STRIP_FRAGMENT | HTTP_URL_REPLACE);
     }
     if (empty($signature)) {
         throw new InvalidArgumentException('Signature argument not found.');
     }
     $expected = $this->sign($url, $key);
     return StringUtils::equals($expected, $signature);
 }

作者:Remnant-Legio    项目:ea   
/**
  * @Route("/sso_callback", name="sso_callback")
  */
 public function callbackAction(Request $request)
 {
     $state = $request->query->get('state', null);
     $code = $request->query->get('code', null);
     $session = $this->get('session');
     $nonce = $session->get('eve_sso_nonce');
     $session->remove('eve_sso_nonce');
     if (!StringUtils::equals($nonce, $state)) {
         return $this->redirect($this->generateUrl('eve.register'));
     }
     $auth_request = $this->buildAuthRequest($code);
     try {
         $response = $this->tryRequest($auth_request);
         return $this->verifySSOResponse($response);
     } catch (\Exception $e) {
         $session->getFlashBag()->add('danger', 'There was a problem with your request<i>Try Again - if this persists - Submit an issue ticket using the link in the footer.</i></b>');
         return $this->redirect($this->generateUrl('eve.register'));
     }
 }

作者:vbessono    项目:fsrap   
protected function validateDigest($digest, $nonce, $created, $secret)
 {
     //        if (strtotime($created) > time()) {
     //            return false;
     //        }
     //        if (time() - strtotime($created) > 300) {
     //            return false;
     //        }
     //        if (file_exists($this->cacheDir . '/' . $nonce) && file_get_contents($this->cacheDir . '/' . $nonce) + 300 > time()) {
     //            throw new NonceExpiredException('Previously used nonce detected');
     //        }
     //        if (!is_dir($this->cacheDir)) {
     //            mkdir($this->cacheDir, 0777, true);
     //        }
     //        file_put_contents($this->cacheDir . '/' . $nonce, time());
     //        $expected = base64_encode(sha1(base64_decode($nonce) . $created . $secret, true));
     //        $expected = base64_encode(sha256($created . $secret, true));
     $expected = $secret;
     return StringUtils::equals($expected, $digest);
 }

作者:myovche    项目:zaralab-ap   
public function authenticate($email, $password)
 {
     /** @var MemberManager $mm */
     $mm = $this->container['member.manager'];
     /** @var Member $member */
     $member = $mm->findMemberByEmail($email);
     /** @var MessageDigestPasswordEncoder $encoder */
     $encoder = $this->container['security.encoder'];
     /** @var UserChecker $userChecker */
     $userChecker = $this->container['security.user_checker'];
     try {
         if ($member) {
             $userChecker->checkPreAuth($member);
             if ($encoder->isPasswordValid($member->getPassword(), $password, $member->getSalt())) {
                 $encodedPassword = $encoder->encodePassword($password, $member->getSalt());
                 $match = StringUtils::equals($member->getPassword(), $encodedPassword);
                 $userChecker->checkPostAuth($member);
                 if ($match) {
                     $authenticatedToken = new UsernamePasswordToken($member, $password, self::PROVIDER_KEY, $member->getRoles());
                     $this->container['security.token_storage']->setToken($authenticatedToken);
                 } else {
                     throw new AuthenticationCredentialsNotFoundException('Wrong email and password combination.', 401);
                 }
             }
         }
     } catch (AuthenticationException $failed) {
         $this->container->get('logger')->error(sprintf('Authentication failed for user "%s" (using password - "%s")', $email, !empty($password) ? 'yes' : 'no'), ['email' => $email, 'description' => $failed->getMessage()]);
         throw new $failed();
     }
     if (null === $this->container['member']) {
         if (empty($email) || empty($password)) {
             throw new AuthenticationCredentialsNotFoundException('Authentication credentials could not be found.', 400);
         }
         throw new AuthenticationCredentialsNotFoundException('Wrong email and password combination.', 401);
     }
     return $this->container['member'];
 }

作者:flelievr    项目:EasyVisi   
/**
  * Compares two passwords.
  *
  * This method implements a constant-time algorithm to compare passwords to
  * avoid (remote) timing attacks.
  *
  * @param string $password1 The first password
  * @param string $password2 The second password
  *
  * @return bool    true if the two passwords are the same, false otherwise
  */
 protected function comparePasswords($password1, $password2)
 {
     return StringUtils::equals($password1, $password2);
 }

作者:Viacomin    项目:sutr   
/**
  * {@inheritDoc}
  */
 public function stringsAreEqual($s1, $s2)
 {
     return StringUtils::equals($s1, $s2);
 }

作者:kokaref    项目:octobe   
/**
  * Checks the request data / headers for a valid CSRF token.
  * Returns false if a valid token is not found. Override this
  * method to disable the check.
  * @return bool
  */
 protected function verifyCsrfToken()
 {
     if (!Config::get('cms.enableCsrfProtection')) {
         return true;
     }
     if (in_array(Request::method(), ['HEAD', 'GET', 'OPTIONS'])) {
         return true;
     }
     $token = Request::input('_token') ?: Request::header('X-CSRF-TOKEN');
     return \Symfony\Component\Security\Core\Util\StringUtils::equals(Session::getToken(), $token);
 }

作者:visualtur    项目:framewor   
/**
  * Determine if the session and input CSRF tokens match.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return bool
  */
 protected function tokensMatch($request)
 {
     $token = $request->session()->token();
     $header = $request->header('X-XSRF-TOKEN');
     return StringUtils::equals($token, $request->input('_token')) || $header && StringUtils::equals($token, $this->encrypter->decrypt($header));
 }


问题


面经


文章

微信
公众号

扫码关注公众号