Get Token Authentication For Customer Logged With Facebook & Twitter : Magento 2












3















Dears, I created a custom REST API, So customer can login Via facebook and twitter through mobile app. The API consists of one service which take some parameters and email parameter and check if this email is found or not.



-If found, then return customer id.



-If not found, then insert email and other parameters (firstname, lastname, socialid, socialtype).



My question, I don't save password for the customer because the response return from facebook doest not contain password, so how to get token authentication, so I can do all operations which request customer token?



In normal, I can login and get token through:



POST



 https://domain.com/index.php/rest/V1/integration/customer/token?username=test@gmail.com&password=12345


and response will be token.










share|improve this question

























  • How did you added the info returned from facebook to the database?. Which table?

    – Yomna Mansour
    Dec 23 '18 at 21:09













  • I used this plugin mageplaza.com/magento-2-social-login-extension

    – Jsparo30
    Dec 24 '18 at 10:01
















3















Dears, I created a custom REST API, So customer can login Via facebook and twitter through mobile app. The API consists of one service which take some parameters and email parameter and check if this email is found or not.



-If found, then return customer id.



-If not found, then insert email and other parameters (firstname, lastname, socialid, socialtype).



My question, I don't save password for the customer because the response return from facebook doest not contain password, so how to get token authentication, so I can do all operations which request customer token?



In normal, I can login and get token through:



POST



 https://domain.com/index.php/rest/V1/integration/customer/token?username=test@gmail.com&password=12345


and response will be token.










share|improve this question

























  • How did you added the info returned from facebook to the database?. Which table?

    – Yomna Mansour
    Dec 23 '18 at 21:09













  • I used this plugin mageplaza.com/magento-2-social-login-extension

    – Jsparo30
    Dec 24 '18 at 10:01














3












3








3


2






Dears, I created a custom REST API, So customer can login Via facebook and twitter through mobile app. The API consists of one service which take some parameters and email parameter and check if this email is found or not.



-If found, then return customer id.



-If not found, then insert email and other parameters (firstname, lastname, socialid, socialtype).



My question, I don't save password for the customer because the response return from facebook doest not contain password, so how to get token authentication, so I can do all operations which request customer token?



In normal, I can login and get token through:



POST



 https://domain.com/index.php/rest/V1/integration/customer/token?username=test@gmail.com&password=12345


and response will be token.










share|improve this question
















Dears, I created a custom REST API, So customer can login Via facebook and twitter through mobile app. The API consists of one service which take some parameters and email parameter and check if this email is found or not.



-If found, then return customer id.



-If not found, then insert email and other parameters (firstname, lastname, socialid, socialtype).



My question, I don't save password for the customer because the response return from facebook doest not contain password, so how to get token authentication, so I can do all operations which request customer token?



In normal, I can login and get token through:



POST



 https://domain.com/index.php/rest/V1/integration/customer/token?username=test@gmail.com&password=12345


and response will be token.







magento2 api rest






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 8 '18 at 9:39







Jsparo30

















asked May 22 '17 at 9:07









Jsparo30Jsparo30

6361624




6361624













  • How did you added the info returned from facebook to the database?. Which table?

    – Yomna Mansour
    Dec 23 '18 at 21:09













  • I used this plugin mageplaza.com/magento-2-social-login-extension

    – Jsparo30
    Dec 24 '18 at 10:01



















  • How did you added the info returned from facebook to the database?. Which table?

    – Yomna Mansour
    Dec 23 '18 at 21:09













  • I used this plugin mageplaza.com/magento-2-social-login-extension

    – Jsparo30
    Dec 24 '18 at 10:01

















How did you added the info returned from facebook to the database?. Which table?

– Yomna Mansour
Dec 23 '18 at 21:09







How did you added the info returned from facebook to the database?. Which table?

– Yomna Mansour
Dec 23 '18 at 21:09















I used this plugin mageplaza.com/magento-2-social-login-extension

– Jsparo30
Dec 24 '18 at 10:01





I used this plugin mageplaza.com/magento-2-social-login-extension

– Jsparo30
Dec 24 '18 at 10:01










3 Answers
3






active

oldest

votes


















3














What I understand from you question is, You have only email (and obviously some network specific secret key to validate i.e facebook key).



So You just need to load the customer by email id as below.



protected function getCustomerToken($emailId){
/**
* @var MagentoCustomerModelCustomer $customer */
*/
$customer->loadByEmail($emailId);
if($customer->getId()){
/**
* @var MagentoIntegrationModelOauthTokenFactory $tokenModelFactory
*/
$customerToken = $this->tokenModelFactory->create();
$tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
return $tokenKey;
}
return "YOU MSG FOR CUSTOMER NOT FOUND";
}


The above code should return the token key without password.



