本文整理汇总了PHP中Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage::setToken方法的典型用法代码示例。如果您正苦于以下问题:PHP TokenStorage::setToken方法的具体用法?PHP TokenStorage::setToken怎么用?PHP TokenStorage::setToken使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage
的用法示例。
在下文中一共展示了TokenStorage::setToken方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: authorize
public function authorize()
{
try {
$this->accessToken = $this->helper->getAccessToken();
} catch (FacebookResponseException $e) {
// When Graph returns an error
throw new FacebookAuthenticationException('Graph returned an error: ' . $e->getMessage());
} catch (FacebookSDKException $e) {
// When validation fails or other local issues
throw new FacebookAuthenticationException('Facebook SDK returned an error: ' . $e->getMessage());
}
if (!$this->accessToken) {
throw new FacebookAuthenticationException('Access token not received. ' . $this->helper->getError(), $this->helper->getErrorCode());
}
try {
// Returns a `Facebook\FacebookResponse` object
$response = $this->facebook->get('/me?fields=id,name', $this->accessToken);
} catch (FacebookResponseException $e) {
throw new FacebookAuthenticationException('Graph returned an error: ' . $e->getMessage());
} catch (FacebookSDKException $e) {
throw new FacebookAuthenticationException('Facebook SDK returned an error: ' . $e->getMessage());
}
$fbUser = $response->getGraphUser();
if (!($user = $this->doctrine->getRepository('QuizBundle:User')->findOneBySocialId($fbUser['id']))) {
$user = (new Entity\User())->setAccessToken($this->accessToken)->setSocialType(Entity\User::FACEBOOK)->setSocialId($fbUser['id'])->setName($fbUser['name']);
$manager = $this->doctrine->getManager();
$manager->persist($user);
$manager->flush();
}
$token = new SocialToken($user, $this->accessToken, 'facebook', [$this->adminId == $fbUser['id'] ? 'ROLE_ADMIN' : 'ROLE_USER']);
$this->tokenStorage->setToken($token);
}
示例2: handle
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(403);
$response->setContent('Invalid or missing WSSE.');
$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->tokenStorage->setToken($authToken);
} catch (AuthenticationException $failed) {
$response = new Response();
$response->setStatusCode(403);
$response->getContent($failed->getMessage());
$event->setResponse($response);
}
}
示例3: testGetSetToken
public function testGetSetToken()
{
$tokenStorage = new TokenStorage();
$this->assertNull($tokenStorage->getToken());
$token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface');
$tokenStorage->setToken($token);
$this->assertSame($token, $tokenStorage->getToken());
}
示例4: forceSignIn
/**
* @param Request $request
* @param User $user
* @param string $password
* @param boolean $oAuth
* @return boolean
*/
public function forceSignIn(Request $request, User $user, $password, $oAuth = false)
{
if ($oAuth === false) {
$password = $this->encoderFactory->getEncoder($user)->encodePassword($password, $user->getSalt());
} else {
$password = $user->getPassword();
}
if ($password === $user->getPassword()) {
$request->request->set('_remember_me', true);
$token = new UsernamePasswordToken($user, $user->getPassword(), "secured_area", $user->getRoles());
$this->tokenStorage->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->eventDispatcher->dispatch("security.interactive_login", $event);
return true;
} else {
return false;
}
}
示例5: loginUser
private function loginUser($user, $request)
{
//this is bad but I don't know any other way (yet)
$providerKey = 'main';
$token = new UsernamePasswordToken($user, $user->getPassword(), $providerKey, $user->getRoles());
$this->tokenStorage->setToken($token);
//a bit hacky I know ~
return $this->authenticationHandler->onAuthenticationSuccess($request, $token);
}
示例6: testIntegrationNoUser
public function testIntegrationNoUser()
{
$token = $this->getMock(TokenInterface::class);
$tokenStorage = new TokenStorage();
$tokenStorage->setToken($token);
$argumentResolver = new ArgumentResolver(null, array(new SecurityUserValueResolver($tokenStorage), new DefaultValueResolver()));
$this->assertSame(array(null), $argumentResolver->getArguments(Request::create('/'), function (UserInterface $user = null) {
}));
}
示例7: onKernelRequest
/**
* Refresh organization context in token
*
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$token = $this->tokenStorage->getToken();
if ($token instanceof OrganizationContextTokenInterface) {
try {
$token->setOrganizationContext($this->manager->getOrganizationById($token->getOrganizationContext()->getId()));
if (!$token->getUser()->getOrganizations(true)->contains($token->getOrganizationContext())) {
$exception = new OrganizationAccessDeniedException();
$exception->setOrganizationName($token->getOrganizationContext()->getName());
$exception->setToken($token);
$event->getRequest()->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
$this->tokenStorage->setToken(null);
throw $exception;
}
} catch (NoResultException $e) {
$token->setAuthenticated(false);
}
}
}
示例8: logout
/**
* @param Request $request
* @param Response $response
* @return Response
*/
public function logout(Request $request, Response $response)
{
$this->tokenStorage->setToken(null);
$request->getSession()->invalidate();
$cookieNames = [$this->cookieRememberMeName];
foreach ($cookieNames as $cookieName) {
$response->headers->clearCookie($cookieName);
}
return $response;
}
示例9: testShouldReturnDateInGoodFormat
public function testShouldReturnDateInGoodFormat()
{
$session = new Session(new MockArraySessionStorage());
$user = new User();
$user->setUsername('kristen');
$tokenStorage = new TokenStorage();
$tokenStorage->setToken(new UsernamePasswordToken($user, 'test', 'fritage', array('ROLE_USER')));
$namer = new FinorthoNamer($tokenStorage, $session);
$date = $namer->weekDate(5);
$carbon = Carbon::createFromFormat('ymd', $date);
$this->assertFalse($carbon->isWeekend());
}
示例10: testCollectAuthenticationTokenAndRoles
/** @dataProvider provideRoles */
public function testCollectAuthenticationTokenAndRoles(array $roles, array $normalizedRoles)
{
$tokenStorage = new TokenStorage();
$tokenStorage->setToken(new UsernamePasswordToken('hhamon', 'P4$$w0rD', 'provider', $roles));
$collector = new SecurityDataCollector($tokenStorage);
$collector->collect($this->getRequest(), $this->getResponse());
$this->assertTrue($collector->isEnabled());
$this->assertTrue($collector->isAuthenticated());
$this->assertSame('Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken', $collector->getTokenClass());
$this->assertSame($normalizedRoles, $collector->getRoles());
$this->assertSame('hhamon', $collector->getUser());
}
示例11: testTokenAwareAuthorizationCheckerAndDrupalPermissionVoter
public function testTokenAwareAuthorizationCheckerAndDrupalPermissionVoter()
{
// We are in Drupal, user with uid 1 can access everything
$superUser = new User();
$superUser->uid = 1;
$superUser->roles = [1 => 1];
$superToken = new UserToken();
$superToken->setUser(new DrupalUser($superUser));
// And anonymous pretty much nothing
$dumbUser = new User();
$dumbUser->uid = 0;
$dumbUser->roles = [0 => 0];
$dumbToken = new UserToken();
$dumbToken->setUser(new DrupalUser($dumbUser));
// We are working in a fully bootstrapped Drupal, in theory
// the permission voter is setup, we can send isGranted() calls
// using permission names: sending a non existing permission
// will always return false for any user, but always true for
// the user with uid 1 (Drupal core default behavior)
$permission = 'a drupal permission that does not exists';
$tokenStorage = new TokenStorage();
$authenticationManager = new SecurityNullAuthenticationManager();
$accessDecisionManager = new AccessDecisionManager([new DrupalPermissionVoter()]);
$defaultAuthorizationChecker = new AuthorizationChecker($tokenStorage, $authenticationManager, $accessDecisionManager);
$tokenAwareAuthorizationChecker = new TokenAwareAuthorizationChecker($defaultAuthorizationChecker, $accessDecisionManager);
// First check results for the current user (should not be allowed)
// Then the super user (should be allowed)
$tokenStorage->setToken($superToken);
$this->assertTrue($defaultAuthorizationChecker->isGranted($permission, null));
$this->assertTrue($tokenAwareAuthorizationChecker->isGranted($permission, null));
$this->assertTrue($tokenAwareAuthorizationChecker->isGranted($permission, null, $superUser));
$this->assertFalse($tokenAwareAuthorizationChecker->isGranted($permission, null, $dumbUser));
// And do the exact opposite
$tokenStorage->setToken($dumbToken);
$this->assertFalse($defaultAuthorizationChecker->isGranted($permission, null));
$this->assertFalse($tokenAwareAuthorizationChecker->isGranted($permission, null));
$this->assertTrue($tokenAwareAuthorizationChecker->isGranted($permission, null, $superUser));
$this->assertFalse($tokenAwareAuthorizationChecker->isGranted($permission, null, $dumbUser));
}
示例12: testShloudGiveBackAnArray
public function testShloudGiveBackAnArray()
{
$user = new User();
$user->setUsername('kristen');
$tokenStorage = new TokenStorage();
$tokenStorage->setToken(new UsernamePasswordToken($user, 'test', 'fritage', array('ROLE_USER')));
$repository = $this->getMockBuilder('\\Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock();
$repository->expects($this->once())->method('findBy')->will($this->returnValue(array(array('id' => 1, 'url' => 'test', 'name' => 'ect..'))));
// Last, mock the EntityManager to return the mock of the repository
$entityManager = $this->getMockBuilder('\\Doctrine\\Common\\Persistence\\ObjectManager')->disableOriginalConstructor()->getMock();
$entityManager->expects($this->any())->method('getRepository')->willReturn($repository);
$last = new LastUploads($entityManager, $tokenStorage);
$this->assertTrue(is_array($last->get()));
}
示例13: loadUserByOAuthUserResponse
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$socialID = $response->getUsername();
/** @var User $user */
$user = $this->userManager->loadUser(['facebookId' => $socialID]);
$update = true;
$email = $response->getEmail();
//check if the user already has the corresponding social account
if (null === $user) {
//check if the user has a normal account
$user = $this->userManager->loadUser($email, 'email');
if (null === $user || !$user instanceof UserInterface) {
//if the user does not have a normal account, set it up:
/** @var User $user */
$name = $response->getNickname() ?? $response->getRealName();
$user = $this->userManager->createUser($name, md5(uniqid()), $response->getEmail(), ['ROLE_OAUTH_USER']);
$user->setEmail($email);
$user->setFullName($name);
$user->setEnabled(true);
$violations = $this->validator->validate($user);
$update = !$violations->count() === 0;
if ($violations->count() === 0) {
$this->session->getFlashBag()->add('warning', 'Welcome! You must complete your profile in order to use the features on the site.');
} else {
throw new CustomUserMessageAuthenticationException('An account in your name already exists.');
}
}
if ($update) {
//then set its corresponding social id
$service = $response->getResourceOwner()->getName();
switch ($service) {
case 'google':
$user->setGoogleID($socialID);
break;
case 'facebook':
$user->setFacebookID($socialID);
break;
}
$this->userManager->updateUser($user);
}
} else {
//and then login the user
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->tokenStorage->setToken($token);
}
$user->setLastLoggedIn(new \DateTime());
$this->userManager->updateUser($user);
return $user;
}
示例14: testOrderAtInternalLink
public function testOrderAtInternalLink()
{
$this->tokenStorage->setToken($this->createUserTokenWithId(17));
$data = $this->prepareOrderAtData();
$this->documentManager->clear();
$testSiteData = ['title' => 'Test', 'nodeType' => Structure::NODE_TYPE_INTERNAL_LINK, 'url' => '/test/123', 'internal_link' => $data[0]->getUuid()];
$site = $this->mapper->save($testSiteData, 'internal_link_page', 'sulu_io', 'en', 1, true, null, $data[0]->getUuid());
$this->documentManager->clear();
$result = $this->mapper->orderAt($site->getUuid(), 3, 17, 'sulu_io', 'en');
$this->assertEquals($site->getUuid(), $result->getUuid());
$this->assertEquals('/page-1/test', $result->getPath());
$this->assertEquals(17, $result->getChanger());
$this->documentManager->clear();
$result = $this->documentManager->find($site->getUuid(), 'en');
$this->assertEquals(30, $result->getSuluOrder());
$this->assertEquals(RedirectType::INTERNAL, $result->getRedirectType());
$result = $this->mapper->loadByParent($data[0]->getUuid(), 'sulu_io', 'en');
$this->assertEquals('/page-1/page-1-1', $result[0]->getPath());
$this->assertEquals('/page-1/page-1-2', $result[1]->getPath());
$this->assertEquals('/page-1/test', $result[2]->getPath());
$this->assertEquals('/page-1/page-1-3', $result[3]->getPath());
$this->assertEquals('/page-1/page-1-4', $result[4]->getPath());
}
示例15: loginUser
/**
* @param UserInterface $user
*/
public function loginUser(AbstractUser $user)
{
$token = new UsernamePasswordToken($user, null, "main", $user->getRoles());
$this->tokenStorage->setToken($token);
}