Magento 2 API – Get Token Authentication for Customer Logged with Facebook & Twitter

apimagento2rest

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.

Best 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 \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 .