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

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 \Magento\Customer\Model\Customer $customer */
*/
$customer->loadByEmail($emailId);
if($customer->getId()){
        /**
        * @var \Magento\Integration\Model\Oauth\TokenFactory $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 .


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.

Tags:

Rest

Api

Magento2