本文整理汇总了PHP中Symfony\Component\Security\Core\SecurityContextInterface::setToken方法的典型用法代码示例。如果您正苦于以下问题:PHP SecurityContextInterface::setToken方法的具体用法?PHP SecurityContextInterface::setToken怎么用?PHP SecurityContextInterface::setToken使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\Security\Core\SecurityContextInterface
的用法示例。
在下文中一共展示了SecurityContextInterface::setToken方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: logInUser
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);
}
示例2: onClientConnect
/**
* @param ClientEvent $event
*
* @throws StorageException
* @throws \Exception
*/
public function onClientConnect(ClientEvent $event)
{
$conn = $event->getConnection();
if (true === $this->originChecker && 1 === count($this->firewalls) && 'ws_firewall' === $this->firewalls[0]) {
$this->logger->warning(sprintf('User firewall is not configured, we have set %s by default', $this->firewalls[0]));
}
$loggerContext = array('connection_id' => $conn->resourceId, 'session_id' => $conn->WAMP->sessionId);
$token = null;
if (isset($conn->Session) && $conn->Session) {
foreach ($this->firewalls as $firewall) {
if (false !== ($serializedToken = $conn->Session->get('_security_' . $firewall, false))) {
/** @var TokenInterface $token */
$token = unserialize($serializedToken);
break;
}
}
}
if (null === $token) {
$token = new AnonymousToken($this->firewalls[0], 'anon-' . $conn->WAMP->sessionId);
}
$this->securityContext->setToken($token);
$user = $token->getUser();
$username = $user instanceof UserInterface ? $user->getUsername() : $user;
try {
$identifier = $this->clientStorage->getStorageId($conn, $username);
$loggerContext['storage_id'] = $identifier;
$this->clientStorage->addClient($identifier, $user);
$conn->WAMP->clientStorageId = $identifier;
$this->logger->info(sprintf('%s connected [%]', $username, $user instanceof UserInterface ? implode(', ', $user->getRoles()) : array()), $loggerContext);
} catch (StorageException $e) {
$this->logger->error($e->getMessage(), $loggerContext);
throw $e;
}
}
示例3: handle
/**
* @param GetResponseEvent $event
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->headers->has('cookie')) {
return;
}
if (strstr($request->headers->get('cookie'), 'SimpleSAMLAuthToken') === false) {
return;
}
if (!$request->query->has('csrf-token')) {
$this->logger->notice('Ssp Firewall: Auth Token cookie but no CSRF Token');
return;
}
$csrfToken = $request->query->getAlnum('csrf-token');
if (!$this->csrfProvider->isCsrfTokenValid('api', $csrfToken)) {
$this->logger->notice('Ssp Firewall: Invalid CSRF token for api use: ' . $csrfToken);
return;
}
try {
$authToken = $this->authenticationManager->authenticate(new SspToken());
$this->securityContext->setToken($authToken);
} catch (AuthenticationException $failed) {
$this->logger->warning('Ssp Firewall: failed:' . $failed->getMessage());
$token = $this->securityContext->getToken();
if ($token instanceof SspToken) {
$this->securityContext->setToken(null);
}
return;
}
}
示例4: login
/**
* {@inheritDoc}
*/
public function login(UserInterface $user, $firewallName = 'main')
{
$this->userChecker->checkPreAuth($user);
$token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles());
$this->securityContext->setToken($token);
$this->eventDispatcher->dispatch(UserEvents::SECURITY_IMPLICIT_LOGIN, new UserEvent($user));
}
示例5: handle
/**
* Handles basic authentication.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (false === ($username = $request->headers->get('PHP_AUTH_USER', false))) {
return;
}
if (null !== ($token = $this->securityContext->getToken())) {
if ($token instanceof OrganizationContextTokenInterface && $token->isAuthenticated() && $token->getUsername() === $username) {
return;
}
}
$this->logProcess($username);
try {
$organizationId = $request->headers->get('PHP_AUTH_ORGANIZATION');
if ($organizationId) {
$authToken = new UsernamePasswordOrganizationToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey, $this->manager->getOrganizationById($organizationId));
} else {
$authToken = new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey);
}
$this->securityContext->setToken($this->authenticationManager->authenticate($authToken));
} catch (AuthenticationException $failed) {
$token = $this->securityContext->getToken();
if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
$this->securityContext->setToken(null);
}
$this->logError($username, $failed->getMessage());
if ($this->ignoreFailure) {
return;
}
$event->setResponse($this->authenticationEntryPoint->start($request, $failed));
}
}
示例6: handle
/**
* {@inheritdoc}
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if ($this->securityContext->getToken() !== null) {
return;
}
if ($request->getRequestUri() == '/app_dev.php/api/login' || $request->getRequestUri() == '/api/login') {
return;
}
//Try to reach token from HTTP headers
if ($request->headers->has('X-Auth-Token')) {
$tokenId = $request->headers->get('X-Auth-Token');
} else {
$tokenId = $request->get('token');
}
//by token
if (isset($tokenId)) {
$user = $this->userProvider->findUserByToken($tokenId);
if (!$user) {
throw new BadCredentialsException();
}
try {
$token = new ApiToken([], $this->providerId, $this->key);
$token->setUser($user);
$authenticatedToken = $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($authenticatedToken);
} catch (AuthenticationException $e) {
//log something
}
}
}
示例7: handle
/**
* This interface must be implemented by firewall listeners.
*
* @param GetResponseEvent $event
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
$apiKey = $request->headers->get('Authorization', $request->query->get('api_key'));
if (!$apiKey) {
if (true === $this->forceApiKey) {
$response = new Response();
$response->setStatusCode(401);
$event->setResponse($response);
}
return;
}
$token = new ApiKeyUserToken();
$token->setApiKey($apiKey);
try {
$authToken = $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
$token = $this->securityContext->getToken();
if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
$this->securityContext->setToken(null);
}
$message = $failed->getMessage();
}
if ($this->isJsonRequest($request)) {
$response = new JsonResponse(array('error' => $message));
} else {
$response = new Response();
$response->setContent($message);
}
$response->setStatusCode(401);
$event->setResponse($response);
}
示例8: handle
/**
* 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->securityContext->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
$token = $this->securityContext->getToken();
if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
$this->securityContext->setToken(null);
}
$message = $failed->getMessage();
}
$response = new Response();
$response->setContent($message);
$response->setStatusCode(403);
$event->setResponse($response);
}
示例9: 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)) {
// Deny authentication with a '403 Forbidden' HTTP response
$response = new Response();
$response->setStatusCode(403);
$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->securityContext->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
// ... you might log something here
$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.
//Make sure to only clear your token, not those of other authentication listeners.
$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;
}
}
示例10: handle
/**
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event The event.
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (null === ($oauthToken = $this->serverService->getBearerToken($event->getRequest(), true))) {
//if it's null, then we try to regular authentication...
$token = $this->handleCookie($event);
if ($token) {
$this->securityContext->setToken($token);
return;
}
}
$token = new OAuthToken();
$token->setToken($oauthToken);
$returnValue = $this->authenticationManager->authenticate($token);
try {
$returnValue = $this->authenticationManager->authenticate($token);
if ($returnValue instanceof TokenInterface) {
return $this->securityContext->setToken($returnValue);
}
if ($returnValue instanceof Response) {
return $event->setResponse($returnValue);
}
} catch (AuthenticationException $e) {
if (null !== ($p = $e->getPrevious())) {
$event->setResponse($p->getHttpResponse());
}
}
}
示例11: handle
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));
}
}
}
示例12: handle
/**
* Handles the authentication for user.
*
* @param GetResponseEvent $event The response event.
*
* @throws AuthenticationException When the request is not authenticated.
*
* @return void
*/
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)) {
return;
}
$token = new WsseUserToken($this->providerKey);
$token->setUser($matches[1]);
$token->setDigest($matches[2]);
$token->setNonce($matches[3]);
$token->setCreated($matches[4]);
try {
$authToken = $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
$failedMessage = 'WSSE Login failed for ' . $token->getUsername() . '. Because: ' . $failed->getMessage();
$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);
$event->setResponse($response);
return;
}
// by default deny authorization
$response = new Response();
$response->setStatusCode(403);
$event->setResponse($response);
}
示例13: checkAuthentication
/**
* Checks if a Wordpress user is authenticated and authenticate him into Symfony security context
*
* @param Request $request
*/
protected function checkAuthentication(Request $request)
{
$session = $request->getSession();
if ($session->has('token')) {
$token = $session->get('token');
$this->securityContext->setToken($token);
}
}
示例14: onAccessDeniedException
/**
* @param GetResponseForExceptionEvent $event
*/
public function onAccessDeniedException(GetResponseForExceptionEvent $event)
{
if ($event->getException() instanceof AccessDeniedHttpException) {
$this->session->invalidate();
$this->session->set(SecurityContextInterface::ACCESS_DENIED_ERROR, ['message' => 'You are not allowed']);
$this->securityContext->setToken(null);
$route = $this->router->generate('oro_distribution_security_login');
$event->setResponse(new RedirectResponse($route));
}
}
示例15: register
/**
* Register new User into the web.
* Creates new token given a user, with related Role set.
*
* @param AbstractUserInterface $user User to register
* @param string $providerKey Provider key
*
* @return $this self Object
*/
public function register(AbstractUserInterface $user, $providerKey)
{
if (!$this->securityContext instanceof SecurityContextInterface) {
return $this;
}
$token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
$this->securityContext->setToken($token);
$event = new AbstractUserRegisterEvent($user);
$this->eventDispatcher->dispatch(ElcodiUserEvents::ABSTRACTUSER_REGISTER, $event);
return $this;
}