Programatically Log User Out [Magento 2] The Next CEO of Stack OverflowLogout by programming from observer in magento 2Keep products in shopping cart after customer logs outHow to customize the customer account after login according to user groupMagento 2.7 and 2.1.1 - While changing the password form the my account page User group changed to default customer groupHow to remove “NOT LOGGED IN” valueMagento 2.1 - User Group Registration FormMagento 2 - Redirect to Account Dashboard During Checkout Funnel LoginHow can I assign EU VAT reg customer to Magento customer group if they don't create an account?How Do You Invalidate Customer Data In Magento 2?Recently viewed products not showing for NOT LOGGED CUSTOMERS in magento 2

How to use ReplaceAll on an expression that contains a rule

Which Pokemon have a special animation when running with them out of their pokeball?

How can the PCs determine if an item is a phylactery?

How do I fit a non linear curve?

How did Beeri the Hittite come up with naming his daughter Yehudit?

What difference does it make using sed with/without whitespaces?

What would be the main consequences for a country leaving the WTO?

What is the process for purifying your home if you believe it may have been previously used for pagan worship?

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

Is it convenient to ask the journal's editor for two additional days to complete a review?

Why am I getting "Static method cannot be referenced from a non static context: String String.valueOf(Object)"?

What happened in Rome, when the western empire "fell"?

Does Germany produce more waste than the US?

Do scriptures give a method to recognize a truly self-realized person/jivanmukta?

Why is information "lost" when it got into a black hole?

Ising model simulation

how one can write a nice vector parser, something that does pgfvecparseA=B-C; D=E x F;

Can you teleport closer to a creature you are Frightened of?

How do you define an element with an ID attribute using LWC?

Traveling with my 5 year old daughter (as the father) without the mother from Germany to Mexico

(How) Could a medieval fantasy world survive a magic-induced "nuclear winter"?

Does higher Oxidation/ reduction potential translate to higher energy storage in battery?

What CSS properties can the br tag have?

Calculate the Mean mean of two numbers



Programatically Log User Out [Magento 2]



The Next CEO of Stack OverflowLogout by programming from observer in magento 2Keep products in shopping cart after customer logs outHow to customize the customer account after login according to user groupMagento 2.7 and 2.1.1 - While changing the password form the my account page User group changed to default customer groupHow to remove “NOT LOGGED IN” valueMagento 2.1 - User Group Registration FormMagento 2 - Redirect to Account Dashboard During Checkout Funnel LoginHow can I assign EU VAT reg customer to Magento customer group if they don't create an account?How Do You Invalidate Customer Data In Magento 2?Recently viewed products not showing for NOT LOGGED CUSTOMERS in magento 2










1















I have written a module which is basically an observer which triggers on 'customer_save_after_data_object' the content of this observer basically listens out for when the customers group is changed.



The issue we are having is that if the customers' group is changed when they are logged in it doesn't seem to take effect, meaning that they need to log out of the account and then back in.



My question is, is there a way to log the customer out of their dashboard programmatically when I don't have direct access to the customer session and only the observer data?










share|improve this question
















bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…

    – Kyrylo Romantsov
    Sep 8 '17 at 7:56
















1















I have written a module which is basically an observer which triggers on 'customer_save_after_data_object' the content of this observer basically listens out for when the customers group is changed.



The issue we are having is that if the customers' group is changed when they are logged in it doesn't seem to take effect, meaning that they need to log out of the account and then back in.



My question is, is there a way to log the customer out of their dashboard programmatically when I don't have direct access to the customer session and only the observer data?










share|improve this question
















bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…

    – Kyrylo Romantsov
    Sep 8 '17 at 7:56














1












1








1








I have written a module which is basically an observer which triggers on 'customer_save_after_data_object' the content of this observer basically listens out for when the customers group is changed.



The issue we are having is that if the customers' group is changed when they are logged in it doesn't seem to take effect, meaning that they need to log out of the account and then back in.



My question is, is there a way to log the customer out of their dashboard programmatically when I don't have direct access to the customer session and only the observer data?










share|improve this question
















I have written a module which is basically an observer which triggers on 'customer_save_after_data_object' the content of this observer basically listens out for when the customers group is changed.



The issue we are having is that if the customers' group is changed when they are logged in it doesn't seem to take effect, meaning that they need to log out of the account and then back in.



My question is, is there a way to log the customer out of their dashboard programmatically when I don't have direct access to the customer session and only the observer data?







