Programmatically: How to create custom Magento REST API authentication
Step 1: Create a new module
Create a new directory for your module in app/code and create the following files: ModuleName.xml (in app/code/ModuleName/etc) Module.php (in app/code/ModuleName/Module.php) etc/api.xml (in app/code/ModuleName/etc/api.xml) etc/auth.xml (in app/code/ModuleName/etc/auth.xml)
Step 2: Configure the module
In ModuleName.xml, add the following code:
<?xml version="1.0"?>
<config>
<modules>
<ModuleName>
<codePool>local</codePool>
<version>1.0.0</version>
</ModuleName>
</modules>
</config>
Step 3: Create the API
In etc/api.xml, add the following code:
<?xml version="1.0"?>
<api>
<resources>
<resource alias="moduleName" />
</resources>
<acl>
<resources>
<resource alias="moduleName" />
</resources>
</acl>
</api>
Step 4: Implement the authentication logic
In Module.php, add the following code:
use Magento\Framework\REST\AuthenticationInterface;
use Magento\Framework\REST\AuthenticationInterfaceFactory;
use Magento\Framework\HTTP\Header;
class Module extends \Magento\Framework AppModule
{
// ...
public function getAuthentication()
{
$auth = new \ModuleName\Auth();
return $auth;
}
}
Step 5: Create the authentication class
In etc/auth.xml, add the following code:
<?xml version="1.0"?>
<config>
<modules>
<ModuleName_auth>
<active>true</active>
<class>Module_NameAuth</class>
</ModuleName_auth>
</modules>
</config>
In Module/Auth.php, add the following code:
class Module\Auth implements AuthenticationInterface
{
public function authenticate($username, $password)
{
// Custom authentication logic here
// For example, you could check against a custom database table or a external service
if ($username === 'myuser' && $password === 'mypassword') {
return new \stdClass();
}
return null;
}
}
Step 6: Register the authentication class
In Module.php, add the following code:
public function registerAuthentication()
{
$this->getAuthenticationInterfaceFactory()->register('moduleName', 'Module_NameAuth');
}
Step 7: Test the authentication
To test the authentication, you can use a tool like curl or a REST client like Postman. Send a request to http://your-magento-url/index.php/rest/V1/integration/customer/token with the following headers:
Authorization: Bearer YOUR_API_KEY Content-Type: application/json
And in the request body, provide the following JSON:
{
"username": "myuser",
"password": "mypassword"
}