Note: Make sure you are doing proper & strong validating before generating the token & rest is already explained in Franck's answer .






share|improve this answer


























  • hi, i am getting this error message in response { "message": "A customer website ID must be specified when using the website scope." }

    – Ashar Riaz
    Dec 27 '17 at 12:21











  • @AsharRiaz the problem is MagentoCustomerModelResourceModelCustomer::loadByEmail, here its checking if website is associated with customer. May be the time customer was created account scope was global and later changed website.

    – Mohammad Mujassam
    Dec 28 '17 at 5:49











  • @MohammadMujassam i resolve this issue by adding $customer->setWebsiteId(1); before loadByEmail method

    – Ashar Riaz
    Dec 28 '17 at 10:43



















2














I think you need to pass the Facebook auth token in order to validate your customer.



Extend the native token authentication with your logic to validate the Facebook token.



Usefull information: https://stackoverflow.com/questions/4623974/design-for-facebook-authentication-in-an-ios-app-that-also-accesses-a-secured-we



The same approach can works with Twitter.



Extend or create your own API endpoint in order to manage FB / Twitter Login.



The native code for token generation is located here :



vendor/magento/module-integration/Model/CustomerTokenService.php:74



/**
* {@inheritdoc}
*/
public function createCustomerAccessToken($username, $password)
{
$this->validatorHelper->validate($username, $password);
$this->getRequestThrottler()->throttle($username, RequestThrottler::USER_TYPE_CUSTOMER);
try {
$customerDataObject = $this->accountManagement->authenticate($username, $password);
} catch (Exception $e) {
$this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_CUSTOMER);
throw new AuthenticationException(
__('You did not sign in correctly or your account is temporarily disabled.')
);
}
$this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_CUSTOMER);
return $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken();
}


Then you can modify the validation logic and the Magento customer ID retrieval in order to return a generated token.






share|improve this answer


























  • Thank you, Do you mean I call facebook auth token directly. As Ex, to get customer info, I call API : https://domain.com/index.php/rest/V1/cus tomers/me and Header Params: Authorization Bearer {{facebook auth token }} ??

    – Jsparo30
    May 22 '17 at 10:44











  • Not really. You can call the integration/customer/token API with username / FB token. Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token). If valid, then generate a native M2 Auth token for this user. Then use the M2 native token for the other native M2 API call.

    – Franck Garnier
    May 22 '17 at 10:52













  • Can you explain more with example? .. For integration/customer/token API with username / FB token which username ? magento 2 or facebook? .. Give more calarification for this part Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token).

    – Jsparo30
    May 22 '17 at 11:01











  • You need to create your custom API, retrieve the native code for integration/customer/token. Put your own logic to validate the FB login, then try to match the internal Magento customer and generate the Magento 2 token. Usefull native code here : MagentoIntegrationModelCustomerTokenService::createCustomerAccessToken

    – Franck Garnier
    May 24 '17 at 12:56











  • Open new question to have specific information about Magento 2

    – Franck Garnier
    May 27 '17 at 9:30



















0














If user is loggined



<?php


namespace TestModuleControllerTest;

use MagentoCustomerModelSession;
use MagentoFrameworkAppActionContext;


class Token extends MagentoCustomerControllerAbstractAccount
{
/**
* @var MagentoCustomerModelSession
*/
protected $_customerSession;

public function __construct(
Context $context,
Session $customerSession,
MagentoIntegrationModelOauthTokenFactory $tokenModelFactory
) {
$this->_customerSession = $customerSession;
$this->_tokenModelFactory = $tokenModelFactory;
parent::__construct(
$context
);
}

public function execute()
{
$customerId = $this->_customerSession->getCustomer()->getId();
$customerToken = $this->_tokenModelFactory->create();
echo "Customer-token=> ".$tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
}
}


If you need login without enter password



class AutoLoginManagement implements FloCoreApiAutoLoginManagementInterface
{

protected $_customer;
protected $_customerSession;
protected $_tokenModelFactory;

public function __construct(
MagentoIntegrationModelOauthTokenFactory $tokenModelFactory,
MagentoCustomerModelCustomer $customer,
MagentoCustomerModelSession $customerSession
)
{
$this->_customer = $customer;
$this->_customerSession = $customerSession;
$this->_tokenModelFactory = $tokenModelFactory;
}

public function postAutoLogin($data)
{

$objectManager = MagentoFrameworkAppObjectManager::getInstance();
// Load customer
$customer = $objectManager->create('MagentoCustomerModelCustomer')->load($data['customer_id']);

if(! $customer->getId()) {
return 'Not Found';
} else {
// Load customer session
$customerSession = $objectManager->create('MagentoCustomerModelSession');
$customerSession->setCustomerAsLoggedIn($customer);

$customerToken = $this->_tokenModelFactory->create();
$tokenKey = $customerToken->createCustomerToken($customer->getId())->getToken();
return $tokenKey;

}

}

private function getCustomerToken($customerId)
{
$customerToken = $this->tokenModelFactory->create();
$tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
return $tokenKey;
}
}




