Hands-on with token-based authentication

The crux of token-based authentication is as follows:

  • Client requests access with a username and password
  • Application validates credentials
  • Application provides a signed token to the client

The following code example demonstrates the console cURL REST-like request for the customer user:

curl -X POST "http://magento2.ce/rest/V1/integration/customer/token"
    -H "Content-Type:application/json"
    -d '{"username":"[email protected]", "password":"abc123"}'

The following code example demonstrates the PHP cURL REST-like request for the customer user:

$data = array('username' => '[email protected]', 'password' => 'abc123');
$data_string = json_encode($data);

$ch = curl_init('http://magento2.ce/rest/V1/integration /customer/token');
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);

The following code example demonstrates the console cURL SOAP-like request for the customer user:

curl -X POST -H 'Content-Type: application/soap+xml;
charset=utf-8; action= "integrationCustomerTokenServiceV1CreateCustomerAccessToken"'
-d @request.xml http://magento2.ce/index.php/soap/default?services= integrationCustomerTokenServiceV1

Notice the -d @request.xml part. Here, we are saying to the curl command to take the content of the request.xml file and pass it on as POST body data where the content of the request.xml file for the preceding curl command is defined as follows:

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="http://magento2.ce/index.php/soap/default? services=integrationCustomerTokenServiceV1">
    <env:Body>
        <ns1:integrationCustomerTokenServiceV1CreateCustomer AccessTokenRequest>
            <username>[email protected]</username>
            <password>abc123</password>
        </ns1:integrationCustomerTokenServiceV1CreateCustomer AccessTokenRequest>
    </env:Body>
</env:Envelope>

The following code example demonstrates the PHP cURL SOAP-like request for the customer user:

$data_string = file_get_contents('request.xml');

$ch = curl_init('http://magento2.ce/index.php/soap/default?services= integrationCustomerTokenServiceV1');
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/soap+xml; charset=utf-8; action="integrationCustomerTokenServiceV1 CreateCustomerAccessToken"',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);

The following code example demonstrates the usage of PHP SoapClient to make a Web API call:

$request = new SoapClient(
    'http://magento2.ce/index.php/soap/default?wsdl&services= integrationCustomerTokenServiceV1',
    array('soap_version' => SOAP_1_2, 'trace' => 1)
);

$token = $request->integrationCustomerTokenServiceV1Create CustomerAccessToken(array('username' => '[email protected]', 'password' => 'abc123'));

The API call for admin user authentication is nearly identical, and depends on which one of three approaches we take. The difference is merely in using https://magento2.ce/rest/V1/integration/admin/token as the endpoint URL in the case of REST, and using http://magento2.ce/index.php/soap/default?services=integrationCustomerTokenServiceV1. Additionally, for a SOAP call, we are calling integrationAdminTokenServiceV1CreateAdminAccessToken on the $request object.

In the case of successful authentication, for both the customer and admin API call, the response would be a random-looking 32-characters-long string that we call token. This token is further saved to the oauth_token table in the database, under the token column.

This might be a bit confusing with regard to what the oauth_token table has to do with token authentication.

Note

If we think about it, token-based authentication can be looked at as a simplified version of OAuth, where the user would authenticate using a username and password and then give the obtained time-expiring token to some third-party application to use it.

In the case of failed authentication, the server returns HTTP 401 Unauthorized, with a body containing a JSON message:

{"message":"Invalid login or password."}

Notice how we are able to call the API method, though we are not already authenticated? This means we must be calling an API defined by the anonymous type of resource. A quick look at the API endpoint gives us a hint as to the location of its definition. Looking under the vendor/magento/module-integration/etc/webapi.xml file, we can see the following (truncated) XML:

<route url="/V1/integration/admin/token" method="POST">
    <service class="MagentoIntegrationApiAdminTokenServiceInterface" method="createAdminAccessToken"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>
<route url="/V1/integration/customer/token" method="POST">
    <service class="MagentoIntegrationApi CustomerTokenServiceInterface" method="createCustomerAccessToken"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

We can clearly see how even token-based authentication itself is defined as API, using the anonymous resource so that everyone can access it. In a nutshell, token-based authentication is a feature of the MagentoIntegration module.

Now that we have our authentication token, we can start making other API calls. Remember, token simply means we have been authenticated against a given username and password. It does not mean we get full access to all Web API methods. This further depends on whether our customer or user has the proper access role.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.183.1