How to Acquire Access Token for Integration in Magento 2

apimagento2oauth

In Magento2 when you create an integration, how do you get an Access Token? It seems OAuth is the recommended approach for a third-party service, per the documentation. Getting an Access Token is a prerequisite for making authenticated requests against the API.

Third-party applications authenticate with OAuth 1.0a.

Best Answer

Just starting out with Magento2 I found this to be pretty painful to figure out. It took me about half a day! To be fair, Magento has the appropriate documentation you need here...

The problem is it's very minimal. With my working knowledge of OAuth1 taken together with a gist of how to get an access token from Magento1 REST services I was finally able to pull it off. Details below!


1. Create a dedicated vhost (for the consumer application)

On my test environment, my Magento installation is installed at magev2.local, and I created a consumer application for purposes of obtaining an access token with the domain mage-access.local

2. Write a PHP file to interact with Magento (or use mine)

Here's the script I used (adapted from the gist I mentioned above). It uses the native PHP OAuth class, so you'll need to install that extension or swap some of this code out with your OAuth client library of choice.

<?php
//------------------------------
// Display an authorization page
//------------------------------
if($_SERVER['REQUEST_METHOD'] == 'GET') {
    file_put_contents('/tmp/redirectUrl', $_GET['success_call_back']);
?>
<html>
<head></head>
<body>
<form action="/oauth.php" method="post">
    <p>Click Authorize to get your app connected son!</p>
    <input type="hidden" name="authorized" value="yes"/>
    <input type="submit" value="Authorize"/>
</body>
<?php
} elseif($_SERVER['REQUEST_METHOD']) {
    //-----------------------------------
    // Capture OAuth info sent by Magento
    //-----------------------------------
    if(isset($_POST['oauth_consumer_key'])) {
        // Configuration
        $data['mageUrl']        = $_POST['store_base_url'];
        $data['consumerKey']    = $_POST['oauth_consumer_key'];
        $data['consumerSecret'] = $_POST['oauth_consumer_secret'];
        $data['verifier']       = $_POST['oauth_verifier'];
        file_put_contents('/tmp/oauth-info', serialize($data));
    }

    //---------------------------------------------
    // We have approval, let's get the access token
    //---------------------------------------------
    elseif(isset($_POST['authorized']) && $_POST['authorized'] == 'yes') {
        $data = unserialize(file_get_contents('/tmp/oauth-info'));
        $requestTokenRequestUrl = $data['mageUrl'] . 'oauth/token/request';
        $accessTokenRequestUrl  = $data['mageUrl'] . 'oauth/token/access';

        // Instantiate the OAuth client
        $oauthClient = new OAuth($data['consumerKey'], $data['consumerSecret']);

        try {
            // Fetch a request token and redirect to the magento site for authorization
            $requestToken = $oauthClient->getRequestToken($requestTokenRequestUrl);

            // Fetch an access token
            $oauthClient->setToken($requestToken['oauth_token'], $requestToken['oauth_token_secret']);
            $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl, null, $data['verifier']);

            // Redirect to Magento
            $redirectUrl = trim(file_get_contents('/tmp/redirectUrl'));
            unlink('/tmp/redirectUrl');
            unlink('/tmp/oauth-info');

            header('Location: ' . $redirectUrl);
        } catch (OAuthException $e) {
            ob_start();
            var_dump($e);
            $details = ob_get_clean();
            echo '<pre>';
            echo '<h2>Error Message</h2>';
            echo $e->getMessage();
            echo '<hr><h3>Details</h3>';
            echo $details;
            echo '</pre>';
        }
    }
}

3. Get your Access Token!

When you create your integration in the Magento2 admin, (substitute the domains you're using of course) use oauth.php on your shiny new consumer application for both the Callback URL and the Identity link URL, here's what mine looks like for my test environment

Sample OAuth Consumer Integration Configuration

I recommend using the Save & Activate option as shown in the image because it seems like Magento has a very short lifetime for the consumer token. I found if I didn't generate the access token immediately after provisioning the consumer, I'd get error messages about the consumer key being expired.

On the next screen ensure the permissions for your consumer are as you wish then click the Allow button. This loads a form from the oauth.php script asking for your authorization and simultaneously, Magento sends a POST request to oauth.php passing a temporary token from which you can procure request and access tokens.

All you have to do now is click the Authorize button and if everything works you'll have a shiny new access token! The list view of your integrations should now look like this

List view of authorized OAuth Consumer

and when you drill into the details, you'll see the access token

Authorized OAuth consumer with Access Token