magento2 magento-2.1 customer-account customer-group






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 8 '17 at 7:54









Amit Bera

59.5k1676177




59.5k1676177










asked Sep 8 '17 at 7:50









CreativeNerdSamCreativeNerdSam

437




437





bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…

    – Kyrylo Romantsov
    Sep 8 '17 at 7:56


















  • you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…

    – Kyrylo Romantsov
    Sep 8 '17 at 7:56

















you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…

– Kyrylo Romantsov
Sep 8 '17 at 7:56






you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…

– Kyrylo Romantsov
Sep 8 '17 at 7:56











3 Answers
3






active

oldest

votes


















0














What you want is the CustomerTokenServiceInterface



In your constructor:



use MagentoIntegrationApiCustomerTokenServiceInterface;

// ...

/** @var CustomerTokenServiceInterface */
private $tokenService;

public function __construct(CustomerTokenServiceInterface $tokenService)

$this->tokenService = $tokenService;



In your code:



$this->tokenService->revokeCustomerAccessToken($customerId);


You can see an example of this in MagentoCustomerControllerAdminhtmlCustomerInvalidateToken which is the action called by the "Force Sign-In" button for customers in the admin panel.



Don't forget to add <module name="Magento_Integration" /> to your sequence file, and magento/module-integration in your module's composer.json requirements!






share|improve this answer























  • Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.

    – CreativeNerdSam
    Sep 8 '17 at 13:19











  • Even when clicking the force log-in button it still doesn't kick the user out.

    – CreativeNerdSam
    Sep 8 '17 at 13:32


















0














Try this code.



<?php
namespace PackageModulenameModel;

use MagentoCustomerApiAccountManagementInterface;
use MagentoFrameworkExceptionLocalizedException;
use MagentoIntegrationModelCredentialsValidator;
use MagentoIntegrationModelOauthToken as Token;
use MagentoIntegrationModelOauthTokenFactory as TokenModelFactory;
use MagentoIntegrationModelResourceModelOauthTokenCollectionFactory as TokenCollectionFactory;
use MagentoIntegrationModelOauthTokenRequestThrottler;
use MagentoFrameworkExceptionAuthenticationException;

class CustomerLogout implements PackageModulenameApiCustomerLogoutInterface

/**
* Token Model
*
* @var TokenModelFactory
*/
private $tokenModelFactory;

/**
* Customer Account Service
*
* @var AccountManagementInterface
*/
private $accountManagement;

/**
* @var MagentoIntegrationModelCredentialsValidator
*/
private $validatorHelper;

/**
* Token Collection Factory
*
* @var TokenCollectionFactory
*/
private $tokenModelCollectionFactory;

/**
* @var RequestThrottler
*/
private $requestThrottler;

/**
* Initialize service
*
* @param TokenModelFactory $tokenModelFactory
* @param AccountManagementInterface $accountManagement
* @param TokenCollectionFactory $tokenModelCollectionFactory
* @param MagentoIntegrationModelCredentialsValidator $validatorHelper
*/
public function __construct(
TokenModelFactory $tokenModelFactory,
AccountManagementInterface $accountManagement,
TokenCollectionFactory $tokenModelCollectionFactory,
CredentialsValidator $validatorHelper
)
$this->tokenModelFactory = $tokenModelFactory;
$this->accountManagement = $accountManagement;
$this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
$this->validatorHelper = $validatorHelper;


/**
* @inheritdoc
*/
public function revokeCustomerAccessToken()

$customerId = 1;
$tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
if ($tokenCollection->getSize() == 0)
throw new LocalizedException(__('This customer has no tokens.'));

try
foreach ($tokenCollection as $token)
$token->setRevoked(1)->save();

catch (Exception $e)
throw new LocalizedException(__('The tokens could not be revoked.'));

return true;