share























    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%2f175480%2fget-token-authentication-for-customer-logged-with-facebook-twitter-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









    3














    What I understand from you question is, You have only email (and obviously some network specific secret key to validate i.e facebook key).



    So You just need to load the customer by email id as below.



    protected function getCustomerToken($emailId){
    /**
    * @var MagentoCustomerModelCustomer $customer */
    */
    $customer->loadByEmail($emailId);
    if($customer->getId()){
    /**
    * @var MagentoIntegrationModelOauthTokenFactory $tokenModelFactory
    */
    $customerToken = $this->tokenModelFactory->create();
    $tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
    return $tokenKey;
    }
    return "YOU MSG FOR CUSTOMER NOT FOUND";
    }


    The above code should return the token key without password.



    Note: Make sure you are doing proper & strong validating before generating the token & rest is already explained in Franck's answer .






    share|improve this answer


























    • hi, i am getting this error message in response { "message": "A customer website ID must be specified when using the website scope." }

      – Ashar Riaz
      Dec 27 '17 at 12:21











    • @AsharRiaz the problem is MagentoCustomerModelResourceModelCustomer::loadByEmail, here its checking if website is associated with customer. May be the time customer was created account scope was global and later changed website.

      – Mohammad Mujassam
      Dec 28 '17 at 5:49











    • @MohammadMujassam i resolve this issue by adding $customer->setWebsiteId(1); before loadByEmail method

      – Ashar Riaz
      Dec 28 '17 at 10:43
















    3














    What I understand from you question is, You have only email (and obviously some network specific secret key to validate i.e facebook key).



    So You just need to load the customer by email id as below.



    protected function getCustomerToken($emailId){
    /**
    * @var MagentoCustomerModelCustomer $customer */
    */
    $customer->loadByEmail($emailId);
    if($customer->getId()){
    /**
    * @var MagentoIntegrationModelOauthTokenFactory $tokenModelFactory
    */
    $customerToken = $this->tokenModelFactory->create();
    $tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
    return $tokenKey;
    }
    return "YOU MSG FOR CUSTOMER NOT FOUND";
    }


    The above code should return the token key without password.



    Note: Make sure you are doing proper & strong validating before generating the token & rest is already explained in Franck's answer .






    share|improve this answer


























    • hi, i am getting this error message in response { "message": "A customer website ID must be specified when using the website scope." }

      – Ashar Riaz
      Dec 27 '17 at 12:21











    • @AsharRiaz the problem is MagentoCustomerModelResourceModelCustomer::loadByEmail, here its checking if website is associated with customer. May be the time customer was created account scope was global and later changed website.

      – Mohammad Mujassam
      Dec 28 '17 at 5:49











    • @MohammadMujassam i resolve this issue by adding $customer->setWebsiteId(1); before loadByEmail method

      – Ashar Riaz
      Dec 28 '17 at 10:43














    3












    3








    3







    What I understand from you question is, You have only email (and obviously some network specific secret key to validate i.e facebook key).



    So You just need to load the customer by email id as below.



    protected function getCustomerToken($emailId){
    /**
    * @var MagentoCustomerModelCustomer $customer */
    */
    $customer->loadByEmail($emailId);
    if($customer->getId()){
    /**
    * @var MagentoIntegrationModelOauthTokenFactory $tokenModelFactory
    */
    $customerToken = $this->tokenModelFactory->create();
    $tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
    return $tokenKey;
    }
    return "YOU MSG FOR CUSTOMER NOT FOUND";
    }


    The above code should return the token key without password.



    Note: Make sure you are doing proper & strong validating before generating the token & rest is already explained in Franck's answer .






    share|improve this answer















    What I understand from you question is, You have only email (and obviously some network specific secret key to validate i.e facebook key).



    So You just need to load the customer by email id as below.



    protected function getCustomerToken($emailId){
    /**
    * @var MagentoCustomerModelCustomer $customer */
    */
    $customer->loadByEmail($emailId);
    if($customer->getId()){
    /**
    * @var MagentoIntegrationModelOauthTokenFactory $tokenModelFactory
    */
    $customerToken = $this->tokenModelFactory->create();
    $tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
    return $tokenKey;
    }
    return "YOU MSG FOR CUSTOMER NOT FOUND";
    }


    The above code should return the token key without password.



    Note: Make sure you are doing proper & strong validating before generating the token & rest is already explained in Franck's answer .







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited May 30 '17 at 14:47

























    answered May 29 '17 at 9:50









    Mohammad MujassamMohammad Mujassam

    1,1271227




    1,1271227













    • hi, i am getting this error message in response { "message": "A customer website ID must be specified when using the website scope." }

      – Ashar Riaz
      Dec 27 '17 at 12:21











    • @AsharRiaz the problem is MagentoCustomerModelResourceModelCustomer::loadByEmail, here its checking if website is associated with customer. May be the time customer was created account scope was global and later changed website.

      – Mohammad Mujassam
      Dec 28 '17 at 5:49











    • @MohammadMujassam i resolve this issue by adding $customer->setWebsiteId(1); before loadByEmail method

      – Ashar Riaz
      Dec 28 '17 at 10:43



















    • hi, i am getting this error message in response { "message": "A customer website ID must be specified when using the website scope." }

      – Ashar Riaz
      Dec 27 '17 at 12:21











    • @AsharRiaz the problem is MagentoCustomerModelResourceModelCustomer::loadByEmail, here its checking if website is associated with customer. May be the time customer was created account scope was global and later changed website.

      – Mohammad Mujassam
      Dec 28 '17 at 5:49











    • @MohammadMujassam i resolve this issue by adding $customer->setWebsiteId(1); before loadByEmail method

      – Ashar Riaz
      Dec 28 '17 at 10:43

















    hi, i am getting this error message in response { "message": "A customer website ID must be specified when using the website scope." }

    – Ashar Riaz
    Dec 27 '17 at 12:21





    hi, i am getting this error message in response { "message": "A customer website ID must be specified when using the website scope." }

    – Ashar Riaz
    Dec 27 '17 at 12:21













    @AsharRiaz the problem is MagentoCustomerModelResourceModelCustomer::loadByEmail, here its checking if website is associated with customer. May be the time customer was created account scope was global and later changed website.

    – Mohammad Mujassam
    Dec 28 '17 at 5:49





    @AsharRiaz the problem is MagentoCustomerModelResourceModelCustomer::loadByEmail, here its checking if website is associated with customer. May be the time customer was created account scope was global and later changed website.

    – Mohammad Mujassam
    Dec 28 '17 at 5:49













    @MohammadMujassam i resolve this issue by adding $customer->setWebsiteId(1); before loadByEmail method

    – Ashar Riaz
    Dec 28 '17 at 10:43





    @MohammadMujassam i resolve this issue by adding $customer->setWebsiteId(1); before loadByEmail method

    – Ashar Riaz
    Dec 28 '17 at 10:43













    2














    I think you need to pass the Facebook auth token in order to validate your customer.



    Extend the native token authentication with your logic to validate the Facebook token.



    Usefull information: https://stackoverflow.com/questions/4623974/design-for-facebook-authentication-in-an-ios-app-that-also-accesses-a-secured-we



    The same approach can works with Twitter.



    Extend or create your own API endpoint in order to manage FB / Twitter Login.



    The native code for token generation is located here :



    vendor/magento/module-integration/Model/CustomerTokenService.php:74



    /**
    * {@inheritdoc}
    */
    public function createCustomerAccessToken($username, $password)
    {
    $this->validatorHelper->validate($username, $password);
    $this->getRequestThrottler()->throttle($username, RequestThrottler::USER_TYPE_CUSTOMER);
    try {
    $customerDataObject = $this->accountManagement->authenticate($username, $password);
    } catch (Exception $e) {
    $this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_CUSTOMER);
    throw new AuthenticationException(
    __('You did not sign in correctly or your account is temporarily disabled.')
    );
    }
    $this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_CUSTOMER);
    return $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken();
    }


    Then you can modify the validation logic and the Magento customer ID retrieval in order to return a generated token.






    share|improve this answer


























    • Thank you, Do you mean I call facebook auth token directly. As Ex, to get customer info, I call API : https://domain.com/index.php/rest/V1/cus tomers/me and Header Params: Authorization Bearer {{facebook auth token }} ??

      – Jsparo30
      May 22 '17 at 10:44











    • Not really. You can call the integration/customer/token API with username / FB token. Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token). If valid, then generate a native M2 Auth token for this user. Then use the M2 native token for the other native M2 API call.

      – Franck Garnier
      May 22 '17 at 10:52













    • Can you explain more with example? .. For integration/customer/token API with username / FB token which username ? magento 2 or facebook? .. Give more calarification for this part Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token).

      – Jsparo30
      May 22 '17 at 11:01











    • You need to create your custom API, retrieve the native code for integration/customer/token. Put your own logic to validate the FB login, then try to match the internal Magento customer and generate the Magento 2 token. Usefull native code here : MagentoIntegrationModelCustomerTokenService::createCustomerAccessToken

      – Franck Garnier
      May 24 '17 at 12:56











    • Open new question to have specific information about Magento 2

      – Franck Garnier
      May 27 '17 at 9:30
















    2














    I think you need to pass the Facebook auth token in order to validate your customer.



    Extend the native token authentication with your logic to validate the Facebook token.



    Usefull information: https://stackoverflow.com/questions/4623974/design-for-facebook-authentication-in-an-ios-app-that-also-accesses-a-secured-we



    The same approach can works with Twitter.



    Extend or create your own API endpoint in order to manage FB / Twitter Login.



    The native code for token generation is located here :



    vendor/magento/module-integration/Model/CustomerTokenService.php:74



    /**
    * {@inheritdoc}
    */
    public function createCustomerAccessToken($username, $password)
    {
    $this->validatorHelper->validate($username, $password);
    $this->getRequestThrottler()->throttle($username, RequestThrottler::USER_TYPE_CUSTOMER);
    try {
    $customerDataObject = $this->accountManagement->authenticate($username, $password);
    } catch (Exception $e) {
    $this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_CUSTOMER);
    throw new AuthenticationException(
    __('You did not sign in correctly or your account is temporarily disabled.')
    );
    }
    $this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_CUSTOMER);
    return $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken();
    }


    Then you can modify the validation logic and the Magento customer ID retrieval in order to return a generated token.






    share|improve this answer


























    • Thank you, Do you mean I call facebook auth token directly. As Ex, to get customer info, I call API : https://domain.com/index.php/rest/V1/cus tomers/me and Header Params: Authorization Bearer {{facebook auth token }} ??

      – Jsparo30
      May 22 '17 at 10:44











    • Not really. You can call the integration/customer/token API with username / FB token. Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token). If valid, then generate a native M2 Auth token for this user. Then use the M2 native token for the other native M2 API call.

      – Franck Garnier
      May 22 '17 at 10:52













    • Can you explain more with example? .. For integration/customer/token API with username / FB token which username ? magento 2 or facebook? .. Give more calarification for this part Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token).

      – Jsparo30
      May 22 '17 at 11:01











    • You need to create your custom API, retrieve the native code for integration/customer/token. Put your own logic to validate the FB login, then try to match the internal Magento customer and generate the Magento 2 token. Usefull native code here : MagentoIntegrationModelCustomerTokenService::createCustomerAccessToken

      – Franck Garnier
      May 24 '17 at 12:56











    • Open new question to have specific information about Magento 2

      – Franck Garnier
      May 27 '17 at 9:30














    2












    2








    2







    I think you need to pass the Facebook auth token in order to validate your customer.



    Extend the native token authentication with your logic to validate the Facebook token.



    Usefull information: https://stackoverflow.com/questions/4623974/design-for-facebook-authentication-in-an-ios-app-that-also-accesses-a-secured-we



    The same approach can works with Twitter.



    Extend or create your own API endpoint in order to manage FB / Twitter Login.



    The native code for token generation is located here :



    vendor/magento/module-integration/Model/CustomerTokenService.php:74



    /**
    * {@inheritdoc}
    */
    public function createCustomerAccessToken($username, $password)
    {
    $this->validatorHelper->validate($username, $password);
    $this->getRequestThrottler()->throttle($username, RequestThrottler::USER_TYPE_CUSTOMER);
    try {
    $customerDataObject = $this->accountManagement->authenticate($username, $password);
    } catch (Exception $e) {
    $this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_CUSTOMER);
    throw new AuthenticationException(
    __('You did not sign in correctly or your account is temporarily disabled.')
    );
    }
    $this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_CUSTOMER);
    return $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken();
    }


    Then you can modify the validation logic and the Magento customer ID retrieval in order to return a generated token.






    share|improve this answer















    I think you need to pass the Facebook auth token in order to validate your customer.



    Extend the native token authentication with your logic to validate the Facebook token.



    Usefull information: https://stackoverflow.com/questions/4623974/design-for-facebook-authentication-in-an-ios-app-that-also-accesses-a-secured-we



    The same approach can works with Twitter.



    Extend or create your own API endpoint in order to manage FB / Twitter Login.



    The native code for token generation is located here :



    vendor/magento/module-integration/Model/CustomerTokenService.php:74



    /**
    * {@inheritdoc}
    */
    public function createCustomerAccessToken($username, $password)
    {
    $this->validatorHelper->validate($username, $password);
    $this->getRequestThrottler()->throttle($username, RequestThrottler::USER_TYPE_CUSTOMER);
    try {
    $customerDataObject = $this->accountManagement->authenticate($username, $password);
    } catch (Exception $e) {
    $this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_CUSTOMER);
    throw new AuthenticationException(
    __('You did not sign in correctly or your account is temporarily disabled.')
    );
    }
    $this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_CUSTOMER);
    return $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken();
    }


    Then you can modify the validation logic and the Magento customer ID retrieval in order to return a generated token.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited May 24 '17 at 12:58

























    answered May 22 '17 at 9:37









    Franck GarnierFranck Garnier

    1,971825




    1,971825













    • Thank you, Do you mean I call facebook auth token directly. As Ex, to get customer info, I call API : https://domain.com/index.php/rest/V1/cus tomers/me and Header Params: Authorization Bearer {{facebook auth token }} ??

      – Jsparo30
      May 22 '17 at 10:44











    • Not really. You can call the integration/customer/token API with username / FB token. Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token). If valid, then generate a native M2 Auth token for this user. Then use the M2 native token for the other native M2 API call.

      – Franck Garnier
      May 22 '17 at 10:52













    • Can you explain more with example? .. For integration/customer/token API with username / FB token which username ? magento 2 or facebook? .. Give more calarification for this part Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token).

      – Jsparo30
      May 22 '17 at 11:01











    • You need to create your custom API, retrieve the native code for integration/customer/token. Put your own logic to validate the FB login, then try to match the internal Magento customer and generate the Magento 2 token. Usefull native code here : MagentoIntegrationModelCustomerTokenService::createCustomerAccessToken

      – Franck Garnier
      May 24 '17 at 12:56











    • Open new question to have specific information about Magento 2

      – Franck Garnier
      May 27 '17 at 9:30



















    • Thank you, Do you mean I call facebook auth token directly. As Ex, to get customer info, I call API : https://domain.com/index.php/rest/V1/cus tomers/me and Header Params: Authorization Bearer {{facebook auth token }} ??

      – Jsparo30
      May 22 '17 at 10:44











    • Not really. You can call the integration/customer/token API with username / FB token. Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token). If valid, then generate a native M2 Auth token for this user. Then use the M2 native token for the other native M2 API call.

      – Franck Garnier
      May 22 '17 at 10:52













    • Can you explain more with example? .. For integration/customer/token API with username / FB token which username ? magento 2 or facebook? .. Give more calarification for this part Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token).

      – Jsparo30
      May 22 '17 at 11:01











    • You need to create your custom API, retrieve the native code for integration/customer/token. Put your own logic to validate the FB login, then try to match the internal Magento customer and generate the Magento 2 token. Usefull native code here : MagentoIntegrationModelCustomerTokenService::createCustomerAccessToken

      – Franck Garnier
      May 24 '17 at 12:56











    • Open new question to have specific information about Magento 2

      – Franck Garnier
      May 27 '17 at 9:30

















    Thank you, Do you mean I call facebook auth token directly. As Ex, to get customer info, I call API : https://domain.com/index.php/rest/V1/cus tomers/me and Header Params: Authorization Bearer {{facebook auth token }} ??

    – Jsparo30
    May 22 '17 at 10:44





    Thank you, Do you mean I call facebook auth token directly. As Ex, to get customer info, I call API : https://domain.com/index.php/rest/V1/cus tomers/me and Header Params: Authorization Bearer {{facebook auth token }} ??

    – Jsparo30
    May 22 '17 at 10:44













    Not really. You can call the integration/customer/token API with username / FB token. Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token). If valid, then generate a native M2 Auth token for this user. Then use the M2 native token for the other native M2 API call.

    – Franck Garnier
    May 22 '17 at 10:52







    Not really. You can call the integration/customer/token API with username / FB token. Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token). If valid, then generate a native M2 Auth token for this user. Then use the M2 native token for the other native M2 API call.

    – Franck Garnier
    May 22 '17 at 10:52















    Can you explain more with example? .. For integration/customer/token API with username / FB token which username ? magento 2 or facebook? .. Give more calarification for this part Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token).

    – Jsparo30
    May 22 '17 at 11:01





    Can you explain more with example? .. For integration/customer/token API with username / FB token which username ? magento 2 or facebook? .. Give more calarification for this part Then extend the native call to check if the FB token is valid for this user. (FB user ID / FB token).

    – Jsparo30
    May 22 '17 at 11:01













    You need to create your custom API, retrieve the native code for integration/customer/token. Put your own logic to validate the FB login, then try to match the internal Magento customer and generate the Magento 2 token. Usefull native code here : MagentoIntegrationModelCustomerTokenService::createCustomerAccessToken

    – Franck Garnier
    May 24 '17 at 12:56





    You need to create your custom API, retrieve the native code for integration/customer/token. Put your own logic to validate the FB login, then try to match the internal Magento customer and generate the Magento 2 token. Usefull native code here : MagentoIntegrationModelCustomerTokenService::createCustomerAccessToken

    – Franck Garnier
    May 24 '17 at 12:56













    Open new question to have specific information about Magento 2

    – Franck Garnier
    May 27 '17 at 9:30





    Open new question to have specific information about Magento 2

    – Franck Garnier
    May 27 '17 at 9:30











    0














    If user is loggined



    <?php


    namespace TestModuleControllerTest;

    use MagentoCustomerModelSession;
    use MagentoFrameworkAppActionContext;


    class Token extends MagentoCustomerControllerAbstractAccount
    {
    /**
    * @var MagentoCustomerModelSession
    */
    protected $_customerSession;

    public function __construct(
    Context $context,
    Session $customerSession,
    MagentoIntegrationModelOauthTokenFactory $tokenModelFactory
    ) {
    $this->_customerSession = $customerSession;
    $this->_tokenModelFactory = $tokenModelFactory;
    parent::__construct(
    $context
    );
    }

    public function execute()
    {
    $customerId = $this->_customerSession->getCustomer()->getId();
    $customerToken = $this->_tokenModelFactory->create();
    echo "Customer-token=> ".$tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
    }
    }


    If you need login without enter password



    class AutoLoginManagement implements FloCoreApiAutoLoginManagementInterface
    {

    protected $_customer;
    protected $_customerSession;
    protected $_tokenModelFactory;

    public function __construct(
    MagentoIntegrationModelOauthTokenFactory $tokenModelFactory,
    MagentoCustomerModelCustomer $customer,
    MagentoCustomerModelSession $customerSession
    )
    {
    $this->_customer = $customer;
    $this->_customerSession = $customerSession;
    $this->_tokenModelFactory = $tokenModelFactory;
    }

    public function postAutoLogin($data)
    {

    $objectManager = MagentoFrameworkAppObjectManager::getInstance();
    // Load customer
    $customer = $objectManager->create('MagentoCustomerModelCustomer')->load($data['customer_id']);

    if(! $customer->getId()) {
    return 'Not Found';
    } else {
    // Load customer session
    $customerSession = $objectManager->create('MagentoCustomerModelSession');
    $customerSession->setCustomerAsLoggedIn($customer);

    $customerToken = $this->_tokenModelFactory->create();
    $tokenKey = $customerToken->createCustomerToken($customer->getId())->getToken();
    return $tokenKey;

    }

    }

    private function getCustomerToken($customerId)
    {
    $customerToken = $this->tokenModelFactory->create();
    $tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
    return $tokenKey;
    }
    }




    share




























      0














      If user is loggined



      <?php


      namespace TestModuleControllerTest;

      use MagentoCustomerModelSession;
      use MagentoFrameworkAppActionContext;


      class Token extends MagentoCustomerControllerAbstractAccount
      {
      /**
      * @var MagentoCustomerModelSession
      */
      protected $_customerSession;

      public function __construct(
      Context $context,
      Session $customerSession,
      MagentoIntegrationModelOauthTokenFactory $tokenModelFactory
      ) {
      $this->_customerSession = $customerSession;
      $this->_tokenModelFactory = $tokenModelFactory;
      parent::__construct(
      $context
      );
      }

      public function execute()
      {
      $customerId = $this->_customerSession->getCustomer()->getId();
      $customerToken = $this->_tokenModelFactory->create();
      echo "Customer-token=> ".$tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
      }
      }


      If you need login without enter password



      class AutoLoginManagement implements FloCoreApiAutoLoginManagementInterface
      {

      protected $_customer;
      protected $_customerSession;
      protected $_tokenModelFactory;

      public function __construct(
      MagentoIntegrationModelOauthTokenFactory $tokenModelFactory,
      MagentoCustomerModelCustomer $customer,
      MagentoCustomerModelSession $customerSession
      )
      {
      $this->_customer = $customer;
      $this->_customerSession = $customerSession;
      $this->_tokenModelFactory = $tokenModelFactory;
      }

      public function postAutoLogin($data)
      {

      $objectManager = MagentoFrameworkAppObjectManager::getInstance();
      // Load customer
      $customer = $objectManager->create('MagentoCustomerModelCustomer')->load($data['customer_id']);

      if(! $customer->getId()) {
      return 'Not Found';
      } else {
      // Load customer session
      $customerSession = $objectManager->create('MagentoCustomerModelSession');
      $customerSession->setCustomerAsLoggedIn($customer);

      $customerToken = $this->_tokenModelFactory->create();
      $tokenKey = $customerToken->createCustomerToken($customer->getId())->getToken();
      return $tokenKey;

      }

      }

      private function getCustomerToken($customerId)
      {
      $customerToken = $this->tokenModelFactory->create();
      $tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
      return $tokenKey;
      }
      }




      share


























        0












        0








        0







        If user is loggined



        <?php


        namespace TestModuleControllerTest;

        use MagentoCustomerModelSession;
        use MagentoFrameworkAppActionContext;


        class Token extends MagentoCustomerControllerAbstractAccount
        {
        /**
        * @var MagentoCustomerModelSession
        */
        protected $_customerSession;

        public function __construct(
        Context $context,
        Session $customerSession,
        MagentoIntegrationModelOauthTokenFactory $tokenModelFactory
        ) {
        $this->_customerSession = $customerSession;
        $this->_tokenModelFactory = $tokenModelFactory;
        parent::__construct(
        $context
        );
        }

        public function execute()
        {
        $customerId = $this->_customerSession->getCustomer()->getId();
        $customerToken = $this->_tokenModelFactory->create();
        echo "Customer-token=> ".$tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
        }
        }


        If you need login without enter password



        class AutoLoginManagement implements FloCoreApiAutoLoginManagementInterface
        {

        protected $_customer;
        protected $_customerSession;
        protected $_tokenModelFactory;

        public function __construct(
        MagentoIntegrationModelOauthTokenFactory $tokenModelFactory,
        MagentoCustomerModelCustomer $customer,
        MagentoCustomerModelSession $customerSession
        )
        {
        $this->_customer = $customer;
        $this->_customerSession = $customerSession;
        $this->_tokenModelFactory = $tokenModelFactory;
        }

        public function postAutoLogin($data)
        {

        $objectManager = MagentoFrameworkAppObjectManager::getInstance();
        // Load customer
        $customer = $objectManager->create('MagentoCustomerModelCustomer')->load($data['customer_id']);

        if(! $customer->getId()) {
        return 'Not Found';
        } else {
        // Load customer session
        $customerSession = $objectManager->create('MagentoCustomerModelSession');
        $customerSession->setCustomerAsLoggedIn($customer);

        $customerToken = $this->_tokenModelFactory->create();
        $tokenKey = $customerToken->createCustomerToken($customer->getId())->getToken();
        return $tokenKey;

        }

        }

        private function getCustomerToken($customerId)
        {
        $customerToken = $this->tokenModelFactory->create();
        $tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
        return $tokenKey;
        }
        }




        share













        If user is loggined



        <?php


        namespace TestModuleControllerTest;

        use MagentoCustomerModelSession;
        use MagentoFrameworkAppActionContext;


        class Token extends MagentoCustomerControllerAbstractAccount
        {
        /**
        * @var MagentoCustomerModelSession
        */
        protected $_customerSession;

        public function __construct(
        Context $context,
        Session $customerSession,
        MagentoIntegrationModelOauthTokenFactory $tokenModelFactory
        ) {
        $this->_customerSession = $customerSession;
        $this->_tokenModelFactory = $tokenModelFactory;
        parent::__construct(
        $context
        );
        }

        public function execute()
        {
        $customerId = $this->_customerSession->getCustomer()->getId();
        $customerToken = $this->_tokenModelFactory->create();
        echo "Customer-token=> ".$tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
        }
        }


        If you need login without enter password



        class AutoLoginManagement implements FloCoreApiAutoLoginManagementInterface
        {

        protected $_customer;
        protected $_customerSession;
        protected $_tokenModelFactory;

        public function __construct(
        MagentoIntegrationModelOauthTokenFactory $tokenModelFactory,
        MagentoCustomerModelCustomer $customer,
        MagentoCustomerModelSession $customerSession
        )
        {
        $this->_customer = $customer;
        $this->_customerSession = $customerSession;
        $this->_tokenModelFactory = $tokenModelFactory;
        }

        public function postAutoLogin($data)
        {

        $objectManager = MagentoFrameworkAppObjectManager::getInstance();
        // Load customer
        $customer = $objectManager->create('MagentoCustomerModelCustomer')->load($data['customer_id']);

        if(! $customer->getId()) {
        return 'Not Found';
        } else {
        // Load customer session
        $customerSession = $objectManager->create('MagentoCustomerModelSession');
        $customerSession->setCustomerAsLoggedIn($customer);

        $customerToken = $this->_tokenModelFactory->create();
        $tokenKey = $customerToken->createCustomerToken($customer->getId())->getToken();
        return $tokenKey;

        }

        }

        private function getCustomerToken($customerId)
        {
        $customerToken = $this->tokenModelFactory->create();
        $tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
        return $tokenKey;
        }
        }





        share











        share


        share










        answered 57 secs ago









        Amir HosseinzadehAmir Hosseinzadeh

        1013




        1013






























            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%2f175480%2fget-token-authentication-for-customer-logged-with-facebook-twitter-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

            Polycentropodidae

            Magento 2 Error message: Invalid state change requested

            Paulmy