Programatically Log User Out [Magento 2]Logout 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” valueHow to get old id of customer group in observer (Magento 2)Magento 2.1 - User Group Registration FormMagento 2 - Redirect to Account Dashboard During Checkout Funnel LoginHow Do You Invalidate Customer Data In Magento 2?Recently viewed products not showing for NOT LOGGED CUSTOMERS in magento 2Magento 2 Customer and admin users are getting logged out frequently

Does a code snippet compile? Or does it gets compiled?

Can an SPI slave start a transmission in full-duplex mode?

Why should public servants be apolitical?

Dereferencing a pointer in a for loop initializer creates a seg fault

Can I call myself an assistant professor without a PhD

Double blind peer review when paper cites author's GitHub repo for code

Acceptable to cut steak before searing?

Is The Lion King live action film made in motion capture?

SQL Minimum Row count

Is this cheap "air conditioner" able to cool a room?

Looking for a new job because of relocation - is it okay to tell the real reason?

How can I tell if a flight itinerary is fake?

In a topological space if there exists a loop that cannot be contracted to a point does there exist a simple loop that cannot be contracted also?

Does the United States guarantee any unique freedoms?

Short story about a teenager who has his brain replaced with a microchip (Psychological Horror)

What happen if I gain the control of aura that enchants an opponent's creature? Would the aura stay attached?

Ex-contractor published company source code and secrets online

How to mark beverage cans in a cooler for a blind person?

Why are the inside diameters of some pipe larger than the stated size?

Does this smartphone photo show Mars just below the Sun?

Pretty heat maps

How do I explain to a team that the project they will work on for six months will 100% fail?

Generator for parity?

Use of "When" in present vs "whenever"



Programatically Log User Out [Magento 2]


Logout 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” valueHow to get old id of customer group in observer (Magento 2)Magento 2.1 - User Group Registration FormMagento 2 - Redirect to Account Dashboard During Checkout Funnel LoginHow Do You Invalidate Customer Data In Magento 2?Recently viewed products not showing for NOT LOGGED CUSTOMERS in magento 2Magento 2 Customer and admin users are getting logged out frequently






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








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


























  • 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


























  • 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

62.8k16 gold badges84 silver badges183 bronze badges




62.8k16 gold badges84 silver badges183 bronze badges










asked Sep 8 '17 at 7:50









CreativeNerdSamCreativeNerdSam

438 bronze badges




438 bronze badges















  • 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

      1,0921 gold badge9 silver badges31 bronze badges




      1,0921 gold badge9 silver badges31 bronze badges















      • 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

          15910 bronze badges




          15910 bronze badges
























              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

                  3163 silver badges5 bronze badges




                  3163 silver badges5 bronze badges






























                      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

                      Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

                      Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                      Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form