share|improve this answer






























    0














    It will work. Pro-grammatically logout customer on observer.



    <?php
    /**
    *
    * Copyright © Magento, Inc. All rights reserved.
    * See COPYING.txt for license details.
    */
    namespace VendorModuleNameObserver;

    use MagentoCustomerModelSession;
    use MagentoFrameworkAppActionContext;
    use MagentoFrameworkAppObjectManager;
    use MagentoFrameworkStdlibCookieCookieMetadataFactory;
    use MagentoFrameworkStdlibCookiePhpCookieManager;
    use MagentoFrameworkEventObserverInterface;

    class Logout implements ObserverInterface
    /**
    * @var Session
    */
    protected $session;

    /**
    * @var CookieMetadataFactory
    */
    private $cookieMetadataFactory;

    /**
    * @var PhpCookieManager
    */
    private $cookieMetadataManager;

    /**
    * @param Context $context
    * @param Session $customerSession
    */
    public function __construct(
    Context $context,
    Session $customerSession,
    CookieMetadataFactory $cookieMetadataManager
    )
    $this->session = $customerSession;
    $this->cookieMetadataManager = $cookieMetadataManager;
    parent::__construct($context);


    /**
    * Retrieve cookie manager
    *
    * @deprecated 100.1.0
    * @return PhpCookieManager
    */
    private function getCookieManager()

    if (!$this->cookieMetadataManager)
    $this->cookieMetadataManager = ObjectManager::getInstance()->get(PhpCookieManager::class);

    return $this->cookieMetadataManager;


    /**
    * Retrieve cookie metadata factory
    *
    * @deprecated 100.1.0
    * @return CookieMetadataFactory
    */
    private function getCookieMetadataFactory()

    if (!$this->cookieMetadataFactory)
    $this->cookieMetadataFactory = ObjectManager::getInstance()->get(CookieMetadataFactory::class);

    return $this->cookieMetadataFactory;


    /**
    * Customer logout action
    *
    * @return MagentoFrameworkControllerResultRedirect
    */
    public function execute()

    $lastCustomerId = $this->session->getId();
    $this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
    ->setLastCustomerId($lastCustomerId);
    if ($this->getCookieManager()->getCookie('mage-cache-sessid'))
    $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
    $metadata->setPath('/');
    $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);


    /** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();
    $resultRedirect->setPath('*/*/logoutSuccess');
    return $resultRedirect;




    This is the magento core logout functionality, we can use as per our wish. Just try.






    share|improve this answer























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "479"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f192492%2fprogramatically-log-user-out-magento-2%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      What you want is the CustomerTokenServiceInterface



      In your constructor:



      use MagentoIntegrationApiCustomerTokenServiceInterface;

      // ...

      /** @var CustomerTokenServiceInterface */
      private $tokenService;

      public function __construct(CustomerTokenServiceInterface $tokenService)

      $this->tokenService = $tokenService;



      In your code:



      $this->tokenService->revokeCustomerAccessToken($customerId);


      You can see an example of this in MagentoCustomerControllerAdminhtmlCustomerInvalidateToken which is the action called by the "Force Sign-In" button for customers in the admin panel.



      Don't forget to add <module name="Magento_Integration" /> to your sequence file, and magento/module-integration in your module's composer.json requirements!






      share|improve this answer























      • Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.

        – CreativeNerdSam
        Sep 8 '17 at 13:19











      • Even when clicking the force log-in button it still doesn't kick the user out.

        – CreativeNerdSam
        Sep 8 '17 at 13:32















      0














      What you want is the CustomerTokenServiceInterface



      In your constructor:



      use MagentoIntegrationApiCustomerTokenServiceInterface;

      // ...

      /** @var CustomerTokenServiceInterface */
      private $tokenService;

      public function __construct(CustomerTokenServiceInterface $tokenService)

      $this->tokenService = $tokenService;



      In your code:



      $this->tokenService->revokeCustomerAccessToken($customerId);


      You can see an example of this in MagentoCustomerControllerAdminhtmlCustomerInvalidateToken which is the action called by the "Force Sign-In" button for customers in the admin panel.



      Don't forget to add <module name="Magento_Integration" /> to your sequence file, and magento/module-integration in your module's composer.json requirements!






      share|improve this answer























      • Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.

        – CreativeNerdSam
        Sep 8 '17 at 13:19











      • Even when clicking the force log-in button it still doesn't kick the user out.

        – CreativeNerdSam
        Sep 8 '17 at 13:32













      0












      0








      0







      What you want is the CustomerTokenServiceInterface



      In your constructor:



      use MagentoIntegrationApiCustomerTokenServiceInterface;

      // ...

      /** @var CustomerTokenServiceInterface */
      private $tokenService;

      public function __construct(CustomerTokenServiceInterface $tokenService)

      $this->tokenService = $tokenService;



      In your code:



      $this->tokenService->revokeCustomerAccessToken($customerId);


      You can see an example of this in MagentoCustomerControllerAdminhtmlCustomerInvalidateToken which is the action called by the "Force Sign-In" button for customers in the admin panel.



      Don't forget to add <module name="Magento_Integration" /> to your sequence file, and magento/module-integration in your module's composer.json requirements!






      share|improve this answer













      What you want is the CustomerTokenServiceInterface



      In your constructor:



      use MagentoIntegrationApiCustomerTokenServiceInterface;

      // ...

      /** @var CustomerTokenServiceInterface */
      private $tokenService;

      public function __construct(CustomerTokenServiceInterface $tokenService)

      $this->tokenService = $tokenService;



      In your code:



      $this->tokenService->revokeCustomerAccessToken($customerId);


      You can see an example of this in MagentoCustomerControllerAdminhtmlCustomerInvalidateToken which is the action called by the "Force Sign-In" button for customers in the admin panel.



      Don't forget to add <module name="Magento_Integration" /> to your sequence file, and magento/module-integration in your module's composer.json requirements!







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Sep 8 '17 at 13:01









      NavarrNavarr

      9971930




      9971930












      • Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.

        – CreativeNerdSam
        Sep 8 '17 at 13:19











      • Even when clicking the force log-in button it still doesn't kick the user out.

        – CreativeNerdSam
        Sep 8 '17 at 13:32

















      • Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.

        – CreativeNerdSam
        Sep 8 '17 at 13:19











      • Even when clicking the force log-in button it still doesn't kick the user out.

        – CreativeNerdSam
        Sep 8 '17 at 13:32
















      Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.

      – CreativeNerdSam
      Sep 8 '17 at 13:19





      Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.

      – CreativeNerdSam
      Sep 8 '17 at 13:19













      Even when clicking the force log-in button it still doesn't kick the user out.

      – CreativeNerdSam
      Sep 8 '17 at 13:32





      Even when clicking the force log-in button it still doesn't kick the user out.

      – CreativeNerdSam
      Sep 8 '17 at 13:32













      0














      Try this code.



      <?php
      namespace PackageModulenameModel;

      use MagentoCustomerApiAccountManagementInterface;
      use MagentoFrameworkExceptionLocalizedException;
      use MagentoIntegrationModelCredentialsValidator;
      use MagentoIntegrationModelOauthToken as Token;
      use MagentoIntegrationModelOauthTokenFactory as TokenModelFactory;
      use MagentoIntegrationModelResourceModelOauthTokenCollectionFactory as TokenCollectionFactory;
      use MagentoIntegrationModelOauthTokenRequestThrottler;
      use MagentoFrameworkExceptionAuthenticationException;

      class CustomerLogout implements PackageModulenameApiCustomerLogoutInterface

      /**
      * Token Model
      *
      * @var TokenModelFactory
      */
      private $tokenModelFactory;

      /**
      * Customer Account Service
      *
      * @var AccountManagementInterface
      */
      private $accountManagement;

      /**
      * @var MagentoIntegrationModelCredentialsValidator
      */
      private $validatorHelper;

      /**
      * Token Collection Factory
      *
      * @var TokenCollectionFactory
      */
      private $tokenModelCollectionFactory;

      /**
      * @var RequestThrottler
      */
      private $requestThrottler;

      /**
      * Initialize service
      *
      * @param TokenModelFactory $tokenModelFactory
      * @param AccountManagementInterface $accountManagement
      * @param TokenCollectionFactory $tokenModelCollectionFactory
      * @param MagentoIntegrationModelCredentialsValidator $validatorHelper
      */
      public function __construct(
      TokenModelFactory $tokenModelFactory,
      AccountManagementInterface $accountManagement,
      TokenCollectionFactory $tokenModelCollectionFactory,
      CredentialsValidator $validatorHelper
      )
      $this->tokenModelFactory = $tokenModelFactory;
      $this->accountManagement = $accountManagement;
      $this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
      $this->validatorHelper = $validatorHelper;


      /**
      * @inheritdoc
      */
      public function revokeCustomerAccessToken()

      $customerId = 1;
      $tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
      if ($tokenCollection->getSize() == 0)
      throw new LocalizedException(__('This customer has no tokens.'));

      try
      foreach ($tokenCollection as $token)
      $token->setRevoked(1)->save();

      catch (Exception $e)
      throw new LocalizedException(__('The tokens could not be revoked.'));

      return true;








      share|improve this answer



























        0














        Try this code.



        <?php
        namespace PackageModulenameModel;

        use MagentoCustomerApiAccountManagementInterface;
        use MagentoFrameworkExceptionLocalizedException;
        use MagentoIntegrationModelCredentialsValidator;
        use MagentoIntegrationModelOauthToken as Token;
        use MagentoIntegrationModelOauthTokenFactory as TokenModelFactory;
        use MagentoIntegrationModelResourceModelOauthTokenCollectionFactory as TokenCollectionFactory;
        use MagentoIntegrationModelOauthTokenRequestThrottler;
        use MagentoFrameworkExceptionAuthenticationException;

        class CustomerLogout implements PackageModulenameApiCustomerLogoutInterface

        /**
        * Token Model
        *
        * @var TokenModelFactory
        */
        private $tokenModelFactory;

        /**
        * Customer Account Service
        *
        * @var AccountManagementInterface
        */
        private $accountManagement;

        /**
        * @var MagentoIntegrationModelCredentialsValidator
        */
        private $validatorHelper;

        /**
        * Token Collection Factory
        *
        * @var TokenCollectionFactory
        */
        private $tokenModelCollectionFactory;

        /**
        * @var RequestThrottler
        */
        private $requestThrottler;

        /**
        * Initialize service
        *
        * @param TokenModelFactory $tokenModelFactory
        * @param AccountManagementInterface $accountManagement
        * @param TokenCollectionFactory $tokenModelCollectionFactory
        * @param MagentoIntegrationModelCredentialsValidator $validatorHelper
        */
        public function __construct(
        TokenModelFactory $tokenModelFactory,
        AccountManagementInterface $accountManagement,
        TokenCollectionFactory $tokenModelCollectionFactory,
        CredentialsValidator $validatorHelper
        )
        $this->tokenModelFactory = $tokenModelFactory;
        $this->accountManagement = $accountManagement;
        $this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
        $this->validatorHelper = $validatorHelper;


        /**
        * @inheritdoc
        */
        public function revokeCustomerAccessToken()

        $customerId = 1;
        $tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
        if ($tokenCollection->getSize() == 0)
        throw new LocalizedException(__('This customer has no tokens.'));

        try
        foreach ($tokenCollection as $token)
        $token->setRevoked(1)->save();

        catch (Exception $e)
        throw new LocalizedException(__('The tokens could not be revoked.'));

        return true;








        share|improve this answer

























          0












          0








          0







          Try this code.



          <?php
          namespace PackageModulenameModel;

          use MagentoCustomerApiAccountManagementInterface;
          use MagentoFrameworkExceptionLocalizedException;
          use MagentoIntegrationModelCredentialsValidator;
          use MagentoIntegrationModelOauthToken as Token;
          use MagentoIntegrationModelOauthTokenFactory as TokenModelFactory;
          use MagentoIntegrationModelResourceModelOauthTokenCollectionFactory as TokenCollectionFactory;
          use MagentoIntegrationModelOauthTokenRequestThrottler;
          use MagentoFrameworkExceptionAuthenticationException;

          class CustomerLogout implements PackageModulenameApiCustomerLogoutInterface

          /**
          * Token Model
          *
          * @var TokenModelFactory
          */
          private $tokenModelFactory;

          /**
          * Customer Account Service
          *
          * @var AccountManagementInterface
          */
          private $accountManagement;

          /**
          * @var MagentoIntegrationModelCredentialsValidator
          */
          private $validatorHelper;

          /**
          * Token Collection Factory
          *
          * @var TokenCollectionFactory
          */
          private $tokenModelCollectionFactory;

          /**
          * @var RequestThrottler
          */
          private $requestThrottler;

          /**
          * Initialize service
          *
          * @param TokenModelFactory $tokenModelFactory
          * @param AccountManagementInterface $accountManagement
          * @param TokenCollectionFactory $tokenModelCollectionFactory
          * @param MagentoIntegrationModelCredentialsValidator $validatorHelper
          */
          public function __construct(
          TokenModelFactory $tokenModelFactory,
          AccountManagementInterface $accountManagement,
          TokenCollectionFactory $tokenModelCollectionFactory,
          CredentialsValidator $validatorHelper
          )
          $this->tokenModelFactory = $tokenModelFactory;
          $this->accountManagement = $accountManagement;
          $this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
          $this->validatorHelper = $validatorHelper;


          /**
          * @inheritdoc
          */
          public function revokeCustomerAccessToken()

          $customerId = 1;
          $tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
          if ($tokenCollection->getSize() == 0)
          throw new LocalizedException(__('This customer has no tokens.'));

          try
          foreach ($tokenCollection as $token)
          $token->setRevoked(1)->save();

          catch (Exception $e)
          throw new LocalizedException(__('The tokens could not be revoked.'));

          return true;








          share|improve this answer













          Try this code.



          <?php
          namespace PackageModulenameModel;

          use MagentoCustomerApiAccountManagementInterface;
          use MagentoFrameworkExceptionLocalizedException;
          use MagentoIntegrationModelCredentialsValidator;
          use MagentoIntegrationModelOauthToken as Token;
          use MagentoIntegrationModelOauthTokenFactory as TokenModelFactory;
          use MagentoIntegrationModelResourceModelOauthTokenCollectionFactory as TokenCollectionFactory;
          use MagentoIntegrationModelOauthTokenRequestThrottler;
          use MagentoFrameworkExceptionAuthenticationException;

          class CustomerLogout implements PackageModulenameApiCustomerLogoutInterface

          /**
          * Token Model
          *
          * @var TokenModelFactory
          */
          private $tokenModelFactory;

          /**
          * Customer Account Service
          *
          * @var AccountManagementInterface
          */
          private $accountManagement;

          /**
          * @var MagentoIntegrationModelCredentialsValidator
          */
          private $validatorHelper;

          /**
          * Token Collection Factory
          *
          * @var TokenCollectionFactory
          */
          private $tokenModelCollectionFactory;

          /**
          * @var RequestThrottler
          */
          private $requestThrottler;

          /**
          * Initialize service
          *
          * @param TokenModelFactory $tokenModelFactory
          * @param AccountManagementInterface $accountManagement
          * @param TokenCollectionFactory $tokenModelCollectionFactory
          * @param MagentoIntegrationModelCredentialsValidator $validatorHelper
          */
          public function __construct(
          TokenModelFactory $tokenModelFactory,
          AccountManagementInterface $accountManagement,
          TokenCollectionFactory $tokenModelCollectionFactory,
          CredentialsValidator $validatorHelper
          )
          $this->tokenModelFactory = $tokenModelFactory;
          $this->accountManagement = $accountManagement;
          $this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
          $this->validatorHelper = $validatorHelper;


          /**
          * @inheritdoc
          */
          public function revokeCustomerAccessToken()

          $customerId = 1;
          $tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
          if ($tokenCollection->getSize() == 0)
          throw new LocalizedException(__('This customer has no tokens.'));

          try
          foreach ($tokenCollection as $token)
          $token->setRevoked(1)->save();

          catch (Exception $e)
          throw new LocalizedException(__('The tokens could not be revoked.'));

          return true;









          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Sep 8 '17 at 13:58









          RaghavRaghav

          14910




          14910





















              0














              It will work. Pro-grammatically logout customer on observer.



              <?php
              /**
              *
              * Copyright © Magento, Inc. All rights reserved.
              * See COPYING.txt for license details.
              */
              namespace VendorModuleNameObserver;

              use MagentoCustomerModelSession;
              use MagentoFrameworkAppActionContext;
              use MagentoFrameworkAppObjectManager;
              use MagentoFrameworkStdlibCookieCookieMetadataFactory;
              use MagentoFrameworkStdlibCookiePhpCookieManager;
              use MagentoFrameworkEventObserverInterface;

              class Logout implements ObserverInterface
              /**
              * @var Session
              */
              protected $session;

              /**
              * @var CookieMetadataFactory
              */
              private $cookieMetadataFactory;

              /**
              * @var PhpCookieManager
              */
              private $cookieMetadataManager;

              /**
              * @param Context $context
              * @param Session $customerSession
              */
              public function __construct(
              Context $context,
              Session $customerSession,
              CookieMetadataFactory $cookieMetadataManager
              )
              $this->session = $customerSession;
              $this->cookieMetadataManager = $cookieMetadataManager;
              parent::__construct($context);


              /**
              * Retrieve cookie manager
              *
              * @deprecated 100.1.0
              * @return PhpCookieManager
              */
              private function getCookieManager()

              if (!$this->cookieMetadataManager)
              $this->cookieMetadataManager = ObjectManager::getInstance()->get(PhpCookieManager::class);

              return $this->cookieMetadataManager;


              /**
              * Retrieve cookie metadata factory
              *
              * @deprecated 100.1.0
              * @return CookieMetadataFactory
              */
              private function getCookieMetadataFactory()

              if (!$this->cookieMetadataFactory)
              $this->cookieMetadataFactory = ObjectManager::getInstance()->get(CookieMetadataFactory::class);

              return $this->cookieMetadataFactory;


              /**
              * Customer logout action
              *
              * @return MagentoFrameworkControllerResultRedirect
              */
              public function execute()

              $lastCustomerId = $this->session->getId();
              $this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
              ->setLastCustomerId($lastCustomerId);
              if ($this->getCookieManager()->getCookie('mage-cache-sessid'))
              $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
              $metadata->setPath('/');
              $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);


              /** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
              $resultRedirect = $this->resultRedirectFactory->create();
              $resultRedirect->setPath('*/*/logoutSuccess');
              return $resultRedirect;




              This is the magento core logout functionality, we can use as per our wish. Just try.






              share|improve this answer



























                0














                It will work. Pro-grammatically logout customer on observer.



                <?php
                /**
                *
                * Copyright © Magento, Inc. All rights reserved.
                * See COPYING.txt for license details.
                */
                namespace VendorModuleNameObserver;

                use MagentoCustomerModelSession;
                use MagentoFrameworkAppActionContext;
                use MagentoFrameworkAppObjectManager;
                use MagentoFrameworkStdlibCookieCookieMetadataFactory;
                use MagentoFrameworkStdlibCookiePhpCookieManager;
                use MagentoFrameworkEventObserverInterface;

                class Logout implements ObserverInterface
                /**
                * @var Session
                */
                protected $session;

                /**
                * @var CookieMetadataFactory
                */
                private $cookieMetadataFactory;

                /**
                * @var PhpCookieManager
                */
                private $cookieMetadataManager;

                /**
                * @param Context $context
                * @param Session $customerSession
                */
                public function __construct(
                Context $context,
                Session $customerSession,
                CookieMetadataFactory $cookieMetadataManager
                )
                $this->session = $customerSession;
                $this->cookieMetadataManager = $cookieMetadataManager;
                parent::__construct($context);


                /**
                * Retrieve cookie manager
                *
                * @deprecated 100.1.0
                * @return PhpCookieManager
                */
                private function getCookieManager()

                if (!$this->cookieMetadataManager)
                $this->cookieMetadataManager = ObjectManager::getInstance()->get(PhpCookieManager::class);

                return $this->cookieMetadataManager;


                /**
                * Retrieve cookie metadata factory
                *
                * @deprecated 100.1.0
                * @return CookieMetadataFactory
                */
                private function getCookieMetadataFactory()

                if (!$this->cookieMetadataFactory)
                $this->cookieMetadataFactory = ObjectManager::getInstance()->get(CookieMetadataFactory::class);

                return $this->cookieMetadataFactory;


                /**
                * Customer logout action
                *
                * @return MagentoFrameworkControllerResultRedirect
                */
                public function execute()

                $lastCustomerId = $this->session->getId();
                $this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
                ->setLastCustomerId($lastCustomerId);
                if ($this->getCookieManager()->getCookie('mage-cache-sessid'))
                $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
                $metadata->setPath('/');
                $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);


                /** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
                $resultRedirect = $this->resultRedirectFactory->create();
                $resultRedirect->setPath('*/*/logoutSuccess');
                return $resultRedirect;




                This is the magento core logout functionality, we can use as per our wish. Just try.






                share|improve this answer

























                  0












                  0








                  0







                  It will work. Pro-grammatically logout customer on observer.



                  <?php
                  /**
                  *
                  * Copyright © Magento, Inc. All rights reserved.
                  * See COPYING.txt for license details.
                  */
                  namespace VendorModuleNameObserver;

                  use MagentoCustomerModelSession;
                  use MagentoFrameworkAppActionContext;
                  use MagentoFrameworkAppObjectManager;
                  use MagentoFrameworkStdlibCookieCookieMetadataFactory;
                  use MagentoFrameworkStdlibCookiePhpCookieManager;
                  use MagentoFrameworkEventObserverInterface;

                  class Logout implements ObserverInterface
                  /**
                  * @var Session
                  */
                  protected $session;

                  /**
                  * @var CookieMetadataFactory
                  */
                  private $cookieMetadataFactory;

                  /**
                  * @var PhpCookieManager
                  */
                  private $cookieMetadataManager;

                  /**
                  * @param Context $context
                  * @param Session $customerSession
                  */
                  public function __construct(
                  Context $context,
                  Session $customerSession,
                  CookieMetadataFactory $cookieMetadataManager
                  )
                  $this->session = $customerSession;
                  $this->cookieMetadataManager = $cookieMetadataManager;
                  parent::__construct($context);


                  /**
                  * Retrieve cookie manager
                  *
                  * @deprecated 100.1.0
                  * @return PhpCookieManager
                  */
                  private function getCookieManager()

                  if (!$this->cookieMetadataManager)
                  $this->cookieMetadataManager = ObjectManager::getInstance()->get(PhpCookieManager::class);

                  return $this->cookieMetadataManager;


                  /**
                  * Retrieve cookie metadata factory
                  *
                  * @deprecated 100.1.0
                  * @return CookieMetadataFactory
                  */
                  private function getCookieMetadataFactory()

                  if (!$this->cookieMetadataFactory)
                  $this->cookieMetadataFactory = ObjectManager::getInstance()->get(CookieMetadataFactory::class);

                  return $this->cookieMetadataFactory;


                  /**
                  * Customer logout action
                  *
                  * @return MagentoFrameworkControllerResultRedirect
                  */
                  public function execute()

                  $lastCustomerId = $this->session->getId();
                  $this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
                  ->setLastCustomerId($lastCustomerId);
                  if ($this->getCookieManager()->getCookie('mage-cache-sessid'))
                  $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
                  $metadata->setPath('/');
                  $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);


                  /** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
                  $resultRedirect = $this->resultRedirectFactory->create();
                  $resultRedirect->setPath('*/*/logoutSuccess');
                  return $resultRedirect;




                  This is the magento core logout functionality, we can use as per our wish. Just try.






                  share|improve this answer













                  It will work. Pro-grammatically logout customer on observer.



                  <?php
                  /**
                  *
                  * Copyright © Magento, Inc. All rights reserved.
                  * See COPYING.txt for license details.
                  */
                  namespace VendorModuleNameObserver;

                  use MagentoCustomerModelSession;
                  use MagentoFrameworkAppActionContext;
                  use MagentoFrameworkAppObjectManager;
                  use MagentoFrameworkStdlibCookieCookieMetadataFactory;
                  use MagentoFrameworkStdlibCookiePhpCookieManager;
                  use MagentoFrameworkEventObserverInterface;

                  class Logout implements ObserverInterface
                  /**
                  * @var Session
                  */
                  protected $session;

                  /**
                  * @var CookieMetadataFactory
                  */
                  private $cookieMetadataFactory;

                  /**
                  * @var PhpCookieManager
                  */
                  private $cookieMetadataManager;

                  /**
                  * @param Context $context
                  * @param Session $customerSession
                  */
                  public function __construct(
                  Context $context,
                  Session $customerSession,
                  CookieMetadataFactory $cookieMetadataManager
                  )
                  $this->session = $customerSession;
                  $this->cookieMetadataManager = $cookieMetadataManager;
                  parent::__construct($context);


                  /**
                  * Retrieve cookie manager
                  *
                  * @deprecated 100.1.0
                  * @return PhpCookieManager
                  */
                  private function getCookieManager()

                  if (!$this->cookieMetadataManager)
                  $this->cookieMetadataManager = ObjectManager::getInstance()->get(PhpCookieManager::class);

                  return $this->cookieMetadataManager;


                  /**
                  * Retrieve cookie metadata factory
                  *
                  * @deprecated 100.1.0
                  * @return CookieMetadataFactory
                  */
                  private function getCookieMetadataFactory()

                  if (!$this->cookieMetadataFactory)
                  $this->cookieMetadataFactory = ObjectManager::getInstance()->get(CookieMetadataFactory::class);

                  return $this->cookieMetadataFactory;


                  /**
                  * Customer logout action
                  *
                  * @return MagentoFrameworkControllerResultRedirect
                  */
                  public function execute()

                  $lastCustomerId = $this->session->getId();
                  $this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
                  ->setLastCustomerId($lastCustomerId);
                  if ($this->getCookieManager()->getCookie('mage-cache-sessid'))
                  $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
                  $metadata->setPath('/');
                  $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);


                  /** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
                  $resultRedirect = $this->resultRedirectFactory->create();
                  $resultRedirect->setPath('*/*/logoutSuccess');
                  return $resultRedirect;




                  This is the magento core logout functionality, we can use as per our wish. Just try.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Oct 31 '18 at 1:39









                  ManiMaran AManiMaran A

                  12614




                  12614



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Magento Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f192492%2fprogramatically-log-user-out-magento-2%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Sum ergo cogito? 1 nng

                      419 nièngy_Soadمي 19bal1.5o_g

                      Queiggey Chernihivv 9NnOo i Zw X QqKk LpB